leetcode 刷题总结
开始刷 leetcode 和剑指 offer 大概一周多了吧,从最开始最简单的代码也要敲 30 mins,各种 bug 不断,到现在简单的可以10 mins 敲完(当然也有些没有思路的),还是有些进步的,另外发现还是需要把一些题解记录下来,总结一下,因为目前按 tags 和难度分开刷的,题目编号可能不连续,打算长期更新,加油吧!
进度更新(6月4日):跌跌撞撞也做了80+题,从开始只做简单到现在开始做些中等题,也算有些进步吧,不足的是代码bug太多,总体接受率才28%,加油,接下来想办法提升接受率,不要一直改bug!
更新(6月26号):最近一段时间没怎么刷题,开始刷题一个多月了,现在leetcode上才刷97题,blog上才更了不到70题,不知道为什么有些题没有记录上来。另外做了一下牛客网的校招编程题,感觉还是不会做。
1. Two Sum
- 题目描述:Given an array of integers, return indices of the two numbers such that they add up to a specific target.
- 解题思路:虽说是第一题简单难度,但是我就是不会做5555,评论区有哈希表解法,即将 target 与当前元素做差,在哈希表中查找有无此元素。
2. Add Two Numbers
- You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.You may assume the two numbers do not contain any leading zero, except the number 0 itself.
- 这题我写的超级麻烦,因为我是在原链表上改(因为我不会新建链表),所以我多了很多判断,比方说l1比l2长的话后面就在l1上改,最后还要返回l1,完后基础用例还是过了,但[5][5]得用例一直报错,内存错误,不知道哪里出现野指针还是这么回事,最后还是参考了讨论区解法。以后需要注意,新建指针方式:ListNode* l0=new ListNode(1);
|
|
3. Longest Substring Without Repeating Characters
- Given a string, find the length of the longest substring without repeating characters.
- 我想到的只有暴力搜索了,讨论区有动态规划的解法,又写了一遍,用的python的dict方法,在dict中查找仅要$O(1)$复杂度,相当于hash表。思路是建立2个指针,第一个指针遍历后将所读取的字符放入dict,如果出现重复字符,则移动第二个指针并把读取的字符从dict中删除,相当于dict中仅有不重复的字串。
|
|
|
|
5. Longest Palindromic Substring
6. ZigZag Conversion
- The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
- 思路:简单暴力,用 vector
分别保存 zigzag 每一行的字符串,然后拼接起来
|
|
7. Reverse Integer
- 反转整数
- 挺简单的,需要特别注意不要溢出了,int范围是:$[-2^{31},2^{31}-1] $ or [INT_MIN,INT_MAX]
|
|
8. String to Integer (atoi)
- Implement atoi which converts a string to an integer.
|
|
9. Palindrome Number
- 判断回文数
- 最简单想到的就是把每位的数都保存到数组里,然后依次比较数组的头与尾,但这样时间效率确实不高,之后参考大神解法(见代码二),直接用一个快指针一个慢指针,找到数的中间位置,找中间位置时顺便把数的一半反转了,然后比较反转的与剩下的一半是否相等。
|
|
|
|
10. Regular Expression Matching
模拟正则表达式
'.' Matches any single character. '*' Matches zero or more of the preceding element.
- 思路:’‘可以表示0个或多个前面一个元素,因此想到用递归的方式不断搜索答案,另外’‘是后置的运算符,因此采用2个指针从后向前搜索答案。搜索时有以下几种情况:
- p的指针搜索到任意字母:与s中的指针比较,不同则返回false,否则p与s的指针向前移动一位,继续搜索。
- p的指针搜索到’.’:p与s的指针向前移动一位,继续搜索。
- p的指针搜索到’‘:如果p指针前一位元素为i,则统计s指针前方有n个i,然后依次’‘前的元素依次重复0~n次,递归继续搜索。1234567891011121314151617181920212223242526272829303132333435363738394041424344class Solution {public:bool isMatch(string s, string p) {int ends=s.size()-1,endp=p.size()-1;return matchOrNot(s, p, ends,endp);}bool matchOrNot(string &s, string &p,int ends,int endp){if(ends<0&&endp<0) return true;if(endp<0||(ends<0 && p[endp]!='*')) return false;if(p[endp]=='*'){if(ends<0){return matchOrNot(s, p, ends,endp-2);}int count=0;//统计s指针前方p[endp-1]个数if(p[endp-1]!='.'){for(int i=ends;i>=0;i--){if(s[i]==p[endp-1]){count++;}elsebreak;}}elsecount=ends+1;bool judge=false;//递归搜索for(int i=0;i<=count;i++){judge=judge||matchOrNot(s, p, ends-i,endp-2);if(judge)return judge;}}else if(p[endp]=='.'){return matchOrNot(s, p, ends-1,endp-1);}else{if(p[endp]==s[ends]){return matchOrNot(s, p, ends-1,endp-1);}}return false;}};
11. Container With Most Water
- Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
- 思路:见https://segmentfault.com/a/1190000008824222
|
|
12. Integer to Roman
- 数字转化为罗马字
- 这题我不会,自定义了一个转化方法,最后结果也不对,可能对转化方法不太熟吧。下面程序方法来源网络,这方法确实不错,把每一种情况都考虑到了。
|
|
13. Roman to Integer
- 将罗马数字转化为阿拉伯数字
- 还以为自己写错了,结果一次就AC了,开心。主要就是要判断一个罗马字是前缀还是后缀,前缀需要相减,后缀则相加。
|
|
14. Longest Common Prefix
- Write a function to find the longest common prefix string amongst an array of strings.
- 开始以为是最长子序列,想了半天想不出怎么做,后来发现是最长前缀子序列,一个一个比较吧。
|
|
15. 3Sum
- Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
- 我的思路:首先建立哈希表,然后取2个指针a,b,在哈希表中查找-(a+b),如果有说明和为0,但这样存在重复情况,如[-1,0,1],a=-1,b=0与a=-1,b=1情况重复,于是新建立一个哈希表map<vector
,int>,每次得到结果在哈希表中查找,时间复杂度大概为$O(n^2)$,而且没有提前停止,所以有个算例,输入n
个0,然后我就超时了,再加上提前停止的判定,好歹AC了,但时间效率很低(其实这个思路还是能优化的,在提前停止部分优化好)。 - 大神思路:类似2Sum,用一个指针开始遍历,另外2个指针类似于2Sum进行遍历。
|
|
16. 3Sum Closest
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
思路:参考第15题3sum的思路,先对数组排序,然后使用3个指针遍历数组,初始化指针p0位于数组开头,p1位于p0的下一个位置,p2位于数组末尾,指针移动规则为:
- sum(p0,p1,p2)>target,说明sum(p0,p1,p2)应该减小,因此p2应向左移动(p2–);
- sum(p0,p1,p2)<target,说明sum(p0,p1,p2)应该增大,因此p1向右移动(p1++)
- sum(p0,p1,p2)==target,直接return target即可;
- 使用一个变量subs记录下最接近target的sum,每次计算完sum后与subs比较,如果sum更接近,则更新subs。
- 提前停止条件:数组已经排过序了,因此sum(p0,p0+1,p0+2)为某个p0时对应的最小和,如果sum(p0,p0+1,p0+2)>target,不论p1p2如何移动,均有
abs(sum(p0,p1,p2))>=abs(sum(p0,p0+1,p0+2))
,因此可以以此作为提前停止条件。
|
|
17. Letter Combinations of a Phone Number
全排列问题,做过很多次了,递归求解。
|
|
18. 4Sum
- Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
- 思路同3sum。
|
|
19. Remove Nth Node From End of List
- Given a linked list, remove the n-th node from the end of list and return its head.
- 思路还是很简单,一个指针先走k步,但边界条件很难搞定,比如输入(ListNode* head, int n)分别为([1],1)、([1,2],2),这样输出phead的话就不对了。于是再链表前面新加了一个p0当head,输出p0的下一个。
|
|
20. Valid Parentheses
- Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, determine if the input string is valid.
- 题目很熟悉,但解法不记得了,这是根据电脑上的记录补充的,等2刷吧。
|
|
21. Merge Two Sorted Lists
- Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
- 题目还是不难的,但是我第一遍写的代码还是超级麻烦,看了看大佬们的代码,可以从一下角度优化(简洁)代码:
- 随便新建一个头指针,
ListNode* head = new ListNode(-1);
,然后开始while循环连接链表节点,最后只需输出head-.next
。这样便省去了判断l1与l2头节点哪个小,然后赋值给head的过程,使代码更简洁。
- 随便新建一个头指针,
|
|
22. Generate Parentheses
- 给出n个括号的排列组合,Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.[ “((()))”, “(()())”, “(())()”, “()(())”, “()()()”]
- 思路:每个位置都进可以放 ( 或 ) ,但当此位置前没有单独的 ( 时,不能放置 ),建立一个变量记录没有配对的 ( 个数,然后递归求解。
|
|
23. Merge k Sorted Lists
- Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
- 思路:按照合并2个list的思路,将k个list两两合并,然后继续递归合并合并后的k/2个list。1234567891011121314151617181920212223242526272829303132333435363738394041* Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/class Solution {public:ListNode* mergeKLists(vector<ListNode*>& lists) {if(lists.size()==0) return NULL;queue<ListNode*> z;for(auto &i:lists){z.push(i);}while(z.size()!=1){ListNode* l1=z.front();z.pop();ListNode* l2=z.front();z.pop();z.push(Merge(l1,l2));}return z.front();}ListNode* Merge(ListNode* pHead1, ListNode* pHead2){if (pHead1 == NULL) return pHead2;if (pHead2 == NULL) return pHead1;ListNode *mergeList = NULL;if (pHead1->val < pHead2->val) {mergeList = pHead1;mergeList->next = Merge(pHead1->next, pHead2);}else {mergeList = pHead2;mergeList->next = Merge(pHead1, pHead2->next);}return mergeList;}};
24. Swap Nodes in Pairs
- Given a linked list, swap every two adjacent nodes and return its head.
- 开始以为2个指针就能交换完,哼哧哼哧写完发现2个指针版本算法是错的,没办法,只好修改成3指针,关键点:[1,2,3,4]交换完[2,1,4,3],1的指针需要指向第4位,而不是原来的第3位!!交换步骤是:
- 2指向1
- 判断1应该指向第3位还是第4位还是NULL,这3种情况分别对应2指针后还有1位、2位以上以及NULL的情况
- 如果2指针后还有2位以上,则将1指向3,2指向3->next,3指向3->next->next继续循环
- 看完题目还是该好好想一下,而不是觉得可以了就开始瞎写,边界条件要考虑清楚!
- 评论区也有递归的解法
|
|
26. Remove Duplicates from Sorted Array
- Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
- 要求在in-place,不能使用额外空间,首先想到很自然的解法,从后向前遍历,发现重复的元素便erase,但时间效率还是不高,只击败了30%的人。
- 改进:遍历数组,同时将不重复元素向前移动,覆盖掉重复元素,见解法二,改进后击败了97%+的人。
|
|
|
|
27. Remove Element
- Given an array nums and a value val, remove all instances of that value in-place and return the new length.Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
- 思路和上体类似啦。
|
|
|
|
28. Implement strStr()
简单题,从头遍历吧。
|
|
29. Divide Two Integers
- Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.Return the quotient after dividing dividend by divisor.The integer division should truncate toward zero.
- 这题很简单,主要是注意数字不要溢出
|
|
30. Substring with Concatenation of All Words
- You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.
- 这题我不会做,看了别人的题解,代码里面注释很全,字节看代码吧,类似的题目都可以使用这种划窗法来做。
|
|
33. Search in Rotated Sorted Array
- 旋转数组中查找
- 要求$O(\log n)$求解,自然想到二分查找,中间也遇到了坑,比如max()函数只接受2个参数,我开始传了3个参数进去后报错,还找不出错误在哪。最后还是用的二分查找的改进版,查找n[i:j],如果n[i]<n[j],说明数组有序,按正常二分查找来,反之说明数组旋转了,二分之后2个数组n[i:(i+j)//2-1]和n[(i+j)//2+1:j]都要查找(不知道时间复杂度符合要求么)
|
|
- Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.Your algorithm’s runtime complexity must be in the order of O(log n).If the target is not found in the array, return [-1, -1].
- 看见$O(logn)$就该想到二分查找了。
|
|
36. Valid Sudoku
- Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
- 每行每列每个box地检查吧,另外这题没有什么必要用递归的(感觉)。改进方式:将每行、每列数字保存在set中,可以在$O(1)$的时间比较。
|
|
39. Combination Sum
- Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.The same repeated number may be chosen from candidates unlimited number of times.
- 此类问题的关键是若满足条件,则将解保存,否则需正确回溯到上一步空间状态,我的思路是:对于第i个元素,有放与不放2种状态,则用递归方式依次搜索着2种状态,另外将数组预先排序,可以降低搜索时间。需要吐槽的是,自己的代码功力还是太弱鸡,开始以为递归的话,sums数组在函数中会被修改,好像就递归不起来了,于是传了个虚参,后来发现可以用实参。然后刚开始考虑,对于第i个元素,我居然写出3种状态来了,然后result最后也传了个虚参,submit后,输出空结果,检查了半天,发现result前面少写了个&。最后总共花了一个多小时,效率太慢了。
|
|
40. Combination Sum II
- Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.Each number in candidates may only be used once in the combination.
- 大体思路与上题一样,感觉没什么区别,就是一个元素只能用1次了,然后我啪啪啪一会就写完,一运行发现结果错了,仔细检查发现,重复的元素会造成干扰,如[1,1,2,3,4],target=3,我的结果是[[1,2],[1,2]],这两个1分别是第一、第二个1,然后想到,要么输出结果后对res数组去重,但这样复杂度太高了,于是第二步想用哈希表,将结果插入res数组时先在哈希表中搜索一下,但我哈希表用的不熟悉,写了一会,用的unordered_map<vector
,int>,结果还是报错了,不知道是不是vector 不能做键值,于是用了第三种方法,思路是:对于第i个元素,有放与不放2种状态,但对于重复元素而言(比较candidates[i]==candidates[i+1]),仅对如果放,按以前一样递归搜索,不放则递归搜索下一个不重复元素。还是以[1,1,2,3,4]为例,如果第一个1放,则考虑第二个1放不放,如果第一个1不放,则考虑第三个元素2放不放,这样便不会出现2个一放第一个和放第二个重复的情况。 12345678910111213141516171819202122232425262728293031323334class Solution {public:vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {vector<vector<int>> res;vector<int> vec1;if(candidates.size()==0) return res;sort(candidates.begin(),candidates.end());getSum(candidates, target,res,vec1,0);return res;}void getSum(vector<int>& candidates, int target,vector<vector<int>> &res,vector<int> &vec1,int begin){if(candidates[begin]<target&&begin<candidates.size()-1){vec1.push_back(candidates[begin]);getSum(candidates, target-candidates[begin],res,vec1,begin+1);vec1.pop_back();int i=1;while(begin+i<candidates.size()-1){if(candidates[begin]<candidates[begin+i])break;i++;}getSum(candidates, target,res,vec1,begin+i);}else if(candidates[begin]==target){vec1.push_back(candidates[begin]);res.push_back(vec1);vec1.pop_back();}}};
41. First Missing Positive
Given an unsorted integer array, find the smallest missing positive integer.
Example 1: Input: [1,2,0] Output: 3
- 这题不会做,思路可以参考https://segmentfault.com/a/1190000007306888
43. Multiply Strings
- 字符串乘法
- 不能直接相乘,就位与位相乘吧,这种题用C++麻烦得很,还要考虑大数相乘。
|
|
44. Wildcard Matching
- Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for ‘?’ and ‘*’.
- 字符串匹配,改了一晚上bug,最后还是TL,麻痹,解法放下面吧,看了别人的DP解法,发现写得很简洁,我的代码真是写的又臭又长。。。感觉子集字符串这方面真是很弱鸡,要加强。
|
|
|
|
45. Jump Game II
- Given an array of non-negative integers, you are initially positioned at the first index of the array.Each element in the array represents your maximum jump length at that position.Your goal is to reach the last index in the minimum number of jumps.
- 思路:遍历一遍数组,记录下当前位置与最大可跳跃位置,然后向后遍历,遍历时用一个变量记录下应该跳跃到的位置(即可跳跃到最大位置的位置),当遍历出了当前位置的最大跳跃位置,将当前位置移动到应该跳跃的位置。1234567891011121314151617181920212223242526class Solution {public:int jump(vector<int>& nums) {if(nums.size()<=1) return 0;int num=0,len=nums.size()-1;int pos=0,max_to_pos=nums[0],max_pos=0,pre_to_pos=nums[0];for(int i=0;i<=len;i++){int to_pos=i+nums[i];if(to_pos>max_to_pos){max_to_pos=to_pos;max_pos=i;}if(i>=pre_to_pos){pre_to_pos=max_to_pos;pos=max_pos;max_to_pos=pos+nums[pos];num+=1;}else if(i==len) num+=1;}return num;}};
46. Permutations
- Given a collection of distinct integers, return all possible permutations.
- 递归问题
|
|
47. Permutations II
- Given a collection of numbers that might contain duplicates, return all possible unique permutations.
- 类似上题,注意去重
|
|
49. Group Anagrams
Given an array of strings, group anagrams together.
123456789Example:Input: ["eat", "tea", "tan", "ate", "nat", "bat"],Output:[["ate","eat","tea"],["nat","tan"],["bat"]]首先自己手撸了个,建立个数组,遍历string,将每个元素个数保存在数组里,比较2个数组是否相同,得到答案。但是时间花销太大了,500+ms。代码如下:
|
|
- 网上别人的哈希表解法,方式是对每个string排序,在哈希表中比较有没有相同string即可。
|
|
54. Spiral Matrix
- 旋转数组,没有什么好解法,上右下左一个一个转吧123456789101112131415161718192021222324252627282930313233class Solution:def spiralOrder(self, matrix):""":type matrix: List[List[int]]:rtype: List[int]"""if(len(matrix)==0):return []elif(len(matrix)==1):return matrix[0]elif(len(matrix[0])==1):return [i[0] for i in matrix]total=min(len(matrix),len(matrix[0]))//2col=len(matrix[0])#lierow=len(matrix)#行res=[]for i in range(total):for j in range(i,col-i):res.append(matrix[i][j])for j in range(i+1,row-i):res.append(matrix[j][col-i-1])for j in range(col-2-i,i-1,-1):res.append(matrix[row-1-i][j])for j in range(row-2-i,i,-1):res.append(matrix[j][i])if(min(row,col)-2*total==1):if(col>=row):for i in range(total,col-total):res.append(matrix[total][i])else:for i in range(total,row-total):res.append(matrix[i][total])return res
55. Jump Game
- Given an array of non-negative integers, you are initially positioned at the first index of the array.Each element in the array represents your maximum jump length at that position.Determine if you are able to reach the last index.
- 解题思路:开始想到可能需要用动态规划法,用一个数组存放该位置可以最大跳到哪,后来想了想,只用一个int记录该位置最大可以跳到哪,最后判断该int是否大于初始数组长度就行了;
|
|
56. Merge Intervals
- Given a collection of intervals, merge all overlapping intervals.
- 合并区间,这个题目我理解错意思了,然后就写了一个相邻区间的合并的函数,最后发现有如下输入:
[[2,3][4,5],[5,6][1,10]]
,答案应该输出[[1,10]]
,而我因为是从第一个开始,相邻的合并,最后只能输出[[2,3][4,5],[1,10]]
,正确思路应该是先根据区间的第一个数进行排序,之后再进行合并的操作。
|
|
58. Length of Last Word
- Given a string s consists of upper/lower-case alphabets and empty space characters ‘ ‘, return the length of last word in the string.If the last word does not exist, return 0.
- 感觉很简单啊。。。1234567891011121314151617class Solution:def lengthOfLastWord(self, s):""":type s: str:rtype: int"""l=0b=1for i in s[::-1]:if(i!=' '):l+=1b=0elif(i==' ' and b==1):continue;else:return l;return l;
59. Spiral Matrix II
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]- 在54题的基础上修改的,很快就改出来了,2233
|
|
61. Rotate List
- Given a linked list, rotate the list to the right by k places, where k is non-negative.
- 需要将最后k位旋转到开头,只需找到第k-1位,以及第末位,然后末位指向开头,第k-1位指向NULL,return 第k位(开头)
|
|
62. Unique Paths
- A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).How many possible unique paths are there?
- 思路:最开始想用递归,三两下就把代码写完了,然后提交发现运行超时(因为重复计算!!!时间复杂度$O(n^n)$),最后想了半天还是不会,看讨论区才发现用动态规划法比较好。
63. Unique Paths II
- An obstacle and empty space is marked as 1 and 0 respectively in the grid.有障碍物。
- 这题恶心在边界条件,居然存在
[[0]]
、[[1]]
、[[0,1]]
、[[1,0]]
之类的恶心输入。话说[[1]]
这样你机器人怎么落脚?[[0]]
机器人根本就不用动啊。总体来说和上题类似,使用动态规划求解。
|
|
64. Minimum Path Sum
- Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
- 学会用动态规划法写题了QAQ123456789101112131415161718192021222324class Solution {public:int minPathSum(vector<vector<int>>& grid) {vector<int> gridSum(grid[0].size(),grid[0][0]);for(int j=0;j<grid.size();j++){for(int i=0;i<grid[0].size();i++){if(j==0){if(i!=0)gridSum[i]=gridSum[i-1]+grid[0][i];}else{if(i==0)gridSum[i]=gridSum[i]+grid[j][i];elsegridSum[i]=min(gridSum[i],gridSum[i-1])+grid[j][i];}}}return gridSum[gridSum.size()-1];}};
69. Sqrt(x)
- Implement int sqrt(int x).
- 类似二分搜索
|
|
70. Climbing Stairs
- You are climbing a stair case. It takes n steps to reach to the top.Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?123456789101112131415161718class Solution {public:int climbStairs(int n) {if(n<=3)return n;int num1=2,num2=1,nums=3;int n_step=4;for(int i=4;i<=n;i++){int tmp=num1;num1=nums;num2=tmp;nums=num1+num2;}return nums;}};
73. Set Matrix Zeroes
- Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
- 思路:首先想到的是用2个向量分别标记行与列是否需要置0,这样空间复杂度为$O(m+n)$,优化方式为使用1个向量标记某列是否为0,行则在遍历时直接替换,这样空间复杂度为$O(n)$,见解法1。
- 继续优化:参考大神解法,原本自然而然的思路是用2个向量分别标记行与列是否需要置0,如果不适用额外空间,则可以找到数组中含0的行与列,用于充当上面提到的向量。见解法2。
|
|
|
|
|
|
74. Search a 2D Matrix
- Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
- Integers in each row are sorted from left to right.
- The first integer of each row is greater than the last integer of the previous row.
- 这题第一次做只会一行一行比较,看讨论区才知道可以二分查找,现在第二次直接就把二分查找写出来了。也不难,也没怎么调bug。
|
|
75. Sort Colors
- Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
- 大概有2个思路:先遍历一遍,统计0,1,2出现个数,再遍历一遍并赋值(题目好像要求只能遍历一遍。。)。或者可以用2个指针交换位置的方法。
|
|
- 好吧,题目不允许遍历2遍,定义2个指针pos0、pos2,pos0当作0与1的交接处,pos2当作1与2的交界处,用pos1从pos0到pos2遍历,如果是1,则pos1++,如果是0,则与pos0交换,且pos0++,如果是2,则与pos2交换,且pos2–。
|
|
77. Combinations
- Given two integers n and k, return all possible combinations of k numbers out of 1 … n.
Input: n = 4, k = 2 Output: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
- 全排列问题,递归求解12345678910111213141516171819202122class Solution {public:vector<vector<int>> combine(int n, int k) {vector<vector<int> > res;if(k<=0) return res;vector<int> nums;solu(res,nums,1,n,k);return res;}void solu(vector<vector<int> > &res,vector<int> &nums,int begin,int n,int k){int len=nums.size();if(len==k){res.push_back(nums);return;}if(begin>n||len+n-begin+1<k) return;nums.push_back(begin);solu(res,nums,begin+1,n,k);nums.pop_back();solu(res,nums,begin+1,n,k);}};
78. Subsets
- Given a set of distinct integers, nums, return all possible subsets (the power set).Note: The solution set must not contain duplicate subsets.
- 递归问题
|
|
79. Word Search
- Given a 2D board and a word, find if the word exists in the grid.The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
- 在网格中寻找单词,只能在相邻的字母间查找
- 花了一个小时终于AC了,但效率超级慢,才击败10%的人。。。思路是用一个二维数组count记录原board中字母使用情况,用map记录单词的位置,然后从word开始遍历每次比较2字母位置以及字母是否已经被使用,如果都符合要求则把当前位置字母标记为已使用,并继续遍历下一个,否则回退回去继续搜索。
- 反思:时间效率低下的原因是每次都必须先遍历数组并保存map,时间及空间的花销都很大,实际上直接遍历数组找word的第一个单词,然后再从相邻元素中找第二个单词,依次迭代即可。
|
|
80. Remove Duplicates from Sorted Array II
- Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.
- 遍历数组,记录下重复数字的个数,同时,记录下新数组的长度。下面为各种可能性:
- 开始遍历时,新数组指针与遍历指针一致,如果数字没有重复超过2个,则新数组指针与遍历指针同时向右移动一位。
- 如果数字重复3个以上,则仅移动遍历的指针,新数组指针所指位置代表需要替换的位置。此时新数组指针与遍历指针错开了。
- 当新数组指针与遍历指针错开,则需判断 1. 数字重复次数小于2时,说明此数字选哟保留,则将遍历指针数字赋值给新数组指针,并且数字重复次数+1。2. 当数字重复次数大于2时,说明此数字已经保留了2个,多余的不需要保存,仅需将遍历指针移动。
|
|
81. Search in Rotated Sorted Array II
- Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).You are given a target value to search. If found in the array return true, otherwise return false.
- 分成2半递归着二分搜索吧。
|
|
82. Remove Duplicates from Sorted List II
- Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
- 基础题吧。
|
|
83. Remove Duplicates from Sorted List
- Given a sorted linked list, delete all duplicates such that each element appear only once.
- 基础题
|
|
88. Merge Sorted Array
- Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
- 基础题,但有个bug检查了很久。。。
|
|
91. Decode Ways
|
|
112. Path Sum
- Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
|
|
113. Path Sum II
- Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
- 深度优先搜索,用python写了一个,注意
list.copy()
|
|
202. Happy Number
- 题目描述:A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
- 解题思路:没什么思路,硬解吧(讨论区有用2个指针的方法,挺不错,即快指针追上慢指针,说明变成一个环了)
|
|
204. Count Primes
- Count the number of prime numbers less than a non-negative number, n.
- 如此短的题目,看完后不明所以,看讨论区也看不懂,然后找到一篇博客,讲的很清楚,反正我完全不会做 QAQ。
231. Power of Two
- 题目描述:Given an integer, write a function to determine if it is a power of two.
- 解题思路:首先想到的是递归,然后想用位运算,看了讨论区才发现一个二的指数的特性,如果一个数n为2的指数倍的话,二进制表示为$0\times0100$,则n-1为$0\times0011$,n&(n-1)=0,可用此特性来判断。
|
|
242. Valid Anagram
- 题目描述:Given two strings s and t , write a function to determine if t is an anagram of s.
- 思路:哈希表或者排序之后对比,见讨论区总结
|
|
326. Power of Three
- 题目描述:Given an integer, write a function to determine if it is a power of 3.
- 解题思路:题目要求不要用循环,就直接写了个递归,然后看了下讨论区,各种各样的解法,什么log的,最大数的,见讨论区总结)
|
|
367. Valid Perfect Square
- 题目描述:Given a positive integer num, write a function which returns True if num is a perfect square else False.
- 思路:二分搜索
NO.387 First Unique Character in a String
- 题目描述:Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.(找到给定的string的第一个不重复的字符。)
- 解题思路:刚看到这个题目,感觉没有什么特别好的解法,除了2个指针遍历的$O(n^2)$的解法,解法二是建立哈希表,这样只需遍历一遍 string 和一遍哈希表,解法三,建立一个包含26元素的数组,数组中每个数字代表对应的字母的个数,遍历 string 后,遍历数组,返回第一个为1的index。
|
|
- 此外还有个 Python 解法-!),感觉很强,在此分享下:
|
|
NO.389. Find the Difference
- Given two strings s and t which consist of only lowercase letters.String t is generated by random shuffling string s and then add one more letter at a random position.Find the letter that was added in t.
- 思路:看讨论区里的,用异或解,或者字符求和后做差。
|
|
NO.434. Number of Segments in a String
- 题目描述:Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.(计算string中的单词个数)
- 解题思路:计算单词间的空格个数。另外看到个挺新颖的解法,分享下:
|
|
438. Find All Anagrams in a String
- Given a string s and a non-empty string p, find all the start indices of p’s anagrams in s.Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
- 思路:反正我没想到什么好思路,写了个超复杂的QAQ
|
|
443. String Compression
题目描述:Given an array of characters, compress it in-place.
The length after compression must always be smaller than or equal to the original array.Every element of the array should be a character (not int) of length 1.After you are done modifying the input array in-place, return the new length of the array.Follow up:Could you solve it using only O(1) extra space?(将[“a”,”a”,”b”,”b”,”c”,”c”,”c”] 缩并成 [“a”,”2”,”b”,”2”,”c”,”3”] 形式,要求:在原容器上更改)解题思路:定义3个指针,第一个指向缩并后数组末尾,负责指定下一个需替换的元素,第二、三个指针遍历数组,统计字符个数。看了下讨论区,大家思路都差不多(为什么我的才超过82% QAQ )。
|
|
454. 4Sum II
Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.
Input: A = [ 1, 2] B = [-2,-1] C = [-1, 2] D = [ 0, 2] Output: 2 Explanation: The two tuples are: 1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0 2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0
- 思路与前面的ksum类似,可以用hash,或者4指针
|
|
520. Detect Capital
题目描述:判断单词是否为Capital,单词为Capital的条件为:
- All letters in this word are capitals, like “USA”.
- All letters in this word are not capitals, like “leetcode”.
- Only the first letter in this word is capital if it has more than one letter, like “Google”.
解题思路:统计单词中大写单词的个数。(查看讨论区发现有 count_if 函数挺好用的)
- std::count(first,last,value):first是容器的首迭代器,last是容器的末迭代器,value是询问的元素,整个函数返回int型。count函数的功能是:统计容器中等于value元素的个数。
- std::count_if(first,last,comp) (在comp为true的情况下计数) 或者 count_if(first,last,value,comp) (这个是在comp为true的情况下统计容器中等于value的元素):first为首迭代器,last为末迭代器,value为要查询的元素,comp为比较bool函数,为true则计数,函数返回型是int。
|
|
541. Reverse String II
- 题目描述:Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.
- 解题思路:用 reverse 翻转吧(这里有个坑,reverse(first,end),是反转[first,end),左开右闭,我一开始认为2边都是闭,结果反转得不对,晕)
|
|
551. Student Attendance Record I
- 题目描述:Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
- 思路:统计L、A个数而已。
557. Reverse Words in a String III
- 题目描述:You need to return whether the student could be rewarded according to his attendance record.
- 思路:挺简单的,找空格而已。
606. Construct String from Binary Tree
- 题目描述:You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.The null node needs to be represented by empty parenthesis pair “()”. And you need to omit all the empty parenthesis pairs that don’t affect the one-to-one mapping relationship between the string and the original binary tree.(打印二叉树)
- 思路:递归做吧,不麻烦
|
|
657. Judge Route Circle
- 题目描述:判断机器人是否回到原点
- 思路:通过坐标x,y,很简单。