✅ 500. 键盘行

https://leetcode-cn.com/problems/keyboard-row

描述

给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。键盘就是你的键盘那样,自己看看。

示例:

输入: ["Hello", "Alaska", "Dad", "Peace"]

输出: ["Alaska", "Dad"]

解答

  • 思路: 构造三个 array

a1 a2 a3

检查每个单词第一个字符在 aX 里:

检查 每个单词2到最后的字符,在aX里面不

是则 留下

否则 不留下

最后打印出来 留下的 所有单词

  • c
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
char ** findWords(char ** words, int wordsSize, int* returnSize){
int arr[26] = {1, 2, 2, 1, 0, 1, 1, 1, 0, 1, 1, 1, 2, 2, 0, 0, 0, 0, 1, 0, 0, 2, 0, 2, 0, 2};
int i,j =0, flag = 0, pos;
char **ret = (char**) malloc(sizeof(char*) * wordsSize);//tt wordsSize is
char c;
*returnSize = 0;//ret is the one to be returned, and C need to know
// how long ret is(how many words will be, aka how many rows),
// so here is returnSize's usage.
for(i = 0; i < wordsSize; i++){
c = tolower(words[i][j]);//we must need tolower()
pos = arr[c - 'a'];
while(words[i][j] != NULL){
c = tolower(words[i][j]);
if(arr[c - 'a'] != pos) {
flag = 1;// flag it as NOT OK;
break;// break `while`
}
j++;
}
j = 0;
if(flag == 0){
//means OK, they are all in one line
ret[*returnSize] = words[i];
(*returnSize)++;//wrong: *returnSize++
}
flag = 0;
}
return ret;
} /*执行用时 :
4 ms
, 在所有 C 提交中击败了
62.05%
的用户
内存消耗 :
7 MB
, 在所有 C 提交中击败了
10.67%
的用户*/
  • py

api知识点:

s.issubset(t)
s <= t
测试是否 s 中的每一个元素都在 t 中


class Solution:
def findWords(self, words: List[str]) -> List[str]:
set1 = set('qwertyuiop')
set2 = set('asdfghjkl')
set3 = set('zxcvbnm')
ret = []
for word in words:
low_word = word.lower()
setForWord = set(low_word)
if setForWord.issubset(set1) or setForWord.issubset(set2) or setForWord.issubset(set3):
ret.append(word) return ret '''执行用时 :
32 ms
, 在所有 Python3 提交中击败了
71.28%
的用户
内存消耗 :
13.2 MB
, 在所有 Python3 提交中击败了
40.92%
的用户'''

✅ 905. 按奇偶排序数组

https://leetcode-cn.com/problems/sort-array-by-parity

描述

给定一个非负整数数组 A,返回一个数组,在该数组中, A 的所有偶数元素之后跟着所有奇数元素。

你可以返回满足此条件的任何数组作为答案。

解答

  • 思路

排序,需要循环,判断比较,交换。本题对排序算法的排序条件的掌握,将常规排序条件从比大小变为判断奇偶。

  • 他人c思路

c语言,双指针,遍历一次,偶数从数组的头开始插入,奇数从数组的尾部开始插入,当插入的最后一个偶数元素的索引大于最后一个奇数的索引值是,跳出循环,最后返回数组。

/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* sortArrayByParity(int* A, int ASize, int* returnSize){
int *result = (int *) calloc (ASize, sizeof(int));
int evenSoldier = 0;
int oddSoldier = ASize - 1;
(*returnSize) = ASize;
for(int i = 0; i < ASize; i++){
if(A[i] % 2 == 0){
//even insert first
result[evenSoldier] = A[i];
evenSoldier++;
}
else{
//odd insert last
result[oddSoldier] = A[i];
oddSoldier--;
}
if(evenSoldier > oddSoldier){
break;//思考一下todo 0209,为什么当插入的最后一个偶数元素的索引大于最后一个奇数的索引值是,跳出循环
}
}
return result;
}
todo 0209 并且一起思考,能不能不用额外 的 result 数组呢?
'''
执行用时 :
60 ms
, 在所有 C 提交中击败了
12.74%
的用户
内存消耗 :
10.4 MB
, 在所有 C 提交中击败了
39.11%
的用户'''
  • java
class Solution {
public int[] sortArrayByParity(int[] A) {
if(A == null || A.length == 1){
return A;
}
int left = 0;
int right = A.length - 1;
int tmp;
while(left < right) {
if((A[left] & 1) == 1 && (A[right] & 1) == 0){
tmp = A[left];
A[left] = A[right];
A[right] = tmp;
} else if ((A[left] & 1) == 0) {
//left is even, is fine, so we jst move forward
left++;
} else if ((A[right] & 1) == 1) {//一定要 给 A[right] & 1 加括号!!!or 语法优先级错误!
//right is odd ,is ok, so we jst move backward
right--;
}
}
return A;
}
}
/*
执行用时 :
1 ms
, 在所有 Java 提交中击败了
100.00%
的用户
内存消耗 :
40.7 MB
, 在所有 Java 提交中击败了
34.85%
的用户*/
  • py
class Solution:
def sortArrayByParity(self, A: List[int]) -> List[int]:
return sorted(A, key=lambda x: 0 if x % 2 == 0 else 1) '''
执行用时 :
88 ms
, 在所有 Python3 提交中击败了
77.49%
的用户
内存消耗 :
13.9 MB
, 在所有 Python3 提交中击败了
53.87%
的用户
'''

py sorted 参数详解

https://www.jb51.net/article/147635.htm

one. basic

# 1、对列表排序,返回的对象不会改变原列表

list = [1,5,7,2,4]

sorted(list)
Out[87]: [1, 2, 4, 5, 7]
#可以设定时候排序方式,默认从小到大,设定reverse = False 可以从大到小
sorted(list,reverse=False)
Out[88]: [1, 2, 4, 5, 7] sorted(list,reverse=True)
Out[89]: [7, 5, 4, 2, 1]

two. 可以根据自定义规则来排序,使用参数:key

# 使用key,默认搭配lambda函数使用

sorted(chars,key=lambda x:len(x))
Out[92]: ['a', 'is', 'boy', 'bruce', 'handsome'] sorted(chars,key=lambda x:len(x),reverse= True)
Out[93]: ['handsome', 'bruce', 'boy', 'is', 'a']

three. 根据自定义规则来排序,对元组构成的列表进行排序

tuple_list = [('A', 1,5), ('B', 3,2), ('C', 2,6)]
#key=lambda x: x[1]中可以任意选定x中可选的位置进行排序
sorted(tuple_list, key=lambda x: x[1]) Out[94]: [('A', 1, 5), ('C', 2, 6), ('B', 3, 2)] sorted(tuple_list, key=lambda x: x[0])
Out[95]: [('A', 1, 5), ('B', 3, 2), ('C', 2, 6)] sorted(tuple_list, key=lambda x: x[2])
Out[96]: [('B', 3, 2), ('A', 1, 5), ('C', 2, 6)]

four. 排序的元素是自定义类

class tuple_list:
def __init__(self, one, two, three):
self.one = one
self.two = two
self.three = three
def __repr__(self):
return repr((self.one, self.two, self.three)) tuple_list_ = [tuple_list('A', 1,5), tuple_list('B', 3,2), tuple_list('C', 2,6)] sorted(tuple_list_, key=lambda x: x.one)
Out[104]: [('A', 1, 5), ('B', 3, 2), ('C', 2, 6)] sorted(tuple_list_, key=lambda x: x.two)
Out[105]: [('A', 1, 5), ('C', 2, 6), ('B', 3, 2)] sorted(tuple_list_, key=lambda x: x.three)
Out[106]: [('B', 3, 2), ('A', 1, 5), ('C', 2, 6)]

✅ 559. N叉树的最大深度

https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree

描述

给定一个 N 叉树,找到其最大深度。

最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。

例如,给定一个 3叉树 :

            1
/ | \
3 2 4
/ \
5 6

我们应返回其最大深度,3。

说明:

树的深度不会超过 1000。

树的节点总不会超过 5000。

解答

第一种想法是DFS递归写法求N叉树的深度。第二种想法是层序遍历N叉树求N叉树深度。

java

dfs-like method(recursive)

/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children; public Node() {} public Node(int _val) {
val = _val;
} public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public int maxDepth(Node root) {
//dfs like way
if(root == null) {
return 0;
}
int depth = 0;
for (int i = 0;i < root.children.size(); i++) {
depth = Math.max(depth, maxDepth(root.children.get(i)));
}
return depth + 1;
}
} '''执行用时 :
1 ms
, 在所有 Java 提交中击败了
87.14%
的用户
内存消耗 :
39.8 MB
, 在所有 Java 提交中击败了
33.95%
的用户'''

层序遍历

/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children; public Node() {} public Node(int _val) {
val = _val;
} public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public int maxDepth(Node root) {
//层序
if(root == null) return 0;
if(root.children.size() == 0) return 1;
int depth = 0;
Queue<Node> q = new LinkedList<Node>();
q.offer(root);
while(!q.isEmpty()){
int qSize = q.size();
depth++;
while(qSize > 0) {
Node node = q.poll();
if(node.children.size() != 0) {
q.addAll(node.children);
}
qSize--;
}
}
return depth;
}
} /*执行用时 :
2 ms
, 在所有 Java 提交中击败了
35.68%
的用户
内存消耗 :
39.7 MB
, 在所有 Java 提交中击败了
38.10%
的用户*/

✅ 349. 两个数组的交集

https://leetcode-cn.com/problems/intersection-of-two-arrays

描述

给定两个数组,编写一个函数来计算它们的交集。

示例 1:
输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2] 示例 2: 输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [9,4]

说明:

输出结果中的每个元素一定是唯一的。

我们可以不考虑输出结果的顺序。

解答

  • set api in java or py or c++ ; no c solution?

use set


class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set = new HashSet<>();
//使用 hashMap 的key 唯一性质,来实现set 性质
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums1.length; i++) {
map.put(nums1[i], 10);//whatever 10 is, dont care
}
for(int j = 0; j < nums2.length; j++) {
if(map.containsKey(nums2[j])){
set.add(nums2[j]);
}
}
int [] ret = new int[set.size()];
Iterator it = set.iterator();
int k = 0;
while(it.hasNext()){
ret[k++] = (int) it.next();
}
return ret;
}
} /*执行用时 :
3 ms
, 在所有 Java 提交中击败了
95.89%
的用户
内存消耗 :
37.2 MB
, 在所有 Java 提交中击败了
12.95%
的用户*/

他人c解答


#include <stdlib.h>
int cmp ( const void *a , const void *b )
{
return *(int *)a - *(int *)b;
}
int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize){
if(nums1Size==0 || nums2Size==0){
*returnSize = 0;
return 0;
} int max = (nums1Size>nums2Size) ? nums1Size : nums2Size; int* bot = (int*)malloc(sizeof(int)*max);
int i, j, k = 0, u, z = 1;
for(i = 0; i < nums1Size; i++){
for(j = 0; j < nums2Size; j++)
if(nums1[i]==nums2[j]){
bot[k++] = nums1[i];
continue;
}
} if(k==0){
*returnSize = 0;
return 0;
} // 对u排序
qsort(bot,k,sizeof(bot[0]),cmp);
//tt todo 0209 这个 for 是为了什么?
for(u = 1; u < k; u++){
if(bot[z-1]==bot[u]) continue;
else bot[z++] = bot[u];
} *returnSize = z;
return bot;
} 作者:logan-31
链接:https://leetcode-cn.com/problems/intersection-of-two-arrays/solution/cyu-yan-jian-bian-suan-fa-by-logan-31/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

leetcode 0209的更多相关文章

  1. 我为什么要写LeetCode的博客?

    # 增强学习成果 有一个研究成果,在学习中传授他人知识和讨论是最高效的做法,而看书则是最低效的做法(具体研究成果没找到地址).我写LeetCode博客主要目的是增强学习成果.当然,我也想出名,然而不知 ...

  2. LeetCode All in One 题目讲解汇总(持续更新中...)

    终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 477 Total Hamming Distance ...

  3. [LeetCode] Longest Substring with At Least K Repeating Characters 至少有K个重复字符的最长子字符串

    Find the length of the longest substring T of a given string (consists of lowercase letters only) su ...

  4. Leetcode 笔记 113 - Path Sum II

    题目链接:Path Sum II | LeetCode OJ Given a binary tree and a sum, find all root-to-leaf paths where each ...

  5. Leetcode 笔记 112 - Path Sum

    题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...

  6. Leetcode 笔记 110 - Balanced Binary Tree

    题目链接:Balanced Binary Tree | LeetCode OJ Given a binary tree, determine if it is height-balanced. For ...

  7. Leetcode 笔记 100 - Same Tree

    题目链接:Same Tree | LeetCode OJ Given two binary trees, write a function to check if they are equal or ...

  8. Leetcode 笔记 99 - Recover Binary Search Tree

    题目链接:Recover Binary Search Tree | LeetCode OJ Two elements of a binary search tree (BST) are swapped ...

  9. Leetcode 笔记 98 - Validate Binary Search Tree

    题目链接:Validate Binary Search Tree | LeetCode OJ Given a binary tree, determine if it is a valid binar ...

随机推荐

  1. AC3 mantissa quantization and decoding

    1.overview 所有的mantissa被quantize到固定精确度的level(有相应的bap标识)上,level小于等于15时,使用symmetric quantization.level大 ...

  2. 各技能DBC参数

    推荐你  通过 引擎的帮助文件查找标准魔法DB 下面是 部分hero引擎的标准魔法DB 34,解毒术,2,26,16,0,0,0,0,0,2,42,50,44,100,46,200,40,, 35,老 ...

  3. Navicat图形更改表结构的时,设置外键时出现1452错误

    原文地址:http://www.mamicode.com/info-detail-1296600.html 提示1452错误,如下图所示. 然后百度了一下,得到了一个靠谱的答案: 这是因为表设置了外键 ...

  4. linux服务器上部署springboot项目,并让他持续运行到后台

    我们知道在运行springboot 项目只需要java -jar + 项目的war包(jar包)名. 但是只要终端已停止那么服务就会被关闭,也就无法访问到我们的项目了.所以我们可以使用守护进程的方式来 ...

  5. 条件锁condition与Queue()

    在学习之前你应该先了解锁和队列基础 import queue import time import random import threading import asyncio import logg ...

  6. dw 快捷键

    <html></html> 创建一个HTML文档<head></head> 设置文档标题和其它在网页中不显示的信息<title></t ...

  7. concat merge

    # concat import numpy as np import pandas as pd from pandas import Series,DataFrame df1 = DataFrame( ...

  8. weinre 真机调试

    1.在任意文件夹 安装weinre cnpm -g install weinre 2.启动 weinre --httpPort 8009 --boundHost -all- 3.在你的页面中加入 本机 ...

  9. web前端技能考核(阿里巴巴)

  10. reduce 方法(升序)

    语法: array1.reduce(callbackfn[, initialValue]) 参数 定义 array1 必需.一个数组对象. callbackfn 必需.一个接受最多四个参数的函数.对于 ...