├── 112. Path Sum.md
├── 120. Triangle.md
├── 292. Nim Game.md
├── 66. Plus One.md
├── 69. Sqrt(x).md
├── 78. Subsets.md
├── 89. Gray Code.md
├── 100. Same Tree.md
├── 155. Min Stack.md
├── 258. Add Digits.md
├── 67. Add Binary.md
├── 75. Sort Colors.md
├── 79. Word Search.md
├── 90. Subsets II.md
├── 91. Decode Ways.md
├── 113. Path Sum II.md
├── 198. House Robber.md
├── 242. Valid Anagram.md
├── 71. Simplify Path.md
├── 72. Edit Distance.md
├── 77. Combinations.md
├── 86. Partition List.md
├── 101. Symmetric Tree.md
├── 344. Reverse String.md
├── 64. Minimum Path Sum.md
├── 70. Climbing Stairs.md
├── 87. Scramble String.md
├── 118. Pascal-s Triangle.md
├── 125. Valid Palindrome.md
├── 130. Surrounded Regions.md
├── 141. Linked List Cycle.md
├── 169. Majority Element.md
├── 217. Contains Duplicate.md
├── 226. Invert Binary Tree.md
├── 68. Text Justification.md
├── 73. Set Matrix Zeroes.md
├── 74. Search a 2D Matrix.md
├── 85. Maximal Rectangle.md
├── 88. Merge Sorted Array.md
├── 97. Interleaving String.md
├── 110. Balanced Binary Tree.md
├── 119. Pascal-s Triangle II.md
├── 206. Reverse Linked List.md
├── 371. Sum of Two Integers.md
├── 93. Restore IP Addresses.md
├── 115. Distinct Subsequences.md
├── 165. Compare Version Numbers.md
├── 76. Minimum Window Substring.md
├── 92. Reverse Linked List II.md
├── 171. Excel Sheet Column Number.md
├── 96. Unique Binary Search Trees.md
├── 99. Recover Binary Search Tree.md
├── 104. Maximum Depth of Binary Tree.md
├── 111. Minimum Depth of Binary Tree.md
├── 237. Delete Node in a Linked List.md
├── 349. Intersection of Two Arrays.md
├── 94. Binary Tree Inorder Traversal.md
├── 95. Unique Binary Search Trees II.md
├── 98. Validate Binary Search Tree.md
├── 350. Intersection of Two Arrays II.md
├── 84. Largest Rectangle in Histogram.md
├── 102. Binary Tree Level Order Traversal.md
├── 121. Best Time to Buy and Sell Stock.md
├── 160. Intersection of Two Linked Lists.md
├── 81. Search in Rotated Sorted Array II.md
├── 83. Remove Duplicates from Sorted List.md
├── 114. Flatten Binary Tree to Linked List.md
├── 122. Best Time to Buy and Sell Stock II.md
├── 107. Binary Tree Level Order Traversal II.md
├── 80. Remove Duplicates from Sorted Array II.md
├── 82. Remove Duplicates from Sorted List II.md
├── 103. Binary Tree Zigzag Level Order Traversal.md
├── 108. Convert Sorted Array to Binary Search Tree.md
├── 109. Convert Sorted List to Binary Search Tree.md
├── 116. Populating Next Right Pointers in Each Node.md
├── 117. Populating Next Right Pointers in Each Node II.md
├── 105. Construct Binary Tree from Preorder and Inorder Traversal.md
├── 106. Construct Binary Tree from Inorder and Postorder Traversall.md
├── 50. Pow(x, n).md
├── 58. Length of Last Word.md
├── 38. Count and Say.md
├── 27. Remove Element.md
├── 41. First Missing Positive.md
├── 13. Roman to Integer.md
├── 11. Container With Most Water.md
├── 9. Palindrome Number.md
├── 24. Swap Nodes in Pairs.md
├── 35. Search Insert Position.md
├── 36. Valid Sudoku.md
├── 7. Reverse Integer.md
├── 26. Remove Duplicates from Sorted Array.md
├── 55. Jump Game.md
├── 22. Generate Parentheses.md
├── 19. Remove Nth Node From End of List.md
├── 31. Next Permutation.md
├── 46. Permutations.md
├── 14 Longest Common Prefix.md
├── 32. Longest Valid Parentheses.md
├── 47. Permutations II.md
├── 63. Unique Paths II.md
├── 61. Rotate List.md
├── 20. Valid Parentheses.md
├── 34. Search for a Range.md
├── 17. Letter Combinations of a Phone Number.md
├── 56. Merge Intervals.md
├── 43. Multiply Strings.md
├── 48. Rotate Image.md
├── 52. N-Queens II.md
├── 6. ZigZag Conversion.md
├── 54. Spiral Matrix.md
├── 42. Trapping Rain Water.md
├── 30. Substring with Concatenation of All Words.md
├── 1. Two Sum.md
├── 8. String to Integer (atoi).md
├── 59. Spiral Matrix II.md
├── 49. Group Anagrams.md
├── 62. Unique Paths.md
├── 10. Regular Expression Matching.md
├── 29. Divide Two Integers.md
├── 23. Merge k Sorted Lists.md
├── 53. Maximum Subarray.md
├── 60. Permutation Sequence..md
├── 12. Integer to Roman.md
├── 3. Longest Substring Without Repeating Characters.md
├── 45. Jump Game II.md
├── 51. N-Queens.md
├── 65. Valid Number.md
├── 18. 4Sum.md
├── 40. Combination Sum II.md
├── 57. Insert Interval.md
├── 4. Median of Two Sorted Arrays.md
├── 25. Reverse Nodes in k-Group.md
├── 28. Implement strStr().md
├── 16. 3Sum Closest.md
├── 21. Merge Two Sorted Lists.md
├── 33. Search in Rotated Sorted Array.md
├── 15 3Sum.md
├── 39. Combination Sum.md
├── 44. Wildcard Matching.md
├── 2. Add Two Numbers.md
├── 5. Longest Palindromic Substring.md
└── README.md
/112. Path Sum.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/112. Path Sum.md
--------------------------------------------------------------------------------
/120. Triangle.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/120. Triangle.md
--------------------------------------------------------------------------------
/292. Nim Game.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/292. Nim Game.md
--------------------------------------------------------------------------------
/66. Plus One.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/66. Plus One.md
--------------------------------------------------------------------------------
/69. Sqrt(x).md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/69. Sqrt(x).md
--------------------------------------------------------------------------------
/78. Subsets.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/78. Subsets.md
--------------------------------------------------------------------------------
/89. Gray Code.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/89. Gray Code.md
--------------------------------------------------------------------------------
/100. Same Tree.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/100. Same Tree.md
--------------------------------------------------------------------------------
/155. Min Stack.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/155. Min Stack.md
--------------------------------------------------------------------------------
/258. Add Digits.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/258. Add Digits.md
--------------------------------------------------------------------------------
/67. Add Binary.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/67. Add Binary.md
--------------------------------------------------------------------------------
/75. Sort Colors.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/75. Sort Colors.md
--------------------------------------------------------------------------------
/79. Word Search.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/79. Word Search.md
--------------------------------------------------------------------------------
/90. Subsets II.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/90. Subsets II.md
--------------------------------------------------------------------------------
/91. Decode Ways.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/91. Decode Ways.md
--------------------------------------------------------------------------------
/113. Path Sum II.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/113. Path Sum II.md
--------------------------------------------------------------------------------
/198. House Robber.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/198. House Robber.md
--------------------------------------------------------------------------------
/242. Valid Anagram.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/242. Valid Anagram.md
--------------------------------------------------------------------------------
/71. Simplify Path.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/71. Simplify Path.md
--------------------------------------------------------------------------------
/72. Edit Distance.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/72. Edit Distance.md
--------------------------------------------------------------------------------
/77. Combinations.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/77. Combinations.md
--------------------------------------------------------------------------------
/86. Partition List.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/86. Partition List.md
--------------------------------------------------------------------------------
/101. Symmetric Tree.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/101. Symmetric Tree.md
--------------------------------------------------------------------------------
/344. Reverse String.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/344. Reverse String.md
--------------------------------------------------------------------------------
/64. Minimum Path Sum.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/64. Minimum Path Sum.md
--------------------------------------------------------------------------------
/70. Climbing Stairs.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/70. Climbing Stairs.md
--------------------------------------------------------------------------------
/87. Scramble String.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/87. Scramble String.md
--------------------------------------------------------------------------------
/118. Pascal-s Triangle.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/118. Pascal-s Triangle.md
--------------------------------------------------------------------------------
/125. Valid Palindrome.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/125. Valid Palindrome.md
--------------------------------------------------------------------------------
/130. Surrounded Regions.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/130. Surrounded Regions.md
--------------------------------------------------------------------------------
/141. Linked List Cycle.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/141. Linked List Cycle.md
--------------------------------------------------------------------------------
/169. Majority Element.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/169. Majority Element.md
--------------------------------------------------------------------------------
/217. Contains Duplicate.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/217. Contains Duplicate.md
--------------------------------------------------------------------------------
/226. Invert Binary Tree.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/226. Invert Binary Tree.md
--------------------------------------------------------------------------------
/68. Text Justification.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/68. Text Justification.md
--------------------------------------------------------------------------------
/73. Set Matrix Zeroes.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/73. Set Matrix Zeroes.md
--------------------------------------------------------------------------------
/74. Search a 2D Matrix.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/74. Search a 2D Matrix.md
--------------------------------------------------------------------------------
/85. Maximal Rectangle.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/85. Maximal Rectangle.md
--------------------------------------------------------------------------------
/88. Merge Sorted Array.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/88. Merge Sorted Array.md
--------------------------------------------------------------------------------
/97. Interleaving String.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/97. Interleaving String.md
--------------------------------------------------------------------------------
/110. Balanced Binary Tree.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/110. Balanced Binary Tree.md
--------------------------------------------------------------------------------
/119. Pascal-s Triangle II.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/119. Pascal-s Triangle II.md
--------------------------------------------------------------------------------
/206. Reverse Linked List.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/206. Reverse Linked List.md
--------------------------------------------------------------------------------
/371. Sum of Two Integers.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/371. Sum of Two Integers.md
--------------------------------------------------------------------------------
/93. Restore IP Addresses.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/93. Restore IP Addresses.md
--------------------------------------------------------------------------------
/115. Distinct Subsequences.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/115. Distinct Subsequences.md
--------------------------------------------------------------------------------
/165. Compare Version Numbers.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/165. Compare Version Numbers.md
--------------------------------------------------------------------------------
/76. Minimum Window Substring.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/76. Minimum Window Substring.md
--------------------------------------------------------------------------------
/92. Reverse Linked List II.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/92. Reverse Linked List II.md
--------------------------------------------------------------------------------
/171. Excel Sheet Column Number.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/171. Excel Sheet Column Number.md
--------------------------------------------------------------------------------
/96. Unique Binary Search Trees.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/96. Unique Binary Search Trees.md
--------------------------------------------------------------------------------
/99. Recover Binary Search Tree.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/99. Recover Binary Search Tree.md
--------------------------------------------------------------------------------
/104. Maximum Depth of Binary Tree.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/104. Maximum Depth of Binary Tree.md
--------------------------------------------------------------------------------
/111. Minimum Depth of Binary Tree.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/111. Minimum Depth of Binary Tree.md
--------------------------------------------------------------------------------
/237. Delete Node in a Linked List.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/237. Delete Node in a Linked List.md
--------------------------------------------------------------------------------
/349. Intersection of Two Arrays.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/349. Intersection of Two Arrays.md
--------------------------------------------------------------------------------
/94. Binary Tree Inorder Traversal.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/94. Binary Tree Inorder Traversal.md
--------------------------------------------------------------------------------
/95. Unique Binary Search Trees II.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/95. Unique Binary Search Trees II.md
--------------------------------------------------------------------------------
/98. Validate Binary Search Tree.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/98. Validate Binary Search Tree.md
--------------------------------------------------------------------------------
/350. Intersection of Two Arrays II.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/350. Intersection of Two Arrays II.md
--------------------------------------------------------------------------------
/84. Largest Rectangle in Histogram.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/84. Largest Rectangle in Histogram.md
--------------------------------------------------------------------------------
/102. Binary Tree Level Order Traversal.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/102. Binary Tree Level Order Traversal.md
--------------------------------------------------------------------------------
/121. Best Time to Buy and Sell Stock.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/121. Best Time to Buy and Sell Stock.md
--------------------------------------------------------------------------------
/160. Intersection of Two Linked Lists.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/160. Intersection of Two Linked Lists.md
--------------------------------------------------------------------------------
/81. Search in Rotated Sorted Array II.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/81. Search in Rotated Sorted Array II.md
--------------------------------------------------------------------------------
/83. Remove Duplicates from Sorted List.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/83. Remove Duplicates from Sorted List.md
--------------------------------------------------------------------------------
/114. Flatten Binary Tree to Linked List.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/114. Flatten Binary Tree to Linked List.md
--------------------------------------------------------------------------------
/122. Best Time to Buy and Sell Stock II.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/122. Best Time to Buy and Sell Stock II.md
--------------------------------------------------------------------------------
/107. Binary Tree Level Order Traversal II.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/107. Binary Tree Level Order Traversal II.md
--------------------------------------------------------------------------------
/80. Remove Duplicates from Sorted Array II.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/80. Remove Duplicates from Sorted Array II.md
--------------------------------------------------------------------------------
/82. Remove Duplicates from Sorted List II.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/82. Remove Duplicates from Sorted List II.md
--------------------------------------------------------------------------------
/103. Binary Tree Zigzag Level Order Traversal.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/103. Binary Tree Zigzag Level Order Traversal.md
--------------------------------------------------------------------------------
/108. Convert Sorted Array to Binary Search Tree.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/108. Convert Sorted Array to Binary Search Tree.md
--------------------------------------------------------------------------------
/109. Convert Sorted List to Binary Search Tree.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/109. Convert Sorted List to Binary Search Tree.md
--------------------------------------------------------------------------------
/116. Populating Next Right Pointers in Each Node.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/116. Populating Next Right Pointers in Each Node.md
--------------------------------------------------------------------------------
/117. Populating Next Right Pointers in Each Node II.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/117. Populating Next Right Pointers in Each Node II.md
--------------------------------------------------------------------------------
/105. Construct Binary Tree from Preorder and Inorder Traversal.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/105. Construct Binary Tree from Preorder and Inorder Traversal.md
--------------------------------------------------------------------------------
/106. Construct Binary Tree from Inorder and Postorder Traversall.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zeech3/LeetCode/HEAD/106. Construct Binary Tree from Inorder and Postorder Traversall.md
--------------------------------------------------------------------------------
/50. Pow(x, n).md:
--------------------------------------------------------------------------------
1 | #
一天一道LeetCode系列
2 | ##(一)题目
3 | >Implement pow(x, n).
4 | ##(二)解题
5 | 题目很简单,实现x的n次方。
6 | ```cpp
7 | /*
8 | 需要注意一下几点:
9 | 1.n==0时,返回值为1
10 | 2.x==1时,返回值为1;x==-1时,根据n的奇偶来判断
11 | 3.n==-2147483648,特殊情况,int的范围时-2147483648~2147483647,
12 | */
13 | class Solution {
14 |
15 | public:
16 |
17 | double myPow(double x, int n) {
18 |
19 | if(n==0||x==1) return 1;
20 |
21 |
22 |
23 | if(x==-1&&n%2==0) return 1;
24 |
25 | if(x==-1&&n%2==1) return -1;
26 |
27 |
28 |
29 | if(n==-2147483648) return 1.0/(x*myPow(x,2147483647));
30 |
31 | if(n<0) return 1.0/myPow(x,0-n);
32 |
33 | if(n%2==0) return myPow(x*x,n/2);
34 |
35 | else return myPow(x*x,n/2)*x;
36 |
37 | }
38 |
39 | };
40 |
41 |
42 |
43 | ```
--------------------------------------------------------------------------------
/58. Length of Last Word.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 | >Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
4 |
5 | >If the last word does not exist, return 0.
6 |
7 | >Note: A word is defined as a character sequence consists of non-space characters only.
8 |
9 | >For example,
10 | >Given s = "Hello World",
11 | >return 5.
12 |
13 | ##(二)解题
14 | 题目比较简单,从尾向头找,第一个不为空格的字母,然后再继续找遇到空格为止。纪录单词长度。
15 |
16 | ```cpp
17 |
18 | class Solution {
19 |
20 | public:
21 |
22 | int lengthOfLastWord(string s) {
23 |
24 | if(s.length() == 0) return 0;
25 |
26 | int count = 0;
27 |
28 | int i = s.length()-1;
29 |
30 | while(s[i]==' ') i--;//忽略前面的空格
31 |
32 | while(i>=0&&s[i]!=' ') //当为字母的时候计算长度,为空格就退出循环
33 |
34 | {
35 |
36 | count++;
37 |
38 | i--;
39 |
40 | }
41 |
42 | return count;
43 |
44 | }
45 |
46 | };
47 |
48 | ```
--------------------------------------------------------------------------------
/38. Count and Say.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 | >The count-and-say sequence is the sequence of integers beginning as follows:
4 | >1, 11, 21, 1211, 111221, ...
5 |
6 | >1 is read off as "one 1" or 11.
7 | >11 is read off as "two 1s" or 21.
8 | >21 is read off as "one 2, then one 1" or 1211.
9 |
10 | >Given an integer n, generate the nth sequence.
11 |
12 | >Note: The sequence of integers will be represented as a string.
13 |
14 | ##(二)解题
15 | ```cpp
16 | /*
17 | 首先初始化字符串为1,对应一个1,读成11
18 | 字符串更新为11,对应两个1,读成21
19 | 字符串更新为21,对应1个2一个1,读成1211
20 | ....
21 | 依次进行n次则得到最后的字符串
22 | */
23 | class Solution {
24 | public:
25 | string countAndSay(int n) {
26 | string str = "1";
27 | while(--n)
28 | {
29 | string ret;
30 | for (int i = 0; i < str.length(); ) {
31 | int count = 0;
32 | while (i < str.length() && str[i] == str[i + 1]) {
33 | count++;
34 | i++;
35 | }
36 | ret += ('1' + count);
37 | ret += str[i];
38 | i++;
39 | }
40 | str = ret;
41 | }
42 | return str;
43 | }
44 | };
45 | ```
--------------------------------------------------------------------------------
/27. Remove Element.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 | >Given an array and a value, remove all instances of that value in place and return the new length.
4 |
5 | >Do not allocate extra space for another array, you must do this in place with constant memory.
6 |
7 | >The order of elements can be changed. It doesn't matter what you leave beyond the new length.
8 |
9 | >Example:
10 | >Given input array nums = [3,2,2,3], val = 3
11 |
12 | >Your function should return length = 2, with the first two elements of nums being 2.
13 |
14 | ##(二)解题
15 |
16 | 解题思路见注释
17 |
18 | ```cpp
19 |
20 | /*
21 |
22 | 在一个vector中删除指定的元素,用到erase()函数,注意迭代器会失效
23 |
24 | erase()会返回被删除元素的下一个元素的迭代器
25 |
26 | */
27 |
28 | class Solution {
29 |
30 | public:
31 |
32 | int removeElement(vector& nums, int val) {
33 |
34 | for(auto iter = nums.begin();iter!=nums.end();){
35 |
36 | if(*iter == val){
37 |
38 | iter = nums.erase(iter);//iter指向被删除元素的下一个元素
39 |
40 | }
41 |
42 | else
43 |
44 | ++iter;
45 |
46 | }
47 |
48 | return nums.size();
49 |
50 | }
51 |
52 | };
53 |
54 | ```
--------------------------------------------------------------------------------
/41. First Missing Positive.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 | >Given an unsorted integer array, find the first missing positive integer.
4 |
5 | >For example,
6 | >Given [1,2,0] return 3,
7 | >and [3,4,-1,1] return 2.
8 |
9 | >Your algorithm should run in O(n) time and uses constant space.
10 |
11 | ##(二)解题
12 |
13 | ```cpp
14 | /*
15 | 首先对初始vector进行排序,然后设定一个target=1
16 | 从第一个大于0的数开始,如果等于target的数后就+1,直到下一个数不能于target为止
17 | 如果不能于就返回target
18 | 如果数组中找完了都没有返回,则返回target+1;
19 | 当然这里要考虑一种特殊情况:数组中有重复的数需要排除
20 | */
21 | class Solution {
22 | public:
23 | int firstMissingPositive(vector& nums) {
24 | sort(nums.begin(),nums.end());
25 | int target = 1;
26 | for(int i = 0 ; i < nums.size() ; i++)
27 | {
28 | if(nums[i]>0)
29 | {
30 | if(nums[i] == target)
31 | {
32 | target++;//注意这里已经+1了,最后返回直接返回target
33 | }
34 | else if(i>0 &&nums[i]!=nums[i-1])//排除重复数字
35 | {
36 | return target;
37 | }
38 | }
39 | }
40 | return target;//如果找不到空缺的就返回target+1
41 | }
42 | };
43 | ```
--------------------------------------------------------------------------------
/13. Roman to Integer.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 |
4 | > Given a roman numeral, convert it to an integer.
5 | >
6 | > Input is guaranteed to be within the range from 1 to 3999.
7 |
8 | ##(二)解题
9 | 和上一题相反,这题将罗马数字转换成整形数。
10 | 注意到 4,9,40,90,400,900这些特殊的数字的区别就不难写出代码了。
11 | ```
12 | class Solution {
13 | public:
14 | int romanToInt(string s) {
15 | int ret=0;
16 | for(auto iter = s.begin() ; iter!=s.end() ; ++iter)
17 | {
18 | if((iter+1)!=s.end() && tonum(*iter) < tonum(*(iter+1)))
19 | {
20 | ret += tonum(*(iter+1))-tonum(*iter);
21 | ++iter;
22 | }
23 | else
24 | ret += tonum(*iter);
25 | }
26 | return ret;
27 | }
28 |
29 | int tonum(char ch)
30 | {
31 | switch(ch)
32 | {
33 | case 'I' : return 1;
34 | case 'V' : return 5;
35 | case 'X' : return 10;
36 | case 'L' : return 50;
37 | case 'C' : return 100;
38 | case 'D' : return 500;
39 | case 'M' : return 1000;
40 | }
41 | }
42 |
43 | };
44 | ```
--------------------------------------------------------------------------------
/11. Container With Most Water.md:
--------------------------------------------------------------------------------
1 | # 一天一道LeetCode系列
2 |
3 | ##(一)题目
4 |
5 | > 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.
6 | >
7 | > Note: You may not slant the container.
8 |
9 | ##(二)解题
10 | 题意:给定一组高度值,选取其中两个使得两者构成的容器的容量最大。
11 | 按照题意,一个双重循环可以很简单的解决问题,可是复杂度太高了,O(n^2)。
12 | 那么我们可以寻找O(n)的解法。
13 | 其实也比较简单,定义两个指针,分别指向头和尾,由于容易装水的容量是由小端决定,所以指针移动的准则就是小端指针移动。
14 | 只需要遍历一遍就能得到最大值。
15 | ```
16 | class Solution {
17 | public:
18 | int maxArea(vector& height) {
19 | int i = 0;
20 | int j = height.size()-1;
21 | int max=0;
22 | while(j>i)
23 | {
24 | int con = 0;
25 | int min = height[i]>height[j]?height[j]:height[i];
26 | if(j==i+1){con = min;}
27 | else
28 | con = min *(j-i);
29 | if(height[i]>height[j])
30 | {
31 | j--;
32 | }
33 | else i++;
34 | if(con>max) max=con;
35 | }
36 | return max;
37 | }
38 | };
39 | ```
--------------------------------------------------------------------------------
/9. Palindrome Number.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 |
4 | > Determine whether an integer is a palindrome. Do this without extra
5 | > space.
6 | > Some hints:
7 | > Could negative integers be palindromes? (ie, -1)
8 | >
9 | > If you are thinking of converting the integer to string, note the
10 | > restriction of using extra space.
11 | >
12 | > You could also try reversing an integer. However, if you have solved
13 | > the problem "Reverse Integer", you know that the reversed integer
14 | > might overflow. How would you handle such case?
15 | >
16 | > There is a more generic way of solving this problem.
17 |
18 | ##(二)解题
19 | 题目需要判断一个整数是不是回文数。需要注意一下几点:、
20 | 1、负数不是回文数
21 | 2、回文数满足反转后与原数相等,在反转整数那一题里面提到需要考虑越界问题,所以需要将int转换成long来处理。
22 | 代码比较简单,如下:
23 |
24 | ```
25 | class Solution {
26 | public:
27 | bool isPalindrome(int x) {
28 | if(x<0) return false;
29 | else{
30 | long n = 0;
31 | long temp = x;//考虑到反过来越界
32 | long lx = x;
33 | while(temp)
34 | {
35 | n = n*10+temp%10;//反转int数
36 | temp = temp/10;
37 | }
38 | if(n==lx) return true; //与原数相等则返回true
39 | else return false;
40 | }
41 | }
42 | };
43 | ```
--------------------------------------------------------------------------------
/24. Swap Nodes in Pairs.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 | >Given a linked list, swap every two adjacent nodes and return its head.
4 | For example,
5 | Given 1->2->3->4, you should return the list as 2->1->4->3.
6 |
7 | Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
8 |
9 | ##(二)解题
10 | 给定一个链表,交换相邻两个节点,这道题要特别注意越界问题。
11 |
12 | 评级easy的题!就不多废话了。
13 |
14 | ```cpp
15 | /**
16 | * Definition for singly-linked list.
17 | * struct ListNode {
18 | * int val;
19 | * ListNode *next;
20 | * ListNode(int x) : val(x), next(NULL) {}
21 | * };
22 | */
23 | class Solution {
24 | public:
25 | ListNode* swapPairs(ListNode* head) {
26 | if(head == NULL) return NULL;
27 | ListNode* p = head;
28 | ListNode* pnext = head->next;
29 | while(p!=NULL&&pnext!=NULL)
30 | {
31 | int tmp = pnext->val;
32 | pnext->val = p->val;
33 | p->val = tmp;
34 | if(pnext->next !=NULL) p = pnext->next; //考虑越界问题,如[1,2,3,4]
35 | else p=NULL;
36 | if(p!= NULL && p->next != NULL) pnext = p->next;//考虑越界问题,如[1,2,3,4,5]
37 | else pnext=NULL;
38 | }
39 | return head;
40 | }
41 | };
42 | ```
--------------------------------------------------------------------------------
/35. Search Insert Position.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 | >Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would >be if it were inserted in order.
4 |
5 | >You may assume no duplicates in the array.
6 |
7 | >Here are few examples.
8 | >[1,3,5,6], 5 → 2
9 | >[1,3,5,6], 2 → 1
10 | >[1,3,5,6], 7 → 4
11 | >[1,3,5,6], 0 → 0
12 |
13 | ##(二)解题
14 |
15 | ```cpp
16 |
17 | /*
18 |
19 | 本题的思路是:如果目标数大于vector中的最大数,就返回vector的长度,即插在最后面
20 |
21 | 如果目标是小于vector中的最小数,就返回0,即插在最前面
22 |
23 | 如果在vector范围内,就用二分法查找,如果有等于target就返回其序号,如果没有即在i=j时退出,返回i表示target的插入位置
24 |
25 | */
26 |
27 |
28 | class Solution {
29 |
30 | public:
31 |
32 | int searchInsert(vector& nums, int target) {
33 |
34 | int len = nums.size();
35 |
36 | if(target > nums[len-1]) return len;
37 |
38 | if(target < nums[0]) return 0;
39 |
40 | int i = 0;
41 |
42 | int j = len-1;
43 |
44 | while(i<=j)
45 |
46 | {
47 |
48 | int mid = (i+j)/2;
49 |
50 | if(nums[mid] == target) return mid;
51 |
52 | else if(nums[mid]>target) j=mid-1;
53 |
54 | else i = mid+1;
55 |
56 | }
57 |
58 | return i;
59 |
60 | }
61 |
62 | };
63 |
64 | ```
--------------------------------------------------------------------------------
/36. Valid Sudoku.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode
2 | >本系列文章已全部上传至我的github,地址:https://github.com/Zeecoders/LeetCode
3 | >欢迎转载,转载请注明出处
4 | ##(一)题目
5 | >Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
6 |
7 | >The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
8 |
9 | >A partially filled sudoku which is valid.
10 |
11 | ##(二)解题
12 | 判断一个数独有效,从三个方面检查:
13 | 1、每一行包含1~9,且无重复
14 | 2、每一列包含1~9,且无重复
15 | 3、每一个3*3矩阵中包含1~9,切勿重复
16 | ```cpp
17 | class Solution {
18 | public:
19 | bool isValidSudoku(vector>& board) {
20 | int row[9][9] = {0};//每一行的检验矩阵
21 | int col[9][9] = {0};//每一列的检验矩阵
22 | int cross[9][9] = {0};//每一个3*3矩阵的检验矩阵
23 | for(int i = 0;i < 9;i++)
24 | {
25 | for(int j = 0 ; j < 9 ;j++)
26 | {
27 | int num = board[i][j] - '1';
28 | if(board[i][j]!='.')
29 | {
30 | if(row[i][num]++) rturn false;//第i行出现num数字,如果为0,则标记为1,如果非零代表重复
31 | if(col[j][num]++) return false;//如上
32 | if(cross[i/3*3+j/3][num]++) return false;//将数独分为9个3*3矩阵,第i/3*3+j/3个矩阵出现num数字,其他如上
33 | }
34 | }
35 | }
36 | return true;
37 | }
38 | };
39 | ```
40 |
41 |
--------------------------------------------------------------------------------
/7. Reverse Integer.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 |
4 | > Reverse digits of an integer.
5 | > Example1: x = 123, return 321
6 | > Example2: x = -123, return -321
7 |
8 | ##(二)解题
9 | 这题看上去很简单,动笔一挥之下,写出如下代码:
10 |
11 | ```
12 | class Solution {
13 | public:
14 | int reverse(int x) {
15 | bool flag = false;
16 | if(x<0) {
17 | x=-k;
18 | flag = true;
19 | }
20 | long result=0;
21 | while(x!=0)
22 | {
23 | result*=10;
24 | result+=x%10;
25 | x=x/10;
26 | }
27 | return flag==true ?-result:result;
28 | }
29 | };
30 | ```
31 | 满心以为一步就能Accepted。没想到直接wrong answer!!
32 | 1534236469反过来9646324351超过了int的最大值,于是修改代码:
33 | ```
34 | class Solution {
35 | public:
36 | int reverse(int x) {
37 | long k = x;
38 | bool flag = false;
39 | if(k<0) {
40 | k=-k;
41 | flag = true;
42 | }
43 | long result=0;
44 | while(k!=0)
45 | {
46 | result*=10;
47 | result+=k%10;
48 | k=k/10;
49 | }
50 | if(result>2147483648||result<-2147483647) return 0;//判断越界没有
51 | else return flag==true ?(int)-result:(int)result;//结果判断正负输出
52 | }
53 | };
54 | ```
55 | 这下能accepted了!果然越是看起来简单的题目越需要细节处理!
--------------------------------------------------------------------------------
/26. Remove Duplicates from Sorted Array.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 | >Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
4 |
5 | >Do not allocate extra space for another array, you must do this in place with constant memory.
6 |
7 | >For example,
8 | >Given input array nums = [1,1,2],
9 |
10 | >Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.
11 |
12 | ##(二)解题
13 |
14 | ```cpp
15 |
16 | /*
17 |
18 | 解题:排好序的数据,删除里面重复的数据
19 |
20 | 需要注意以下两点:
21 |
22 | 1.erase()调用之后迭代器失效,需要将iter = nums.erase(iter);
23 |
24 | 2.考虑nums为空或者只有1个的情况,可以直接返回
25 |
26 | */
27 |
28 | class Solution {
29 |
30 | public:
31 |
32 | int removeDuplicates(vector& nums) {
33 |
34 | if(nums.size()<=1) return nums.size();
35 |
36 | auto iter = nums.begin() +1;
37 |
38 | for(;iter!=nums.end();)
39 |
40 | {
41 |
42 | if(*iter == *(iter-1))
43 |
44 | {
45 |
46 | iter = nums.erase(iter);//关键!erase()返回的是删除的数据的下一个迭代器
47 |
48 | }
49 |
50 | else
51 |
52 | ++iter;//没有删除元素的时候+1
53 |
54 | }
55 |
56 | return nums.size();
57 |
58 | }
59 |
60 | };
61 |
62 | ```
--------------------------------------------------------------------------------
/55. Jump Game.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 |
4 | >Given an array of non-negative integers, you are initially positioned at the first index of the array.
5 | Each element in the array represents your maximum jump length at that position.
6 | Determine if you are able to reach the last index.
7 | For example:
8 | A = [2,3,1,1,4], return true.
9 | A = [3,2,1,0,4], return false.
10 |
11 | ##(二)解题
12 |
13 | 思路可以参考这篇博文:[【一天一道LeetCode】#45. Jump Game II](http://blog.csdn.net/terence1212/article/details/51353209)
14 |
15 | 考虑在O(n)复杂度的情况下解决此题。用两个参数来lastmax和curmax来存储i前面能跳到的最远距离和当前能跳到的最远距离,如果此刻i还在lastmax之内,就要更新lastmax的值为max(lastmax,curmax)
16 |
17 | ```cpp
18 |
19 | /*
20 |
21 | 代码很简单,主要注意两个点:
22 |
23 | 1、i小于lastmax才能改变lastmax的值
24 |
25 | 2、是否能跳到重点取决于lastmax的值
26 |
27 | */
28 |
29 | class Solution {
30 |
31 | public:
32 |
33 | bool canJump(vector& nums) {
34 |
35 | int lastmax = 0;
36 |
37 | int curmax = 0;
38 |
39 | for(int i = 0 ; i < nums.size() ; i++)
40 |
41 | {
42 |
43 | curmax = i+nums[i];
44 |
45 | if(i<=lastmax)
46 |
47 | {
48 |
49 | lastmax = max(lastmax,curmax);
50 |
51 | }
52 |
53 | }
54 |
55 | if(lastmax >=nums.size()-1) return true;
56 |
57 | else return false;
58 |
59 | }
60 |
61 | };
62 |
63 | ```
--------------------------------------------------------------------------------
/22. Generate Parentheses.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode
2 | ##(一)题目
3 |
4 | > Given n pairs of parentheses, write a function to generate all
5 | > combinations of well-formed parentheses.
6 | >
7 | > For example, given n = 3, a solution set is:
8 | >
9 | >> "((()))", "(()())", "(())()", "()(())", "()()()"
10 | ##(二)解题
11 | 在[ 【一天一道LeetCode】#20. Valid Parentheses](http://blog.csdn.net/terence1212/article/details/51175915)一文中提到怎么判断该组括号有效,另外在[【一天一道LeetCode】#17. Letter Combinations of a Phone Number](http://blog.csdn.net/terence1212/article/details/51153263)一文中用到回溯法。本题结合这两题的思路来解决。
12 | 假设在位置k之后,如果'('的数量还有剩余则可以继续添加;那么要添加')',则必须满足其剩余的数量大于0且比'('剩余的数量大,才可以添加,否则就不是一个有效的括号组。
13 |
14 | ```
15 | class Solution {
16 | public:
17 | vector ret;
18 | vector generateParenthesis(int n) {
19 | string str;
20 | generate(str , n , n);
21 | return ret;
22 | }
23 | void generate(string str , int m , int n)
24 | {
25 | if(m==0)//
26 | {
27 | while(n--) str+=')';//如果‘(’没有剩余的了,就直接把剩余的')'加上
28 | ret.push_back(str);
29 | return;
30 | }
31 | if(m>0)//如果‘(’剩余,可以继续添加'('
32 | {
33 | generate(str+'(',m-1,n);
34 | }
35 | if(m0)//如果m0,可以继续添加')'
36 | {
37 | generate(str+')',m,n-1);
38 | }
39 | }
40 | };
41 | ```
--------------------------------------------------------------------------------
/19. Remove Nth Node From End of List.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 |
4 | > Given a linked list, remove the nth node from the end of list and return its head.
5 | >
6 | >> For example,
7 | > Given linked list: 1->2->3->4->5, and n = 2. After
8 | > removing the second node from the end, the linked list becomes 1->2->3->5.
9 | ##(二)解题
10 | 剑指上面的经典题目了。两个指针,一个指向head,一个指向正数第K-1个,同时移动,知道第K-1的指针指向NULL。则指向head的数就是倒数第K个。
11 | 删除节点的时候要区分头节点和其他节点。
12 |
13 | ```
14 | /**
15 | * Definition for singly-linked list.
16 | * struct ListNode {
17 | * int val;
18 | * ListNode *next;
19 | * ListNode(int x) : val(x), next(NULL) {}
20 | * };
21 | */
22 | class Solution {
23 | public:
24 | ListNode* removeNthFromEnd(ListNode* head, int n) {
25 | if(n == 0) return head;
26 | ListNode* ptemp = head;
27 | for(int i = 0 ; i < n ;i++)
28 | {
29 | ptemp = ptemp->next;
30 | }
31 | ListNode* pNth = head;
32 | ListNode* pre = head;
33 | while(ptemp!= NULL)
34 | {
35 | pre = pNth;
36 | ptemp = ptemp->next;
37 | pNth = pNth->next;
38 | }
39 | if(pNth == head)//如果是头节点
40 | {
41 | head = head->next;
42 | }
43 | else pre->next = pNth->next;//非头节点
44 | free(pNth);
45 | return head;
46 | }
47 | };
48 | ```
--------------------------------------------------------------------------------
/31. Next Permutation.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 | >Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
4 |
5 | >If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
6 |
7 | >The replacement must be in-place, do not allocate extra memory.
8 |
9 | >Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
10 | >>1,2,3 → 1,3,2
11 | 3,2,1 → 1,2,3
12 | 1,1,5 → 1,5,1
13 |
14 | ##(二)解题
15 |
16 | ```
17 |
18 | /*
19 |
20 | 本题用到STL中next_Permutation的思想:
21 |
22 | (1)首先从右到左找到第一个破坏升序的值a,
23 |
24 | (2)然后再从右至左找到第一个比a大的数b,
25 |
26 | (3)交换a和b,
27 |
28 | (4)再把交换后的a的位置之后的数反转。
29 |
30 | 如1,4,5,3,1
31 |
32 | 第一步找到4,第二步找到5,交换4,5得到15431,然后反转5以后的数,得到15134即为所求。
33 |
34 | */
35 |
36 | class Solution {
37 |
38 | public:
39 |
40 | void nextPermutation(vector& nums) {
41 |
42 | int len = nums.size();
43 |
44 | if(len!=1){
45 |
46 | int i = len-2;
47 |
48 | while(i>=0 &&nums[i]>=nums[i+1]) i--;
49 |
50 | int j =len-1;
51 |
52 | while(j>i &&nums[j]<=nums[i]) j--;
53 |
54 | if(i>=0) swap(nums[i],nums[j]);
55 |
56 | reverse(nums.begin()+i+1,nums.end());
57 |
58 | }
59 |
60 | }
61 |
62 | };
63 |
64 | ```
--------------------------------------------------------------------------------
/46. Permutations.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 | >Given a collection of distinct numbers, return all possible permutations.
4 |
5 | >>For example,
6 | >>[1,2,3] have the following permutations:
7 | >>[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
8 |
9 | ##(二)解题
10 |
11 | 求全排列数。具体思路可以参考[【一天一道LeetCode】#31. Next Permutation](https://leetcode.com/problems/next-permutation/)这篇博客。
12 |
13 | ```cpp
14 |
15 |
16 | class Solution {
17 |
18 | public:
19 |
20 | vector> permute(vector& nums) {
21 |
22 | vector> ret;
23 |
24 | sort(nums.begin(),nums.end());
25 |
26 | do{
27 |
28 | ret.push_back(nums);
29 |
30 | }while(nextpermute(nums));
31 |
32 | return ret;
33 |
34 | }
35 |
36 | bool nextpermute(vector& nums)
37 |
38 | {
39 |
40 | int i = nums.size() -2;
41 |
42 | while(i>=0 && nums[i] > nums[i+1]) i--;//找到第一个破坏升序的数,
43 |
44 | int j = nums.size()-1;
45 |
46 | while(j>=0 && nums[j] < nums[i]) j--;//找到第一个大于i的数
47 |
48 | if(i>=0)
49 |
50 | {
51 |
52 | swap(nums[i],nums[j]);//交换i和j
53 |
54 | reverse(nums.begin()+i+1,nums.end());//将i以后的数反转
55 |
56 | return true;//如果还存在下一个全排列数就返回true
57 |
58 | }
59 |
60 | return false;//如果数组已经为倒序了就说明没有下一个了,返回false
61 |
62 | }
63 |
64 | };
65 |
66 | ```
67 |
--------------------------------------------------------------------------------
/14 Longest Common Prefix.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目:
3 |
4 | > Write a function to find the longest common prefix string amongst an
5 | > array of strings.
6 | ##(二)题意
7 | 求一组字符串中的最长前缀字符串。
8 | 举例:字符串组:abc,ab,abdef,abws 最长前缀字符串:ab
9 |
10 | 我的解法是先求出这组字符串中最短的,然后依次匹配,遇到不同的就退出。
11 |
12 | ```
13 | class Solution {
14 | public:
15 | string longestCommonPrefix(vector& strs) {
16 | if(strs.size()==0) return "";
17 | if(strs.size()==1) return strs[0];
18 |
19 | string minstr=strs[0];
20 | string compre="";
21 | int minlen=strs[0].length();
22 | for(int i = 0 ; i一天一道LeetCode系列
2 | ##(一)题目
3 | >Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
4 |
5 | >For "(()", the longest valid parentheses substring is "()", which has length = 2.
6 |
7 | >Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.
8 |
9 |
10 | ##(二)解题
11 | ```cpp
12 | /*
13 | stack法思想:和Valid Parentheses一样,用stack来解决,只不过栈中记录的是每个‘(’的下标
14 | 1.首先在栈里面压入初始值-1(初始匹配失败的下标), 如果是‘(’就直接把‘(’的下标压进栈
15 | 2. 如果是‘)’开始判断
16 | (1) 如果此刻栈的大小大于1,则将栈顶元素弹出,将下标减去当前的栈顶元素即为当前有效串的长度
17 | (2) 如果此刻栈的大小小于等于1,则代表匹配失败,更新目前匹配失败的下标。
18 | */
19 | class Solution {
20 | public:
21 | int longestValidParentheses(string s) {
22 | stack stmp;
23 | stmp.push(-1);
24 | int max = 0;
25 | for(int i = 0 ; i < s.length() ; i++){
26 | if(s[i] == '(')
27 | {
28 | stmp.push(i);
29 | }
30 | else
31 | {
32 | if(stmp.size()>1)
33 | {
34 | stmp.pop();
35 | int len = i - stmp.top();
36 | max = max>len?max:len;
37 | }
38 | else
39 | {
40 | stmp.pop();
41 | stmp.push(i);
42 | }
43 | }
44 | }
45 | return max;
46 | }
47 | };
48 | ```
--------------------------------------------------------------------------------
/47. Permutations II.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 | >Given a collection of numbers that might contain duplicates, return all possible unique permutations.
4 |
5 | >>For example,
6 | >>[1,1,2] have the following unique permutations:
7 | >>[1,1,2], [1,2,1], and [2,1,1].
8 |
9 | ##(二)解题
10 |
11 | 求全排列数。具体思路可以参考[【一天一道LeetCode】#46. Permutations](http://blog.csdn.net/terence1212/article/details/51362681)这篇博客。
12 | 不同之处:上一题没有重复的数字,这一题有重复的数字
13 |
14 | ```cpp
15 |
16 |
17 | class Solution {
18 |
19 | public:
20 |
21 | vector> permute(vector& nums) {
22 |
23 | vector> ret;
24 |
25 | sort(nums.begin(),nums.end());
26 |
27 | do{
28 |
29 | ret.push_back(nums);
30 |
31 | }while(nextpermute(nums));
32 |
33 | return ret;
34 |
35 | }
36 |
37 | bool nextpermute(vector& nums)
38 |
39 | {
40 |
41 | int i = nums.size() -2;
42 |
43 | while(i>=0 && nums[i] >= nums[i+1]) i--;//考虑到有相等的情况,这里需要找到第一个破坏非降序的数
44 |
45 | int j = nums.size()-1;
46 |
47 | while(j>=0 && nums[j] <= nums[i]) j--;//找到第一个大于i的数
48 |
49 | if(i>=0)
50 |
51 | {
52 |
53 | swap(nums[i],nums[j]);//交换i和j
54 |
55 | reverse(nums.begin()+i+1,nums.end());//将i以后的数反转
56 |
57 | return true;//如果还存在下一个全排列数就返回true
58 |
59 | }
60 |
61 | return false;//如果数组已经为倒序了就说明没有下一个了,返回false
62 |
63 | }
64 |
65 | };
66 |
67 | ```
68 |
69 |
--------------------------------------------------------------------------------
/63. Unique Paths II.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode
2 |
3 | ##(一)题目
4 |
5 | >Follow up for "Unique Paths":
6 |
7 | >Now consider if some obstacles are added to the grids. How many unique paths would there be?
8 |
9 | >An obstacle and empty space is marked as 1 and 0 respectively in the grid.
10 |
11 | >For example,
12 |
13 | >There is one obstacle in the middle of a 3x3 grid as illustrated below.
14 |
15 | >[
16 |
17 | >[0,0,0],
18 |
19 | > [0,1,0],
20 |
21 | > [0,0,0]
22 |
23 | >]
24 |
25 | >The total number of unique paths is 2.
26 |
27 |
28 |
29 | ##(二)解题
30 |
31 | 解题思路:参考上一篇博文[【一天一道LeetCode】#62. Unique Paths](http://blog.csdn.net/terence1212/article/details/51502144)
32 |
33 | ```
34 |
35 | class Solution {
36 |
37 | public:
38 |
39 | int dp[101][101];
40 |
41 | int uniquePathsWithObstacles(vector>& obstacleGrid) {
42 |
43 | int row = obstacleGrid.size();
44 |
45 | int col = 0;
46 |
47 | if(row!=0) col = obstacleGrid[0].size();
48 |
49 | if(obstacleGrid[0][0]==1) return 0;//起始点不通则直接返回0
50 |
51 | for(int i = row-1 ; i>=0 ; i--)
52 |
53 | for(int j = col-1 ; j>=0 ; j--)
54 |
55 | {
56 |
57 | if(obstacleGrid[i][j]==1) dp[i][j] = 0;//代表此路不通
58 |
59 | else if(i==row-1&&j==col-1) dp[i][j] = 1;//规定终点的dp为1
60 |
61 | else dp[i][j] = dp[i+1][j]+dp[i][j+1];
62 |
63 | }
64 |
65 | return dp[0][0];
66 |
67 | }
68 |
69 | ```
70 |
71 |
--------------------------------------------------------------------------------
/61. Rotate List.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 | >Given a list, rotate the list to the right by k places, where k is non-negative.
4 |
5 | >For example:
6 | >Given 1->2->3->4->5->NULL and k = 2,
7 | >return 4->5->1->2->3->NULL.
8 |
9 |
10 | ##(二)解题
11 | 本题的思路:
12 | 1、找到倒数第K个节点
13 | 2、将k以后的节点移动到前面来,与头结点相连。
14 | 3、新的头结点就是倒数第k个节点。
15 | 需要注意一下几种特殊情况:
16 | 1、链表为空或者链表只有一个节点
17 | 2、k的值为0或者k的值大于链表的长度
18 | ```cpp
19 | /**
20 | * Definition for singly-linked list.
21 | * struct ListNode {
22 | * int val;
23 | * ListNode *next;
24 | * ListNode(int x) : val(x), next(NULL) {}
25 | * };
26 | */
27 | class Solution {
28 | public:
29 | ListNode* rotateRight(ListNode* head, int k) {
30 | if(k==0||head == NULL || head->next==NULL) return head;
31 | ListNode* pkth = head;//记录倒数第k个节点
32 | ListNode* pLast = head;//记录最后一个节点
33 | ListNode* ptemp =NULL;//倒数第K+1个节点
34 | ListNode* p = head;
35 | int length = 0;
36 | while(p!=NULL)//求出链表的长度
37 | {
38 | p=p->next;
39 | ++length;
40 | }
41 | k %=length;//保证k在0~length之间
42 | if(k==0) return head;//k等于0直接返回head
43 | while(pLast != NULL && --k) pLast = pLast->next;//找到正数第K个节点
44 | while(pLast->next !=NULL){//找到倒数第K个节点
45 | ptemp = pkth;//这里用到两个指针,pLast和pkth同时移动,最后pkth就是倒数第K个节点
46 | pkth = pkth->next;
47 | pLast = pLast->next;
48 | }
49 | ptemp->next = NULL;
50 | pLast->next = head;//调整链表
51 | return pkth;
52 | }
53 | };
54 | ```
--------------------------------------------------------------------------------
/20. Valid Parentheses.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 |
4 | > Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
5 | >
6 | > The brackets must close in the correct order, "()" and "()[]{}" are
7 | > all valid but "(]" and "([)]" are not.
8 | ##(二)解题
9 | 本题的关键在于利用stack,想到了stack就不难写出代码了。
10 | 每次碰到(,{,[就压栈,碰到),},],就判断栈顶元素匹配上就出栈,匹配不上就返回false.
11 | 下面是Accepted的代码,复杂度为0(n):
12 |
13 | ```
14 | class Solution {
15 | public:
16 | bool isValid(string s) {
17 | stack tmp;
18 | for(int i = 0 ; i < s.length() ; i++)
19 | {
20 | if(s[i] == '(' || s[i] == '{' || s[i] == '[')
21 | {
22 | tmp.push(s[i]);
23 | }
24 | else if(s[i] == ')' || s[i] == '}' || s[i] == ']')
25 | {
26 | if(tmp.empty()) return false;
27 | switch(s[i])
28 | {
29 | case ')':
30 | if(tmp.top() == '(') tmp.pop();
31 | else return false;
32 | break;
33 | case ']':
34 | if(tmp.top() == '[') tmp.pop();
35 | else return false;
36 | break;
37 | case '}':
38 | if(tmp.top() == '{') tmp.pop();
39 | else return false;
40 | break;
41 | }
42 | }
43 | }
44 | if(tmp.empty()) return true;
45 | else return false;
46 | }
47 | };
48 | ```
--------------------------------------------------------------------------------
/34. Search for a Range.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 | >Given a sorted array of integers, find the starting and ending position of a given target value.
4 |
5 | >Your algorithm's runtime complexity must be in the order of O(log n).
6 |
7 | >If the target is not found in the array, return [-1, -1].
8 |
9 | >For example,
10 | >Given [5, 7, 7, 8, 8, 10] and target value 8,
11 | >return [3, 4].
12 |
13 | ##(二)解题
14 | ```cpp
15 | /*
16 | 首先二分法查找目标值
17 | 然后沿着目标值左右延伸,依次找到相同值得左右边界
18 | */
19 | class Solution {
20 | public:
21 | vector searchRange(vector& nums, int target) {
22 | int i = 0;
23 | int j = nums.size()-1;
24 | int idx = -1;
25 | vector ret;
26 | while(i <= j)
27 | {
28 | int mid = (i+j)/2;
29 | if(nums[mid] == target)
30 | {
31 | idx = mid;
32 | break;
33 | }
34 | else if(nums[mid]>target)
35 | {
36 | j = mid-1;
37 | }
38 | else if(nums[mid]=0 && nums[k] == target) k--;
46 | int m = idx;
47 | while(m一天一道LeetCode
2 | ##(一)题目
3 |
4 | > Given a digit string, return all possible letter combinations that the number could represent.
5 | >
6 | > A mapping of digit to letters (just like on the telephone buttons) is
7 | > given below.
8 | > 
9 | >
10 | >
11 | > > Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf",
12 | > > "cd", "ce", "cf"].
13 | ##(二)解题
14 | 这题采用回溯法。
15 | 以23为例,2对应“abc” ,3对应“def。
16 | 第一步:a,b,c
17 | 第二部:ad,ae,af,bd,be,bf,cd ,ce,cf
18 | 回溯法的意思是,依次递归到最后,如果到最后了就回溯,继续递归。
19 | 算法的过程:
20 | 首先依次递归得到ad,到digits的长度了,回溯得到a
21 | 这下又可以递归了,得到ae,又到digits的长度了,再回溯到a
22 | 然后继续循环得到af,f到头了,a也到头了,轮到b上场了!
23 | .......依次下去就把所有的情况都输出了!
24 |
25 | ```
26 | class Solution {
27 | public:
28 | string phoneStr[10] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
29 | string tmp;
30 | vector result;
31 | vector letterCombinations(string digits) {
32 | if(digits.length()==0) return result;
33 | dfs(digits , 0);
34 | return result;
35 | }
36 | void dfs(string &str , int idx)
37 | {
38 | if(idx == str.length())
39 | {
40 | result.push_back(tmp);//递归结束条件
41 | return;
42 | }
43 | else
44 | {
45 | for(int i = 0 ; i < phoneStr[str[idx]-'0'].length() ; i++)
46 | {
47 | tmp = tmp.substr(0,idx);//回溯!
48 | tmp+=(phoneStr[str[idx]-'0'])[i];
49 | dfs(str,idx+1);
50 | }
51 | }
52 |
53 | }
54 | };
55 | ```
--------------------------------------------------------------------------------
/56. Merge Intervals.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 | >Given a collection of intervals, merge all overlapping intervals.
4 |
5 | >For example,
6 | >Given [1,3],[2,6],[8,10],[15,18],
7 | >return [1,6],[8,10],[15,18].
8 |
9 | ##(二)解题
10 |
11 | ```cpp
12 |
13 | /*
14 |
15 | 本题的解题步骤:
16 |
17 | 1、对vector里面的每个Interval结构体按照start的值升序排列
18 |
19 | 2、遍历整个intervals,如果有重复区域就合并,如果没有就存到ret里面
20 |
21 | */
22 |
23 | /**
24 |
25 | * Definition for an interval.
26 |
27 | * struct Interval {
28 |
29 | * int start;
30 |
31 | * int end;
32 |
33 | * Interval() : start(0), end(0) {}
34 |
35 | * Interval(int s, int e) : start(s), end(e) {}
36 |
37 | * };
38 |
39 | */
40 |
41 | class Solution {
42 |
43 | public:
44 |
45 | vector merge(vector& intervals) {
46 |
47 | vector ret;
48 |
49 | if(intervals.empty()) return ret;
50 |
51 | sort(intervals.begin(),intervals.end(),comparein);///按照start的值升序排列
52 |
53 | Interval tmp = intervals[0];//初始化
54 |
55 | for(int i = 1 ; i < intervals.size() ; i++)
56 |
57 | {
58 |
59 | if(intervals[i].start<=tmp.end) tmp.end = max(tmp.end,intervals[i].end);//更新end
60 |
61 | else{
62 |
63 | ret.push_back(tmp);//没有重复区域就压入ret
64 |
65 | tmp = intervals[i];//更新tmp的值,继续遍历
66 |
67 | }
68 |
69 | }
70 |
71 | ret.push_back(tmp);
72 |
73 | return ret;
74 |
75 | }
76 |
77 | static bool comparein(const Interval& i1 , const Interval& i2)//比较函数
78 |
79 | {
80 |
81 | return i1.start一天一道LeetCode系列
2 | ##(一)题目
3 | >Given two numbers represented as strings, return multiplication of the numbers as a string.
4 |
5 | >>Note:
6 | >>The numbers can be arbitrarily large and are non-negative.
7 | >>Converting the input string to integer is NOT allowed.
8 | >>You should NOT use internal library such as BigInteger.
9 | ##(二)解题
10 | 两个string代表的数字相乘,主要就是要求写出大数相乘的代码,具体看注释
11 | ```
12 | /*
13 | 本题的思路主要是:num1的第i位和num2的第j位相乘等于乘积的第i+j位
14 | m位数和n位数相乘的结果最大位m+n位!
15 | 1.为了便于理解,将两个string首先反转
16 | 2.两个for循环,从num1的0位开始,依次乘上num2的0-size位,注意考虑到进位的问题
17 | 3.对于结果ret,先反转,如果全为0,则直接返回0,否则去掉前面连续的0,即为最后的结果
18 | */
19 | class Solution {
20 | public:
21 | string multiply(string num1, string num2) {
22 | reverse(num1.begin(),num1.end());//反转num1
23 | reverse(num2.begin(),num2.end());//反转num2
24 | string ret(num1.size()+num2.size(),'0');
25 | for(int i = 0 ; i < num1.size() ; i++)
26 | {
27 | int carry = 0;//处理进位
28 | int j = 0;
29 | for(; j < num2.size() ; j++)
30 | {
31 | carry += (ret[i+j]-'0') + (num1[i]-'0')*(num2[j]-'0');
32 | ret[i+j] = ('0'+carry%10) ;
33 | carry /=10;
34 | }
35 | if(carry!=0)//处理最后的进位
36 | {
37 | ret[i+j] = ('0'+carry);
38 | }
39 | }
40 | //对最后的字符串进行处理
41 | reverse(ret.begin(),ret.end());
42 | for(auto iter=ret.begin() ; iter!=ret.end() ; )
43 | {
44 | if(*iter == '0'&&ret.size()>1) iter = ret.erase(iter);//如果为‘0’则删除
45 | else break;//第一位不为‘0’的数就退出
46 | }
47 | return ret;
48 | }
49 | };
50 | ```
51 |
52 |
--------------------------------------------------------------------------------
/48. Rotate Image.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 | >You are given an n x n 2D matrix representing an image.
4 |
5 | >Rotate the image by 90 degrees (clockwise).
6 |
7 | >Follow up:
8 | >Could you do this in-place?
9 |
10 | ##(二)解题
11 |
12 | 90度旋转图像,我们不难看出$$matrix[i][j] = tmp[j][n-i-1]\quad \quad注:tmp=matrix$$经过这样的变换后,图像就旋转了90度。
13 |
14 | ```cpp
15 |
16 |
17 | class Solution {
18 |
19 | public:
20 |
21 | void rotate(vector>& matrix) {
22 |
23 | int n = matrix.size()-1;
24 |
25 | vector> tmp = matrix;//深拷贝
26 |
27 | for(int i = 0 ; i< n+1; i++)
28 |
29 | {
30 |
31 | for(int j = 0 ; j < n+1 ; j++)
32 |
33 | {
34 |
35 | matrix[j][n-i] = tmp[i][j];//赋值转换
36 |
37 | }
38 |
39 | }
40 |
41 | }
42 |
43 | };
44 |
45 | ```
46 | 网上还有一种解法去先转置在对称变换。代码如下:
47 |
48 | ```cpp
49 |
50 | class Solution {
51 |
52 | public:
53 |
54 | void rotate(vector > &matrix) {
55 |
56 | int dim = matrix.size();
57 |
58 | int temp = 0;
59 |
60 | for (int i = 0; i < dim; ++i) { //先转置
61 |
62 | for (int j = i+1; j < dim; ++j) {
63 |
64 | temp = matrix[i][j];
65 |
66 | matrix[i][j] = matrix[j][i];
67 |
68 | matrix[j][i] = temp;
69 |
70 | }
71 |
72 | }
73 |
74 | for (int i = 0; i < dim/2; ++i) { //然后对称变换
75 |
76 | for (int j = 0; j < dim; ++j) {
77 |
78 | temp = matrix[j][i];
79 |
80 | matrix[j][i] = matrix[j][dim - i -1];
81 |
82 | matrix[j][dim - i -1] = temp;
83 |
84 | }
85 |
86 | }
87 |
88 | }
89 |
90 | };
91 |
92 | ```
--------------------------------------------------------------------------------
/52. N-Queens II.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 | >Follow up for N-Queens problem.
4 | 
5 | >Now, instead outputting board configurations, return the total number of distinct solutions.
6 |
7 | ##(二)解题
8 | 具体思路参考[【一天一道LeetCode】#51. N-Queens](http://blog.csdn.net/terence1212/article/details/51435966)
9 | ```cpp
10 | /*
11 | 与N-Queens不同的事,这题只要求输出摆放方式的个数,因此对程序只需要做小的改动
12 | */
13 | class Solution {
14 | public:
15 | int count = 0;//记录次数
16 | vector> queens;//存放已摆放的皇后的坐标值
17 | int totalNQueens(int n) {
18 | int *a = new int[n];//确保每一列只有一个皇后
19 | memset(a,0,n*sizeof(int));
20 | backtrc(a, 0, n);
21 | return count;
22 | }
23 | bool isValid(vector> queens , int row,int col)//
24 | {
25 | if (queens.empty()) return true;
26 | for (int i = 0; i < queens.size();i++)
27 | {
28 | if (abs(row- queens[i].first) == abs(col-queens[i].second))
29 | {
30 | return false;
31 | }
32 | }
33 | return true;
34 | }
35 | void backtrc(int a[], int row, int n)//row确保每一行只有一个皇后
36 | {
37 | if (row == n)//如果摆放完n行,则退出
38 | {
39 | count++;//次数加1
40 | return;
41 | }
42 | for (int i = 0; i < n; i++)
43 | {
44 | if (a[i] == 0&&isValid(queens, row, i))//保证了同一行,同一列,同一对角线只有一个Q
45 | {
46 | a[i] = 1;
47 | queens.push_back(pair(row, i));
48 | backtrc(a, row + 1, n);
49 | //回溯
50 | a[i] = 0;
51 | queens.pop_back();
52 | }
53 | }
54 | }
55 | };
56 | ```
--------------------------------------------------------------------------------
/6. ZigZag Conversion.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 |
4 | > The string "PAYPALISHIRING" is written in a zigzag pattern on a given
5 | > number of rows like this: (you may want to display this pattern in a
6 | > fixed font for better legibility)
7 | >
8 | > P A H N A P L S I I G Y I R And then read line by line:
9 | > "PAHNAPLSIIGYIR" Write the code that will take a string and make this
10 | > conversion given a number of rows:
11 | >
12 | > string convert(string text, int nRows); convert("PAYPALISHIRING", 3)
13 | > should return "PAHNAPLSIIGYIR".
14 |
15 | 题意:
16 | 
17 |
18 | ##(二)解题
19 |
20 | 已知输入条件:初始string s和numRows。可以得出循环间隔gap = 2*numRows-2。
21 | 统计规律:
22 | - 第0行 从j=0开始,间距gap,取s[j]
23 | - 第1~numRows-2行 从j=1开始,间距`gap=(j%gap)一天一道LeetCode系列
2 | ##(一)题目
3 | >Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
4 |
5 | >For example,
6 | >Given the following matrix:
7 |
8 | >>[
9 | [ 1, 2, 3 ],
10 | [ 4, 5, 6 ],
11 | [ 7, 8, 9 ]
12 | ]
13 |
14 |
15 | >You should return [1,2,3,6,9,8,7,4,5].
16 |
17 | ##(二)解题
18 | 相当于顺时针打印矩阵。我想到的方法就是一圈一圈的打印,每一圈的起点分别是(0,0),(1,1).....,那么退出循环打印的条件是什么呢?
19 | 我们可以分析3*3的矩阵有两圈,4*4的矩阵有两圈,5*5的矩阵有三圈,6*6的矩阵有三圈.....
20 | 假设m*n的矩阵,起点位置为(ori,ori),那么满足的条件为m>ori*2&&n>ori*2
21 | 具体思路见代码注释:
22 | ```cpp
23 | class Solution {
24 | public:
25 | vector spiralOrder(vector>& matrix) {
26 | vector ret;
27 | if(matrix.size() ==0) return ret;//矩阵为空的时候直接返回
28 | int ori=0;//每一圈的起点
29 | int row = matrix.size();
30 | int col = matrix[0].size();
31 | int px=ori,py=ori;
32 | int i , j , x, y;
33 | while(row>ori*2 && col > ori*2)//退出循环的条件
34 | {
35 | bool flag1 = false, flag2 = false, flag3 = false;//整圈打印需要连续,如果发生某一个方向没打印就下面的就不需要判断了
36 | for (i = px; i < col - px; i++)//从左往右
37 | {
38 | ret.push_back(matrix[py][i]);
39 | flag1 = true;
40 | }
41 | px = i-1;//i越界了,应该减1
42 | for (j = py+1; j < row - py && flag1; j++)//从上到下
43 | {
44 | ret.push_back(matrix[j][px]);
45 | flag2 = true;
46 | }
47 | py = j-1;//同上
48 | for (x = px-1; x >= ori&&flag2; x--)//从右往左
49 | {
50 | ret.push_back(matrix[py][x]);
51 | flag3 = true;
52 | }
53 | px = x+1;//同上
54 | for (y = py-1; y > ori &&flag3; y--)//从下到上
55 | {
56 | ret.push_back(matrix[y][px]);
57 | }
58 | px = ++ori;//更新起点x
59 | py = ori;//更新起点y
60 | }
61 | return ret;
62 | }
63 | };
64 | ```
--------------------------------------------------------------------------------
/42. Trapping Rain Water.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 | >Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much >water it is able to trap after raining.
4 |
5 | >For example,
6 | >Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
7 |
8 | >
9 |
10 | >The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
11 |
12 | ##(二)解题
13 |
14 | 题目需要求的是矩阵作为容器能盛多少体积的水。
15 | 方法可以参考我的这篇博客:[【一天一道LeetCode】#11Container With Most Water](http://blog.csdn.net/terence1212/article/details/51079744)
16 | ```cpp
17 | /*
18 | 思路:考虑到所盛的水取决于容器两端中小的那一端。因此用两个指针,分别指向头和尾,依次向中间移动。
19 | 1.如果左边小,则左边向右移动一格,这个时候需要判断向右移动一格后
20 | ①如果高度大于原来的就表示盛不下水
21 | ②如果小于原来的则表示有凹下去的部分,这个时候计算高度差就代表能盛多少水。(右边比左边高,可以保证右边不溢出)
22 | 2.如果右边小,则右边向左移动一格,这个时候同1一样判断。
23 | */
24 | class Solution {
25 | public:
26 | int trap(vector& height) {
27 | if(height.size()<=2) return 0;
28 | int ret = 0;
29 | int l = 0;
30 | int r = height.size()-1;
31 | int left = height[0];
32 | int right = height[r];
33 | while(l=left)
39 | {
40 | left = height[l];
41 | }
42 | else ret+=(left-height[l]);
43 | }
44 | else
45 | {
46 | r--;
47 | if(height[r]>=right)
48 | {
49 | right = height[r];
50 | }
51 | else ret +=(right-height[r]);
52 | }
53 | }
54 | return ret;
55 | }
56 | };
57 |
58 | ```
--------------------------------------------------------------------------------
/30. Substring with Concatenation of All Words.md:
--------------------------------------------------------------------------------
1 | 注:这道题之前跳过了,现在补回来
2 |
3 |
4 | ----------
5 |
6 |
7 | #一天一道LeetCode系列
8 | ##(一)题目
9 | >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 wordsexactly once and without any intervening characters.
10 |
11 | >For example, given:
12 | s: "barfoothefoobarman"
13 | words: ["foo", "bar"]
14 |
15 | >You should return the indices: [0,9].
16 | (order does not matter).
17 |
18 |
19 | ##(二)解题
20 | 本题需要在s中找到一串子串,子串是words中的单词按一定顺序排列组成的。返回这个子串在s中的起始位置。
21 | 主要思路:由于要考虑words中的重复单词,需要用到multiset,加快查找速度
22 | 1、首先用multiset存放words中的所有单词
23 | 2、遍历s,如果找到words中的某个单词,就在multiset中删除,直到multiset为空,如果没有找到则继续往后查找
24 | 3、返回下标的集合
25 | ```cpp
26 | class Solution {
27 | public:
28 | vector findSubstring(string s, vector& words) {
29 | multiset cnt;//用来存放words中的单词
30 | for (int i = 0; i < words.size(); i++)
31 | {
32 | cnt.insert(words[i]);//初始化
33 | }
34 | vector ret;
35 | int lenw = words[0].length();
36 | int total = words.size() * lenw;
37 | int i, j;
38 | if (s.length() < total) return ret;
39 | for (i = 0; i <= s.length() - total;i++)
40 | {
41 | multiset tempcnt = cnt;//拷贝一个副本
42 | for (j = i; j < s.length(); j += lenw)
43 | {
44 | string temp = s.substr(j, lenw);
45 | auto iter = tempcnt.find(temp);
46 | if (iter != tempcnt.end())//找到了
47 | {
48 | tempcnt.erase(iter);//先删除该元素
49 | if (tempcnt.empty()) {//为空代表找到了words中的所有单词按一定顺序排列的子串
50 | ret.push_back(i);
51 | break;
52 | }
53 | }
54 | else {//没找到
55 | break;
56 | }
57 | }
58 | }
59 | return ret;
60 | }
61 | };
62 | ```
--------------------------------------------------------------------------------
/1. Two Sum.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 | > Given an array of integers, return indices of the two numbers such
4 | > that they add up to a specific target.
5 | >
6 | > You may assume that each input would have exactly one solution.
7 | >
8 | > *Example: Given nums = [2, 7, 11, 15], target = 9,*
9 | >
10 | > Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. UPDATE
11 | > (2016/2/13): The return format had been changed to zero-based indices.
12 | > Please read the above updated description carefully.
13 |
14 | 题目的意思是:输入一组数组和一个目标值,在数组中找出两个数,他们的和等于目标值,返回两个数的下标。
15 |
16 | ##(二)代码实现
17 |
18 | 初看题目我们可以很快得到以下的答案:
19 |
20 | ```
21 | class Solution {
22 | public:
23 | vector twoSum(vector& nums, int target) {
24 | vector result;
25 | for(int i = 0 ; i < nums.size() ; ++i)
26 | {
27 | for(int j = i+1 ; j twoSum(vector& nums, int target) {
48 | unordered_map map;
49 | vector result;
50 | for(int i = 0 ; i < nums.size() ; ++i)
51 | {
52 | if(map.find(target - nums[i])!=map.end())
53 | {
54 | if(map[target - nums[i]]!=i)
55 | {
56 | result.push_back(map[target - nums[i]]);
57 | result.push_back(i);
58 | return result;
59 | }
60 | }
61 | map[nums[i]] = i;
62 | }
63 | }
64 | };
65 | ```
66 |
67 |
68 |
69 |
--------------------------------------------------------------------------------
/8. String to Integer (atoi).md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 |
4 | > Implement atoi to convert a string to an integer.
5 | >
6 | > Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
7 | >
8 | > Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
9 | >
10 | > Update (2015-02-10): The signature of the C++ function had been updated. If you still see your function signature accepts a const char* argument, please click the reload button to reset your code definition.
11 |
12 | ##(二)解题
13 | 分析特殊情况:
14 | 1、字符前面有空格,“ 010”
15 | 2、数字前或者中间出现了其他的字符“b123”,“ -012b12123”
16 | 3、数字越界,int是-2147483648到2147483647
17 | 4、最奇葩的+-2,我觉得应该输出-2,可是leetcode上显示输出0。
18 | ```
19 | class Solution {
20 | public:
21 | int myAtoi(string str) {
22 | long lresult=0;
23 | int i = 0;
24 | int max=2147483647;
25 | int min=-2147483648;
26 | bool isNegetive = false;
27 | while(str[i] != '\0' && str[i] ==' ') i++;//判断前面是空格的情况
28 | if(str[i] == '-') {isNegetive = true;i++;}//判断正负
29 | else if(str[i] == '+'){i++;}
30 |
31 | while(i='0' && str[i]<='9')
34 | {
35 | lresult*=10;
36 | lresult+=(str[i] - '0');
37 | i++;
38 | }
39 | else break;//出现其他字符干扰则退出循环
40 | //检查越界情况
41 | long lresult_temp = (isNegetive == true) ?-lresult:lresult;
42 | if(!isNegetive&&lresult_temp>=max) return max;
43 | if(isNegetive&&lresult_temp<=min) return min;
44 | }
45 | return (isNegetive == true) ?-lresult:lresult;//输出结果
46 |
47 | }
48 | };
49 | ```
50 | 感觉做这道题还是自己考虑的情况不够多,总是遗漏了一些特殊情况。
--------------------------------------------------------------------------------
/59. Spiral Matrix II.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 | >Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
4 |
5 | >For example,
6 | >Given n = 3,
7 |
8 | >You should return the following matrix:
9 |
10 | >[
11 | >[ 1, 2, 3 ],
12 | >[ 8, 9, 4 ],
13 | >[ 7, 6, 5 ]
14 | >]
15 | ##(二)解题
16 |
17 | 思路参考: [【一天一道LeetCode】#54. Spiral Matrix](http://blog.csdn.net/terence1212/article/details/51459045)
18 |
19 | 还是一样按圈赋值,每一圈的起点分别为(0,0),(1,1).....
20 |
21 | ```cpp
22 |
23 | class Solution {
24 |
25 | public:
26 |
27 | vector> generateMatrix(int n) {
28 |
29 | vector> ret;
30 |
31 | if(n==0) return ret;
32 |
33 | for(int i = 0 ; i < n ; i++)
34 |
35 | {
36 |
37 | vector tmp(n,0);
38 |
39 | ret.push_back(tmp);
40 |
41 | }
42 |
43 | int count = 0 ;
44 |
45 | int px = 0 , py = 0;//初始值
46 |
47 | int start = 0;//每一圈的起点
48 |
49 | while(start=start ; i--){//从右往左
72 |
73 | ret[px][i] = ++count;
74 |
75 | }
76 |
77 | py = i+1;
78 |
79 | for(i = px-1 ; i>=start + 1 ; i--){//从下往上
80 |
81 | ret[i][py] = ++count;
82 |
83 | }
84 |
85 | start++;
86 |
87 | px = py = start;//下一圈
88 |
89 | }
90 |
91 | if(n%2==1) ret[px][py] =++count;//n为奇数的时候需要考虑中心值
92 |
93 | return ret;
94 |
95 | }
96 |
97 | };
98 |
99 | ```
--------------------------------------------------------------------------------
/49. Group Anagrams.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 | >Given an array of strings, group anagrams together.
4 |
5 | >For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
6 | >Return:
7 |
8 | >>[
9 | >> ["ate", "eat","tea"],
10 | >> ["nat","tan"],
11 | >> ["bat"]
12 | >>]
13 |
14 |
15 | >Note:
16 |
17 | >>1.For the return value, each inner list's elements must follow the lexicographic order.
18 |
19 | >>2.All inputs will be in lower-case.
20 |
21 | ##(二)解题
22 | 本题的解法是通过sort对单个string中的字符进行排序,排序后如果相同的就放在一个vector
23 | 注意:题目中的Note部分有提到返回的结果需要进行字典排序,一开始一直想不到办法,后来在讨论区看到有人直接用sort对里面的数进行排序就得出了字典排序,一下子恍然大悟!
24 | ```cpp
25 | class Solution {
26 |
27 | public:
28 |
29 | vector> groupAnagrams(vector& strs) {
30 |
31 | vector> ret;
32 |
33 | map nonrepstr;//用来存放排序后不重复的string
34 |
35 | int count = 0;//用来标识该string在ret中的位置
36 |
37 | for(int i = 0 ; i < strs.size() ; i++)
38 |
39 | {
40 |
41 | string tempstr = strs[i];
42 |
43 | sort(strs[i].begin(),strs[i].end(),less());
44 |
45 | auto iter = nonrepstr.find(strs[i]);
46 |
47 | if(iter!=nonrepstr.end())//找到
48 |
49 | {
50 |
51 | (ret[iter->second]).push_back(tempstr);//如果找到了就放到ret里相应的vector中
52 |
53 | }
54 |
55 | else//没找到
56 |
57 | {
58 |
59 | nonrepstr.insert(pair(strs[i],count++));//不重复的string放入map中
60 |
61 | vector temp;
62 |
63 | temp.push_back(tempstr);
64 |
65 | ret.push_back(temp);//结果中也需要保存一份
66 |
67 | }
68 |
69 | }
70 |
71 | for(int j=0;j一天一道LeetCode系列
2 | ##(一)题目
3 | >A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
4 | 
5 | >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).
6 |
7 | >How many possible unique paths are there?
8 |
9 |
10 |
11 | >Above is a 3 x 7 grid. How many possible unique paths are there?
12 |
13 | >Note: m and n will be at most 100.
14 |
15 | ##(二)解题
16 |
17 | 主要思想:对于i,j这一点来说,它到终点的路径数dp[i][j] = dp[i+1][j]+ dp[i][j+1],这就是状态转移方程,然后利用动态规划来求解!
18 |
19 | ###递归版本
20 |
21 |
22 | ```cpp
23 | class Solution {
24 | public:
25 | int dp[101][101];//用来标记已经计算过的路径
26 | int uniquePaths(int m, int n) {
27 | dp[m-1][n-1] = 1;
28 | int ret = dfsPath(0,0,m-1,n-1);
29 | return ret;
30 | }
31 | int dfsPath(int pm,int pn,int m ,int n)
32 | {
33 |
34 | if(pm==m && pn==n) return 1 ;
35 | int down = 0;
36 | int right = 0;
37 | if(pm+1<=m) down = dp[pm+1][pn]==0?dfsPath(pm+1,pn,m,n):dp[pm+1][pn];//往下走的那一格到终点的路径数
38 | if(pn+1<=n) right = dp[pm][pn+1]==0?dfsPath(pm,pn+1,m,n):dp[pm][pn+1];//往右走的那一格到终点的路径数
39 | dp[pm][pn] = down+right;
40 | return dp[pm][pn];
41 | }
42 | };
43 | ```
44 | ###非递归版本
45 | ```cpp
46 | /*
47 | 提示:这个版本画个图可能会更好理解
48 | */
49 | class Solution {
50 | public:
51 | int uniquePaths(int m, int n) {
52 | int dp[101][101];
53 | for(int i = 0 ; i < m ; i++) dp[i][n-1] = 1;//首先初始化dp
54 | for(int i = 0 ; i < n ; i++) dp[m-1][i] = 1;
55 | if(m==1||n==1) return 1;//特殊情况
56 | for(int i = m-2 ; i>=0 ; i--)
57 | for(int j = n-2 ; j>=0 ; j--)
58 | {
59 | dp[i][j] = dp[i+1][j] + dp[i][j+1];//状态转移方程
60 | }
61 | return dp[0][0];
62 | }
63 | };
64 | ```
--------------------------------------------------------------------------------
/10. Regular Expression Matching.md:
--------------------------------------------------------------------------------
1 | # 一天一道LeetCode系列
2 |
3 | # (一)题目
4 |
5 | > Implement regular expression matching with support for '.' and '*'.
6 | >> '.' Matches any single character.
7 | >> '*' Matches zero or more of the preceding element.
8 | >>
9 | >> The matching should cover the entire input string (not partial).
10 | >>
11 | >> The function prototype should be: bool isMatch(const char *s, const
12 | >> char *p)
13 | >>
14 | >> Some examples:
15 | >> isMatch("aa","a") → false
16 | >> isMatch("aa","aa") → true
17 | >> isMatch("aaa","aa") → false
18 | >> isMatch("aa", "a*") → true
19 | >> isMatch("aa",".*") → true
20 | >> isMatch("ab", ".*") → true
21 | >> isMatch("aab", "c*a*b") → true
22 | # (二)解题
23 | 本题的意思是实现正则表达式的判断函数。
24 | > tips:评级为hard的题还真是难做!
25 |
26 | 考虑到aaaaaab和a*b,这种无法判断*的结束位置,需要用到动态规划来求解。
27 | 分为以下两种情况:
28 | case 1:p[j+1] !='*'时,无论是是s[i] == p[j]还是p[j]=='.',状态转移方程均为dfs[i][j] = dfs[i+1][j+1];
29 | case 2:p[j+1] == '*'时,这个时候就需要判断*匹配的结束位置。
30 | ```cpp
31 | while(*s == *p || *s != '\0' && *p == '.')
32 | {
33 | if(Match(s,p+2)) return true;
34 | s++;
35 | }
36 | ```
37 | 结束位置找到以后状态转移方程为:dfs[i][j] = dfs[i][j+2];
38 | 接下来看代码:
39 | ```cpp
40 | class Solution {
41 | public:
42 | bool isMatch(string s, string p) {
43 | Match((const char *)&s[0],(const char *)&p[0]);
44 | }
45 | bool Match(const char *s,const char *p)
46 | {
47 | if(*p == '\0') return *s == '\0';
48 | if(*(p+1) == '*')
49 | {
50 | while(*s == *p || *s != '\0' && *p == '.')
51 | {
52 | if(Match(s,p+2)) return true;
53 | s++;
54 | }
55 | return Match(s,p+2);
56 | }
57 | else
58 | {
59 | if(*s == *p ||*s != '\0' && *p == '.')
60 | {
61 | return Match(s+1,p+1);
62 | }
63 | return false;
64 | }
65 | }
66 | };
67 | ```
--------------------------------------------------------------------------------
/29. Divide Two Integers.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 | >Divide two integers without using multiplication, division and mod operator.
4 |
5 | >If it is overflow, return MAX_INT.
6 |
7 | ##(二)解题
8 |
9 | 这题看起来很简单,一开始想到的方法就是从0开始一次累加除数,一直到比被除数大为止,好无悬念,这样做的结果就是超时了。
10 |
11 | 用移位来实现除法效率就比较高了。具体思路可以参考二进制除法。下面举个例子来说明。
12 |
13 | 例如:10/2 即10010/10
14 |
15 | 第一步:1-10不够减,结果添0,左移位变成10
16 |
17 | 第二步:10-10够减,结果添1,余010,左移位0
18 |
19 | 第三步:0-10不够减,结果添0,左移一位变成01
20 |
21 | 第四步:1-10不够减,结果添0,左移一位变成10
22 |
23 | 第五步:10-10够减,结果添1,后面没有位了,运算完毕
24 |
25 | 10010 = 10 *01001 即 10 = 2 * 5。
26 |
27 | 那么按照这种思路,我们每次对除数进行移位,找到等于或小于被除数(dividend)的最大值(max),判断移位次数k,结果```ret += 1<= absdivisor)//循环条件被除数大于除数
54 |
55 | {
56 |
57 | long long count = 1;
58 |
59 | long long tmpdiv = absdivisor;//初始值为除数
60 |
61 | while(tmpdiv<=absdividend){//移位后判断
62 |
63 | count<<=1;
64 |
65 | tmpdiv<<=1;
66 |
67 | }//找到了小于或等于被除数的最大值
68 |
69 | absdividend-=(tmpdiv>>1);//注意此处最大值应为tmpdiv>>1
70 |
71 | ret +=(count>>1);//上面多左移了一次,这里右移回来
72 |
73 | }
74 |
75 | if((dividend>0&&divisor<0)||(dividend<0&&divisor>0)){//判断正负
76 |
77 | ret = 0-ret;
78 |
79 | }
80 |
81 | if(ret>2147483647 ||ret<-2147483648) return 2147483647;//判断越界
82 |
83 | return (int)ret;//强制转换成int后退出
84 |
85 | }
86 |
87 | };
88 |
89 | ```
--------------------------------------------------------------------------------
/23. Merge k Sorted Lists.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | #一天一道LeetCode系列
4 | ----------
5 |
6 |
7 | ##(一)题目
8 |
9 | >Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
10 |
11 | ##(二)解题
12 |
13 | 合并K个已拍好序的链表。剑指上有合并两个已排好序的链表的算法,那么K个数,我们可以采用归并排序的思想,不过合并函数可能需要修改一下,换成合并两个已排好序的链表的方法。代码如下:
14 |
15 | ```cpp
16 |
17 | /**
18 |
19 | * Definition for singly-linked list.
20 |
21 | * struct ListNode {
22 |
23 | * int val;
24 |
25 | * ListNode *next;
26 |
27 | * ListNode(int x) : val(x), next(NULL) {}
28 |
29 | * };
30 |
31 | */
32 |
33 | class Solution {
34 |
35 | public:
36 |
37 | ListNode* mergeKLists(vector& lists) {
38 |
39 | int len = lists.size();
40 |
41 | if(len == 0) return NULL;
42 |
43 | if(len == 1) return lists[0];
44 |
45 | ListNode* ret = merge(lists,0,lists.size()-1);
46 |
47 | return ret;
48 |
49 | }
50 |
51 | ListNode* merge(vector& lists , int i,int j){
52 |
53 | if(i==j) return lists[i];
54 |
55 | ListNode* ret = NULL;
56 |
57 | if(ival < list2->val){
86 |
87 | ret = list1;
88 |
89 | ret->next = mergeTwoLists(list1->next , list2);
90 |
91 | }
92 |
93 | else{
94 |
95 | ret = list2;
96 |
97 | ret->next = mergeTwoLists(list1 , list2->next);
98 |
99 | }
100 |
101 | return ret;
102 |
103 | }
104 |
105 | };
106 |
107 | ```
--------------------------------------------------------------------------------
/53. Maximum Subarray.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 | >Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
4 |
5 | >For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
6 | >the contiguous subarray [4,−1,2,1] has the largest sum = 6.
7 |
8 | ##(二)解题
9 | 本题想到了两个思路:暴力求解法和分治法。前者就不多说了,本文主要讨论分治法。
10 | 分治法的大致思路:对于A[low,high]这个数组,任何的连续子数组A[i,j]的位置必然是一下三种情况之一:
11 |
12 | 完全位于子数组A[low,mid]中,因此有low<=i<=j<=mid
13 | 完全位于子数组A[mid+1,high]中,因此mid& nums) {
25 |
26 | int len = nums.size();
27 |
28 | return findMaxSubArray(nums,0,len-1);
29 |
30 | }
31 |
32 | int findMaxSubArray(vector& nums , int low , int high)
33 |
34 | {
35 |
36 | if(low==high) return nums[low];
37 |
38 | int mid = (low+high)/2;
39 |
40 | int left = findMaxSubArray(nums,low,mid);//子数组在左边的最大值
41 |
42 | int right = findMaxSubArray(nums,mid+1,high);//子数组在右边的最大值
43 |
44 | int cross = findMaxCrossSubArray(nums,low,high,mid);//子数组跨越中间点的时候的最大值
45 |
46 | if(left>=cross&&left>=right) return left;
47 |
48 | else if(right>=cross&&right>=left) return right;
49 |
50 | else return cross;//返回三个数的最大值
51 |
52 | }
53 |
54 | int findMaxCrossSubArray(vector& nums , int low , int high , int mid)
55 |
56 | {
57 |
58 | int sum = 0;
59 |
60 | int left_sum = -2147483648;//int的最小数
61 |
62 | int right_sum = -2147483648;
63 |
64 | for(int i = mid ; i >= low ;i--)
65 |
66 | {
67 |
68 | sum+=nums[i];
69 |
70 | left_sum = left_sum一天一道LeetCode系列
2 | ##(一)题目
3 | >The set [1,2,3,…,n] contains a total of n! unique permutations.
4 | >By listing and labeling all of the permutations in order,
5 | >We get the following sequence (ie, for n = 3):
6 | 1:"123"
7 | 2:"132"
8 | 3 : "213"
9 | 4 :"231"
10 | 5 : "312"
11 | 6 : "321"
12 | >Given n and k, return the kth permutation sequence.
13 | ##(二)解题
14 | ###第一种解法:
15 | 参考:[【一天一道LeetCode】#31. Next Permutation ](https://leetcode.com/problems/next-permutation/)这篇博客,很奇怪的是为什么n=8,k=8590的时候会超时,暂时还没有想出来原因,欢迎大家留言讨论。
16 | ```cpp
17 | /*
18 | 利用STL的next_permutation每次求出下一个排列数
19 | */
20 | class Solution {
21 | public:
22 | string getPermutation(int n, int k) {
23 | string seq;
24 | string ret;
25 | for(int i = 0 ; i < n ; i++)
26 | {
27 | seq+=('1' + i);
28 | }
29 | do
30 | {
31 | k--;
32 | if(k==0) {
33 | ret = seq;
34 | break;
35 | }
36 | }while(next_permutation(seq.begin(),seq.end()));
37 | return ret;
38 | }
39 | };
40 | ```
41 | ###第二种解法:
42 | 利用排列数的规律来求解。
43 | 我们以题目给出的例子为例来讲解规律。 n=3时,由1,2,3三个数组成{a1,a2,a3}
44 | 1:"123"
45 | 2:"132"
46 | 3 : "213"
47 | 4 :"231"
48 | 5 : "312"
49 | 6 : "321"
50 | 首先看第一个数a1(候选数字temp = "123"),k为1,2时,a1=1,k为3,4时,a1=2,k为5,6时,a1=3,从中可以看出a1=temp[(k-1)/(n-1)!]。
51 | 确定了第一个数后我们来看第二个数a2,以1,2这一组来看,排除了1,候选数字temp = "23",这个时候k只能为1和2,所以在上一步中k%=(n-1)!,这个时候a2=temp[(k-1)/(n-2)!]
52 | 最后a3只能为剩下的一个数字了。
53 |
54 | ok,整理一下思路,我们需要一个候选字符串temp,一个(n-1)!的数组f[10] = {1,1,2,6,24,120,720,5040,5040*8}(n为1~9的数字),k初始值为k-1
55 | 在每一步中,a1=temp[k/f[n-1]],k%=f[n-1]。一直到n为0。
56 | 具体思路见代码:
57 | ```cpp
58 | class Solution {
59 | public:
60 | string getPermutation(int n, int k) {
61 | string temp = "123456789";
62 | int f[] = {1,1,2,6,24,120,720,5040,5040*8};
63 | string ret;
64 | int i = n;
65 | k--;//k的初始值
66 | while(i)
67 | {
68 | int m = k/f[i-1];
69 | k %=f[i-1];
70 | ret+=temp[m];
71 | temp.erase(temp.begin()+m);//擦除掉已经选掉的值
72 | i--;
73 | }
74 | return ret;
75 | }
76 | };
77 | ```
--------------------------------------------------------------------------------
/12. Integer to Roman.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 |
4 | > Given an integer, convert it to a roman numeral.
5 | >
6 | > Input is guaranteed to be within the range from 1 to 3999.
7 | ##(二)解题
8 | 将整形数字转换成罗马数字
9 | 罗马数字共有七个,即I(1),V(5),X(10),L(50),C(100),D(500),M(1000)
10 | 举例:Ⅰ、Ⅱ、Ⅲ、Ⅳ、Ⅴ、Ⅵ、Ⅶ、Ⅷ、Ⅸ、Ⅹ、Ⅺ、Ⅻ表示1-11
11 | 代码:
12 |
13 | ```
14 | class Solution {
15 | public:
16 | string intToRoman(int num) {
17 | string str = "";
18 | string roman[8] = {"I","V","X","L","C","D","M"};
19 | int j=0;
20 | while(num)
21 | {
22 | int temp = num%10;
23 | string str_t ="";
24 | if(temp <4)
25 | {
26 | int count = temp;
27 | while(count--) str_t+=roman[j];
28 | }
29 | else if(temp==4)
30 | {
31 | str_t=roman[j];
32 | str_t+=roman[j+1];
33 | }
34 | else if(temp>=5&&temp<=8)
35 | {
36 | str_t+=roman[j+1];
37 | int count = temp-5;
38 | while(count--) str_t+=roman[j];
39 | }
40 | else if(temp==9)
41 | {
42 | str_t+=roman[j];
43 | str_t+=roman[j+2];
44 | }
45 | cout<= values[i]) {
65 | number -= values[i];
66 | result.append(numerals[i]);
67 | }
68 | }
69 | return result.toString();
70 | }
71 | }
72 | ```
73 |
74 | 看起来就简单多了。
--------------------------------------------------------------------------------
/3. Longest Substring Without Repeating Characters.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode
2 | ###(一)题目
3 | > Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
4 |
5 | 题目意思:求一字符串中最长的无重复的字符串
6 |
7 | ###(二) 解题过程
8 | 一开始拿到这题,直接暴力解决,用双重循环找无重复的子字符串
9 | 结果可想而知,超时!Time Limit Exceeded!
10 |
11 | ```
12 | class Solution {
13 | public:
14 | int lengthOfLongestSubstring(string s) {
15 | int max = 0 ;
16 | for(int i = 0 ; i < s.length();++i)
17 | {
18 | int j = i+1;
19 | int count = 1;
20 | while(j=i) z--;//判断是s[j]不等于s[i~j]任一个字符
24 | if(z+1 == i) count++;//如果不等,则count++
25 | j++;
26 | }
27 | if(maxidx) //①如果这个字符出现过,则令idx等于上一次出现该字符的位置序号
47 | {
48 | idx = last[s[i]];
49 | }
50 |
51 | if(i -idx > max){ ②//记录最大的无重复字串
52 | max = i-idx;
53 | }
54 |
55 | last[s[i]] = i;③
56 | }
57 | return max;
58 | }
59 | };
60 | ```
61 | 以abca为例:
62 | i=0:查表last['a'] = -1,①不执行 idx=-1, ②执行max =1,更新last表 last['a'] = 0;
63 | i=1:查表last['b'] = -1,①不执行 idx=-1, ②执行max =2,更新last表 last['b'] = 1;
64 | i=2:查表last['c'] = -1,①不执行 idx=-1, ②执行max =3,更新last表 last['c'] = 2;
65 | i=3:查表last['a'] = 0,①执行,idx=0 , ②执行max =3,更新last表 last['a'] = 3;
66 | .....
67 | 上述算法的时间复杂度为O(n),Accepted!
--------------------------------------------------------------------------------
/45. Jump Game II.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 | >Given an array of non-negative integers, you are initially positioned at the first index of the array.
4 |
5 | >Each element in the array represents your maximum jump length at that position.
6 |
7 | >Your goal is to reach the last index in the minimum number of jumps.
8 |
9 | >For example:
10 | >Given array A = [2,3,1,1,4]
11 |
12 | >The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
13 |
14 | >Note:
15 | >You can assume that you can always reach the last index.
16 |
17 | ##(二)解题
18 | 1、首先想到的做法就是对于序号i,判断i+nums[i]能不能到达终点,如果能直接return,如果不能对小于nums[i]的数依次进行递归,得到最小的min值。这种做法直接超时了,TLE!
19 | ```cpp
20 | class Solution {
21 | public:
22 | int min;
23 | int jump(vector& nums) {
24 | min = nums.size();
25 | jumpdfs(nums,0,0);
26 | return min;
27 | }
28 | void jumpdfs(vector& nums , int idx , int count)
29 | {
30 | int len = nums.size();
31 | if(idx >= len -1) {
32 | min = count;
33 | return;
34 | }
35 | if(idx= len-1){
36 | min = min>(count+1)?(count+1):min;
37 | return;
38 | }
39 | else
40 | {
41 | for(int i = 1 ; idx& nums) {
58 | int ret = 0 ;
59 | int last = 0;
60 | int cur = 0;
61 | for(int i = 0 ; i < nums.size() ; i++)
62 | {
63 | if(last>=nums.size()-1) break;
64 | if(i>last)//如果当前位置已经跳出了上一跳的最远位置
65 | {
66 | last = cur;//更新上一跳的最远位置等于当前跳的最远位置
67 | ++ret;//跳的次数加1
68 | }
69 | cur = max(cur , i+nums[i]);//更新当前跳的最远位置
70 | }
71 | return ret;
72 | }
73 | };
74 | ```
--------------------------------------------------------------------------------
/51. N-Queens.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 | >The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
4 | >
5 | >Given an integer n, return all distinct solutions to the n-queens puzzle.
6 | >Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space >respectively.
7 | >For example,
8 | >There exist two distinct solutions to the 4-queens puzzle:
9 | >[
10 | [".Q..", // Solution 1
11 | "...Q",
12 | "Q...",
13 | "..Q."],
14 | > ["..Q.", // Solution 2
15 | "Q...",
16 | "...Q",
17 | ".Q.."]
18 | ]
19 | ##(二)解题
20 | 不玩国际象棋还真不知道这题的规则。百度了好久才明白。
21 | 主要有以下三个:
22 | + 同一行上只能有一个皇后
23 | + 同一列上只能有一个皇后
24 | + 两个皇后之间不能处在同一条对角线上
25 | 具体解法看代码:
26 | ```cpp
27 | /*
28 | 首先利用一个数row和数组a[i]确保每一行每一列只有一个皇后
29 | 然后利用一个vector存储已摆放皇后的位置坐标,每摆一个皇后就与已摆放的皇后进行比较,如果在一条对角线上就不能摆
30 | */
31 | class Solution {
32 | public:
33 | vector> ret;
34 | vector> queens;//存放已摆放的皇后的坐标值
35 | vector> solveNQueens(int n) {
36 | int *a = new int[n];//确保每一列只有一个皇后
37 | memset(a,0,n*sizeof(int));
38 | vector res;
39 | backtrc(res, a, 0, n);
40 | return ret;
41 | }
42 | bool isValid(vector> queens , int row,int col)//
43 | {
44 | if (queens.empty()) return true;
45 | for (int i = 0; i < queens.size();i++)
46 | {
47 | if (abs(row- queens[i].first) == abs(col-queens[i].second))
48 | {
49 | return false;
50 | }
51 | }
52 | return true;
53 | }
54 | void backtrc(vector res, int a[], int row, int n)//row确保每一行只有一个皇后
55 | {
56 | if (row == n)//如果摆放完n行,则退出
57 | {
58 | ret.push_back(res);
59 | return;
60 | }
61 | for (int i = 0; i < n; i++)
62 | {
63 | if (a[i] == 0&&isValid(queens, row, i))//保证了同一行,同一列,同一对角线只有一个Q
64 | {
65 | a[i] = 1;
66 | string tmp(n, '.');
67 | tmp[i] = 'Q';
68 | res.push_back(tmp);
69 | queens.push_back(pair(row, i));
70 | backtrc(res, a, row + 1, n);
71 | //回溯
72 | a[i] = 0;
73 | queens.pop_back();
74 | res.pop_back();
75 | }
76 | }
77 | }
78 | };
79 | ```
80 |
81 |
--------------------------------------------------------------------------------
/65. Valid Number.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode
2 |
3 | >本系列文章已全部上传至我的github,地址:[ZeeCoder‘s Github](https://github.com/Zeecoders/LeetCode)
4 |
5 | >欢迎大家关注我的新浪微博,[我的新浪微博](http://weibo.com/zc463717263?is_all=1)
6 | >
7 | >欢迎转载,转载请注明出处
8 |
9 | ##(一)题目
10 |
11 | >Validate if a given string is numeric.
12 |
13 | >Some examples:
14 | >"0" => true
15 | >" 0.1 " => true
16 | >"abc" => false
17 | >"1 a" => false
18 | >"2e10" => true
19 |
20 | >Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front >before implementing one.
21 | >Update (2015-02-10):
22 | >The signature of the C++ function had been updated. If you still see your function signature accepts a const >char * argument, please click the reload button to reset your code definition.
23 | ##(二)解题
24 | 题目大意:判断一个string数是否为有效数
25 | 大致从以下三点考虑这个问题:
26 | 1、全为数字
27 | 2、存在有且仅有一个’e‘,这个时候需要判断前后的数字有效,如4e+,.e1
28 | 3、存在有些仅有一个'.',注意指数不能为小数
29 | 做题时没有考虑到的特殊情况:
30 | “e”,“4e+”,“.e1”
31 | ```cpp
32 | class Solution {
33 | public:
34 | bool isNumber(string s) {
35 | int len = s.length();
36 | if(len == 0) return false;
37 | //剔除前面的空格
38 | int st = 0 ;
39 | while(st=0&&s[ed] == ' ') ed--;
43 | if(st>ed) return false;//如果全是空格就返回false
44 | //符号
45 | if(s[st]=='+'||s[st]=='-') st++;
46 | //标志.和e的位置
47 | int hase = -1;
48 | int hasdot =-1;
49 | //开始循环
50 | for(int i =st ; i <= ed ;)
51 | {
52 | if(s[i]>='0'&&s[i]<='9') i++;
53 | else if(s[i]=='e')
54 | {
55 | if(hase==-1) hase = i;//只能出现一个e
56 | else return false;
57 | if(i==st||i==ed) return false;//e在最前面或最后面返回false
58 | i++;
59 | if(s[i]=='+'||s[i]=='-') i++;//考虑指数带有符号
60 | if(i>ed) return false;//指数非法,如10e+
61 | }
62 | else if(s[i]=='.')
63 | {
64 | if(hasdot==-1) hasdot = i;//只能有一个.
65 | else return false;
66 | i++;
67 | if(ed-st==0) return false;//string为“.”的特殊情况
68 | }
69 | else return false;
70 | }
71 | if(hase!=-1&&hasdot!=-1){//判断e前面的数字有效
72 | if(hase一天一道LeetCode
2 | ##(一)题目
3 |
4 | > Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
5 | >
6 | > Note: Elements in a quadruplet (a,b,c,d) must be in non-descending
7 | > order. (ie, a ≤ b ≤ c ≤ d) The solution set must not contain duplicate
8 | > quadruplets.
9 | >
10 | > For example, given array S = {1 0 -1 0 -2 2}, and target = 0.
11 | > A solution set is:
12 | > (-1, 0, 0, 1)
13 | > (-2, -1, 1, 2)
14 | > (-2, 0, 0, 2)
15 | ##(二)解题
16 | 勉强不超时的代码。(注:和3sum比较类似)
17 | ```
18 | class Solution {
19 | public:
20 | vector> fourSum(vector& nums, int target) {
21 | vector> result;
22 | if(nums.size()<4) return result;
23 | sort(nums.begin(),nums.end());
24 | for(int i = 0 ; i < nums.size()-3 ; )
25 | {
26 | for(int j=i+1 ; j < nums.size()-2 ; )
27 | {
28 | int start = j+1;
29 | int end = nums.size()-1;
30 | while(start vec;
36 | vec.push_back(nums[i]);
37 | vec.push_back(nums[j]);
38 | vec.push_back(nums[start]);
39 | vec.push_back(nums[end]);
40 | result.push_back(vec);
41 | start++;
42 | while(starttarget)
47 | {
48 | end--;
49 | while(start一天一道LeetCode系列
2 | ##(一)题目
3 | >Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
4 |
5 | >Each number in C may only be used once in the combination.
6 |
7 | >Note:
8 |
9 | >>All numbers (including target) will be positive integers
10 |
11 | >>Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
12 |
13 | >>The solution set must not contain duplicate combinations.
14 |
15 |
16 |
17 | >For example, given candidate set 10,1,2,7,6,1,5 and target 8,
18 | >A solution set is:
19 | >[1, 7]
20 | >[1, 2, 5]
21 | >[2, 6]
22 | >[1, 1, 6]
23 |
24 | ##(二)解题
25 | 具体思路与[【一天一道LeetCode】39. Combination Sum](http://blog.csdn.net/terence1212/article/details/51308668)这篇博文一样,采用动态规划和回溯法进行求解。
26 | ```cpp
27 | /*
28 | 和上一题的思路一样,区别是数字不能重复查找,但Vector中允许有重复的数字
29 | 具体改动请看代码注释
30 | */
31 | class Solution {
32 | public:
33 | vector> ret;
34 | vector> combinationSum2(vector& candidates, int target) {
35 | sort(candidates.begin(),candidates.end());
36 | for(int idx = 0;idx=0 && candidates[idx] == candidates[idx-1]) continue;//避免重复查找
39 | else
40 | {
41 | if(candidates[idx]<=target)
42 | {//如果小于则调用动态规划函数
43 | vector tmp;
44 | tmp.push_back(candidates[idx]);
45 | combinationDfs(candidates,tmp,idx,target-candidates[idx]);
46 | }
47 | }
48 | }
49 | return ret;
50 | }
51 | void combinationDfs(vector& candidates ,vector& tmp, int start ,int target)
52 | {
53 | if(target == 0){
54 | ret.push_back(tmp);
55 | return;
56 | }
57 | for(int i = start+1 ; i < candidates.size() ; i++)//从start+1开始查找,避免了数字重复查找
58 | {
59 | if(candidates[i] < target){
60 | tmp.push_back(candidates[i]);
61 | combinationDfs(candidates,tmp,i,target-candidates[i]);
62 | tmp.pop_back(); //回溯
63 | }
64 | else if(candidates[i] == target){
65 | tmp.push_back(candidates[i]);
66 | ret.push_back(tmp);
67 | tmp.pop_back();//回溯
68 | }
69 | else
70 | {
71 | return;
72 | }
73 | while(i+1< candidates.size()&&candidates[i]==candidates[i+1]) i++;//去除重复的查找
74 | }
75 | }
76 | };
77 | ```
--------------------------------------------------------------------------------
/57. Insert Interval.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 | >Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
4 |
5 | >You may assume that the intervals were initially sorted according to their start times.
6 |
7 | > **Example 1**:
8 | >Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
9 |
10 | > **Example 2**:
11 | >Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].
12 |
13 | >This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
14 |
15 | ##(二)解题
16 |
17 | 相关题目:[【一天一道LeetCode】#56. Merge Intervals](http://blog.csdn.net/terence1212/article/details/51476535)
18 |
19 | ```cpp
20 |
21 | /*
22 |
23 | 主要解题思路:
24 |
25 | 1、当intervals[i].endnewInterval.start的时候,确定合并后的interval的start值
28 |
29 | 3、当找到最后一个满足intervals[i].start>newInterval.end的时候,确定合并后的interval的end值
30 |
31 | */
32 |
33 | /**
34 |
35 | * Definition for an interval.
36 |
37 | * struct Interval {
38 |
39 | * int start;
40 |
41 | * int end;
42 |
43 | * Interval() : start(0), end(0) {}
44 |
45 | * Interval(int s, int e) : start(s), end(e) {}
46 |
47 | * };
48 |
49 | */
50 |
51 | class Solution {
52 |
53 | public:
54 |
55 | vector insert(vector& intervals, Interval newInterval) {
56 |
57 | vector ret;
58 |
59 | if(intervals.size()==0){//特殊情况
60 |
61 | ret.push_back(newInterval);
62 |
63 | return ret;
64 |
65 | }
66 |
67 | int i = 0;
68 |
69 | Interval tmp;
70 |
71 | while(inewInterval.start的i值
80 |
81 | //这里需要注意当newInterval比vector里面的值都大的情况
82 |
83 | tmp.start = min(i==intervals.size()?newInterval.start:intervals[i].start,newInterval.start);
84 |
85 | tmp.end = newInterval.end;
86 |
87 | while(i一天一道LeetCode
2 | ##(一)题目
3 |
4 | > There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
5 |
6 | 给定两个排好序的数组,求两个数组的中间值。
7 | 例如:[1 2]和[1 2] 返回值:1.5
8 |
9 | ##(二)解题思路
10 | 时间复杂度要满足O(log(m+n)), 可以采用一个辅助容器来存储小值,等存到两个数组的一半的时候就停止,再根据奇偶来求中间值。
11 |
12 | ```
13 | class Solution {
14 | public:
15 | double findMedianSortedArrays(vector& nums1, vector& nums2) {
16 | vector temp;
17 | int len1=nums1.size();
18 | int len2= nums2.size();
19 | int idx = (len1+len2)/2+1;//需要存放idx个数
20 | int i =0,j=0;
21 | int size = 0;
22 | if(len1 ==0 && len2==0) return 0.0;
23 | while(size != idx) //当idx==size的时候退出
24 | {
25 | if(i == len1 && j
61 | class Solution {
62 | public:
63 | double findMedianSortedArrays(int A[], int m, int B[], int n) {
64 |
65 | int mid = (m+n+1)/2-1, median1 = 0, median2 = 0;
66 | multiset mergeArray;
67 | for(int i = 0; i < m; i++)
68 | mergeArray.insert(A[i]);
69 | for(int i = 0; i < n; i++)
70 | mergeArray.insert(B[i]);
71 |
72 | int i = 0;
73 | set::iterator iter = mergeArray.begin();
74 | for(; i++ < mid &&iter != mergeArray.end(); ++iter);
75 |
76 | median1 = *iter;
77 | iter++;
78 | median2 = *iter;
79 |
80 | if((m+n)%2)
81 | return median1;
82 | else
83 | return (median1+median2)/2.0;
84 | }
85 | };
86 | ```
87 |
88 |
--------------------------------------------------------------------------------
/25. Reverse Nodes in k-Group.md:
--------------------------------------------------------------------------------
1 |
2 | #一天一道LeetCode系列
3 | ##(一)题目
4 | >Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
5 | If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
6 |
7 | >You may not alter the values in the nodes, only nodes itself may be changed.
8 |
9 | >Only constant memory is allowed.
10 |
11 | >For example,
12 | Given this linked list: 1->2->3->4->5
13 |
14 | >For k = 2, you should return: 2->1->4->3->5
15 |
16 | >For k = 3, you should return: 3->2->1->4->5
17 |
18 | ##(二)解题
19 |
20 | ```cpp
21 | /**
22 | * Definition for singly-linked list.
23 | * struct ListNode {
24 | * int val;
25 | * ListNode *next;
26 | * ListNode(int x) : val(x), next(NULL) {}
27 | * };
28 | */
29 | class Solution {
30 | public:
31 | ListNode* reverseKGroup(ListNode* head, int k) {
32 | //主要思想:以K为间距,分别对间距内的链表进行反转
33 | //需要注意的问题:为了防止链表断裂需要记录每一段的首尾元素
34 | ListNode* pret = head;
35 | ListNode* phead = head;//当前待反转的head节点
36 | ListNode* ptail = NULL;//当前待反转的尾节点
37 | ListNode* pnexthead = NULL;.//记录下一段的head
38 | ListNode* plasttail = NULL;//记录前一段的尾节点
39 | if(head == NULL) return NULL;
40 | while(phead!=NULL)
41 | {
42 | int gap=k;
43 | ListNode* p = phead;
44 | while(gap != 1&& p!=NULL) {p = p->next;gap--;}//找到尾节点
45 | if(p!=NULL){
46 | ptail = p;
47 | ListNode* tmp;
48 | pnexthead = p->next;
49 | if(phead == head) pret = reverseK(phead,ptail,pnexthead);//0-k段的时候要记录整个链表的头节点
50 | else
51 | {
52 | tmp = reverseK(phead,ptail,pnexthead);
53 | plasttail->next = tmp;
54 | }
55 | phead = pnexthead;//跳转到下一段
56 | plasttail = ptail;//记录当前段的尾节点
57 | }
58 | else
59 | {
60 | if(plasttail!= NULL) plasttail->next = phead;//将[0-k],[k+1-2k]......链接起来,防止链表断裂
61 | phead = NULL;//如果链接最后凑不够K个元素,则将phead置为NULL
62 | }
63 | }
64 | return pret;
65 | }
66 | ListNode* reverseK(ListNode* phead ,ListNode* &ptail/*注意此处用引用来获得尾节点*/,ListNode* pnexthead)
67 | {
68 | ListNode* prevHead = phead;
69 | ListNode* p = phead->next;
70 | ListNode* pre = phead;
71 | while(1)
72 | {
73 | if(p==pnexthead) {
74 | ptail = pre;//返回尾节点
75 | return prevHead;
76 | }
77 | pre->next = p->next;
78 | p->next = prevHead;
79 | prevHead = p;
80 | p=pre->next;
81 | }
82 | }
83 | };
84 | ```
85 |
--------------------------------------------------------------------------------
/28. Implement strStr().md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 | >Implement strStr().
4 |
5 | >Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
6 |
7 | ##(二)解题
8 |
9 | 第一种解法:朴素匹配算法
10 |
11 | ```cpp
12 |
13 | /*
14 |
15 | 两个指针,分别指向两个字符串的首字符
16 |
17 | 如果相等则一起向后移动,如果不同i取第一个相同字符的下一个开始继续匹配
18 |
19 | 如果最后j等于needle的长度则匹配成功,返回i-j
20 |
21 | 否则返回0
22 |
23 | */
24 |
25 | class Solution {
26 |
27 | public:
28 |
29 | int strStr(string haystack, string needle) {
30 |
31 | int j,i;
32 |
33 | for(i = 0 , j =0 ; ihaystack.length()) return -1;
38 |
39 | if(haystack[i]==needle[j]){//如果匹配上就继续向后匹配
40 |
41 | i++;
42 |
43 | j++;
44 |
45 | }
46 |
47 | else{
48 |
49 | i-=j-1;//回溯到匹配开始时needle的首字符对应的下一位
50 |
51 | j=0;//j回溯到needle的首字符
52 |
53 | }
54 |
55 | }
56 |
57 | if(j==needle.length()) return i-j;
58 |
59 | else return -1;
60 |
61 | }
62 |
63 | };
64 |
65 | ```
66 |
67 | 第二种解法:KMP模式匹配算法
68 | 关于kmp,请自行百度或者大话数据结构P143页
69 |
70 | ```cpp
71 |
72 | class Solution {
73 |
74 | public:
75 |
76 | int strStr(string haystack, string needle) {
77 |
78 | int hlen = haystack.length();
79 |
80 | int nlen = needle.length();
81 |
82 | if(hlen==0) return nlen==0?0:-1;//临界值判断
83 |
84 | if(nlen==0) return 0;//needle为NULL,就直接返回0
85 |
86 | int* next = new int[nlen+1];
87 |
88 | getNext(needle,next);
89 |
90 | int i = 0;
91 |
92 | int j = 0;
93 |
94 | while(i一天一道LeetCode系列
2 | ##(一)题目:
3 |
4 | > Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
5 | > > For example, given array S = {-1 2 1 -4}, and target = 1. The sum that
6 | > > is closest to the target is 2. (-1 + 2 + 1 = 2).
7 | ##(二)解题
8 | 直接用三重循环,然后考虑到重复的数字,则需要先排序,以便于后续去重。
9 | 其次,当等于target时,则直接返回
10 | ```
11 | class Solution {
12 | public:
13 | int threeSumClosest(vector& nums, int target) {
14 | int min = 2147438647;
15 | int key =0;
16 | std::sort(nums.begin() , nums.end());
17 | for(int i = 0 ; i < nums.size()-2 ; )
18 | {
19 | for(int j = i+1 ; j < nums.size()-1 ;)
20 | {
21 | for(int k = j+1 ; k < nums.size() ; )
22 | {
23 | int gap = nums[i]+nums[j]+nums[k];
24 | int temp = gap-target>0?gap-target:target-gap;
25 | if(temp& nums, int target) {
51 | std::sort(nums.begin() , nums.end());
52 | bool isfirst = true;
53 | int ret;
54 | for(int i = 0 ; i < nums.size() ; i++)
55 | {
56 | int j = i+1;
57 | int k = nums.size()-1;
58 | while(jtarget)
75 | k--;
76 | else
77 | j++;
78 | }
79 | }
80 | return ret;
81 | }
82 | };
83 | ```
--------------------------------------------------------------------------------
/21. Merge Two Sorted Lists.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 |
4 | > 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.
5 | ##(二)解题
6 | 这题是剑指offer上的老题了,剑指上面用的是递归,我写了个非递归的版本。
7 | ```cpp
8 | /**
9 | * Definition for singly-linked list.
10 | * struct ListNode {
11 | * int val;
12 | * ListNode *next;
13 | * ListNode(int x) : val(x), next(NULL) {}
14 | * };
15 | */
16 | class Solution {
17 | public:
18 | ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
19 | ListNode* head = NULL;
20 | if(l1==NULL && l2==NULL) return head;
21 | ListNode* p = NULL;
22 | ListNode* p1 = l1;
23 | ListNode* p2 = l2;
24 | while(p1 != NULL || p2!=NULL)
25 | {
26 | if(p1 != NULL && p2 != NULL)
27 | {
28 | if(p1->val < p2->val)
29 | {
30 | if(head == NULL) //记录头节点head
31 | {
32 | head = p1;
33 | p = head;
34 | }
35 | else {p->next = p1;p=p->next;}
36 | p1=p1->next;
37 |
38 | }
39 | else
40 | {
41 | if(head == NULL)
42 | {
43 | head = p2;
44 | p = head;
45 | }
46 | else {p->next = p2;p=p->next;}
47 | p2=p2->next;
48 | }
49 | }
50 | if(p1 == NULL && p2 != NULL)
51 | {
52 | if(head == NULL)
53 | {
54 | head = p2;
55 | p = head;
56 | }
57 | else {p->next = p2;p=p->next;}
58 | p2=p2->next;
59 | }
60 | if(p1 != NULL && p2 == NULL)
61 | {
62 | if(head == NULL)
63 | {
64 | head = p1;
65 | p = head;
66 | }
67 | else {p->next = p1;p=p->next;}
68 | p1=p1->next;
69 | }
70 | }
71 | return head;
72 | }
73 | };
74 | ```
75 | 递归版本:
76 |
77 | ```cpp
78 | class Solution {
79 | public:
80 | ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
81 | if(l1 == NULL) return l2;
82 | if(l2 == NULL) return l1;
83 | ListNode* head;
84 | if(l1->val < l2->val)
85 | {
86 | head = l1;
87 | head->next = mergeTwoLists(l1->next , l2);
88 | }
89 | else
90 | {
91 | head = l2;
92 | head->next = mergeTwoLists(l1 , l2->next);
93 | }
94 | return head;
95 | }
96 | };
97 | ```
98 |
99 |
--------------------------------------------------------------------------------
/33. Search in Rotated Sorted Array.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode
2 |
3 | >本系列文章已全部上传至我的github,地址:
4 | >https://github.com/Zeecoders/LeetCode
5 | >欢迎转载,转载请注明出处
6 |
7 | ##(一)题目
8 |
9 | >Suppose a sorted array is rotated at some pivot unknown to you beforehand.
10 | >(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
11 | >You are given a target value to search. If found in the array return its index, otherwise return -1.
12 | >You may assume no duplicate exists in the array.
13 |
14 | ##(二)解题
15 |
16 | 一个排好序的数组,经过一定的旋转之后得到新的数组,在这个新的数组中查找一个目标数。
17 | 那么,首先我们需要在旋转后的数组中找到原数组的起始点,并将数组分成两部分。
18 | 例如:4,5,6,7,0,1,2分为4,5,6,7和0,1,2
19 | 然后,确定目标数在哪一个部分,
20 | 最后,采用二分法来进行加速搜索!
21 | 具体看代码:
22 | ###未优化版本
23 | ```cpp
24 | class Solution {
25 | public:
26 |
27 | int search(vector& nums, int target) {
28 |
29 | int len = nums.size();
30 |
31 | int i = 0 ;
32 |
33 | int j = len-1;
34 |
35 | int p = 0 ;
36 |
37 | while(p+1=target) i=p+1;
42 |
43 | while(i<=j)//二分搜索
44 |
45 | {
46 |
47 | int mid = (i+j)/2;
48 |
49 | if(nums[mid] == target) return mid;
50 |
51 | else if(nums[mid] >target) j= mid-1;
52 |
53 | else i = mid+1;
54 |
55 | }
56 |
57 | return -1;//未找到则返回-1
58 |
59 | }
60 |
61 | };
62 |
63 | ```
64 |
65 | AC之后一看运行时间8ms,看来代码还有待优化,于是在查找旋转中心的方法上进行优化,采用二分法进行搜索旋转中心。
66 |
67 | ###优化版本
68 |
69 | ```cpp
70 |
71 | class Solution {
72 |
73 | public:
74 |
75 | int search(vector& nums, int target) {
76 |
77 | int len = nums.size();
78 |
79 | int i = 0;
80 |
81 | int j = len - 1;
82 |
83 | int p = 0;
84 |
85 | bool isfind = false;
86 |
87 | if (nums[0]>nums[len-1])//如果进行了旋转
88 |
89 | {
90 |
91 | while (i < j)//二分搜索旋转中心
92 |
93 | {
94 |
95 | if (i == j - 1) {
96 |
97 | isfind = true;
98 |
99 | break;
100 |
101 | }
102 |
103 | int mid = (i + j) / 2;
104 |
105 | if (nums[i] < nums[mid]) i = mid;
106 |
107 | if (nums[j] > nums[mid]) j = mid;
108 |
109 | }
110 |
111 | }
112 |
113 | if (isfind)//找到了旋转中心
114 |
115 | {
116 |
117 | if (nums[0] <= target) { j = i; i = 0; }
118 |
119 | if (nums[len - 1] >= target) { i = j; j = len - 1;}
120 |
121 | }
122 |
123 | while (i<=j)二分搜索目标数
124 |
125 | {
126 |
127 | int mid = (i + j) / 2;
128 |
129 | if (nums[mid] == target) return mid;
130 |
131 | else if (nums[mid] >target) j = mid-1;
132 |
133 | else i = mid+1;
134 |
135 | }
136 |
137 | return -1;
138 |
139 | }
140 |
141 | };
142 |
143 | ```
144 |
145 | 优化后的版本运行时间4ms,快了一半!
--------------------------------------------------------------------------------
/15 3Sum.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 |
4 | > Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
5 | >
6 | > For example, given array S = {-1 0 1 2 -1 -4},
7 | > A solution set is:
8 | > (-1, 0, 1)
9 | > (-1, -1, 2)
10 | ##(二)解题
11 | 这道题的关键在于:结果集合中不允许有重复。
12 | 想到的方法有两个:1、在查找过程中去重 2、在结果中去重
13 | 经过试验,结果中去重会直接超时。
14 | 1、过程中去重版本
15 | ```
16 | class Solution {
17 | public:
18 | vector> threeSum(vector& nums) {
19 | vector> vecresult;
20 | std::sort(nums.begin(),nums.end());
21 | int len = nums.size();
22 | if(len <3) return vecresult;
23 | for(int i = 0 ; i < nums.size() ;)
24 | {
25 | if(nums[i]>0) return vecresult;
26 | for(int j = i+1;j::iterator iter = find(nums.begin()+j+1,nums.end(),temp);
30 | if(iter != nums.end())
31 | {
32 | vector tempres;
33 | tempres.push_back(nums[i]);
34 | tempres.push_back(nums[j]);
35 | tempres.push_back(*iter);
36 | vecresult.push_back(tempres);
37 | }
38 | j++;
39 | while(j> threeSum(vector& nums) {
54 | vector> vecresult;
55 | std::sort(nums.begin(),nums.end());
56 | int len = nums.size();
57 | if(len <3) return vecresult;
58 | for(int i = 0 ; i < nums.size() ; i++)
59 | {
60 | if(nums[i]>0) return vecresult;
61 | for(int j = i+1;j::iterator iter = find(nums.begin()+j+1,nums.end(),temp);
65 | if(iter != nums.end())
66 | {
67 | vector tempres;
68 | tempres.push_back(nums[i]);
69 | tempres.push_back(nums[j]);
70 | tempres.push_back(*iter);
71 | if(vecresult.size()==0)
72 | {
73 | vecresult.push_back(tempres);
74 | }
75 | else{
76 | vector>::iterator it1 = find(vecresult.begin(),vecresult.end(),tempres);
77 | if(it1 == vecresult.end())//结果中去重
78 | {
79 | vecresult.push_back(tempres);
80 | }
81 | }
82 | }
83 | }
84 | }
85 | return vecresult;
86 | }
87 | };
88 | ```
--------------------------------------------------------------------------------
/39. Combination Sum.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 | >Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the >candidate numbers sums to T.
4 |
5 | >The same repeated number may be chosen from C unlimited number of times.
6 |
7 | >Note:
8 |
9 | >>All numbers (including target) will be positive integers.
10 |
11 | >>Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
12 |
13 | >>The solution set must not contain duplicate combinations.
14 |
15 |
16 |
17 | >For example, given candidate set 2,3,6,7 and target 7,
18 | >A solution set is:
19 | >[7]
20 | >[2, 2, 3]
21 |
22 | ##(二)解题
23 |
24 | ```cpp
25 |
26 | /*
27 |
28 | 主要思路:
29 |
30 | 1.对目标vector排序,定义一个临时的vector容器tmp
31 |
32 | 2.采用动态规划和回溯法的方法,对于当前要添加到tmp的数num
33 |
34 | (1)如果targetnum,则继续在num和num以后的数中选择一个数相加;(此处需要考虑可以重复的组合)
37 |
38 | (3)如果target==num,则代表找到
39 |
40 | 对于(2),(3)递归完成后需要将压入的数弹出,即采用回溯法的思想
41 |
42 | */
43 |
44 |
45 | class Solution {
46 |
47 | public:
48 |
49 | vector> ret;//结果
50 |
51 | vector> combinationSum(vector& candidates, int target) {
52 |
53 | sort(candidates.begin(),candidates.end());//首先进行排序
54 |
55 | for(int idx = 0;idx=0 && candidates[idx] == candidates[idx-1]) continue;//避免重复查找
60 |
61 | else{
62 |
63 | if(candidates[idx]<=target){//如果小于则调用动态规划函数
64 |
65 | vector tmp;
66 |
67 | tmp.push_back(candidates[idx]);
68 |
69 | combinationDfs(candidates,tmp,idx,target-candidates[idx]);
70 |
71 | }
72 |
73 | }
74 |
75 | }
76 |
77 | return ret;
78 |
79 | }
80 |
81 | /*candidates为目标vector
82 |
83 | tmp为临时vector变量,存储找到的组合
84 |
85 | start是初始序号,代表在start及其以后的数字中查找
86 |
87 | target是当前需要在candidates中查找的数
88 |
89 | */
90 |
91 | void combinationDfs(vector& candidates , vector& tmp , int start,int target)
92 |
93 | {
94 |
95 | if(target == 0){//如果target等于0,代表第一个数就满足
96 |
97 | ret.push_back(tmp);
98 |
99 | return;
100 |
101 | }
102 |
103 | for(int idx = start;idx candidates[idx])
108 |
109 | {
110 |
111 | tmp.push_back(candidates[idx]);
112 |
113 | combinationDfs(candidates,tmp,idx,target-candidates[idx]);
114 |
115 | tmp.pop_back();//回溯法,要pop出最后压入的元素
116 |
117 | }
118 |
119 | else if(target == candidates[idx])//等于target代表以及找到
120 |
121 | {
122 |
123 | tmp.push_back(candidates[idx]);
124 |
125 | ret.push_back(tmp);
126 |
127 | tmp.pop_back();//回溯法,要pop出最后压入的元素
128 |
129 | }
130 |
131 | else if(target < candidates[idx])
132 |
133 | {
134 |
135 | return;
136 |
137 | }
138 |
139 | }
140 |
141 | }
142 |
143 | };
144 |
145 | ```
--------------------------------------------------------------------------------
/44. Wildcard Matching.md:
--------------------------------------------------------------------------------
1 | #一天一道LeetCode系列
2 | ##(一)题目
3 | >Implement wildcard pattern matching with support for '?' and '*'.
4 | >>'?' Matches any single character.
5 | >>'*' Matches any sequence of characters (including the empty sequence).
6 | >>The matching should cover the entire input string (not partial).
7 | >>The function prototype should be:
8 | >>bool isMatch(const char *s, const char *p)
9 | >>Some examples:
10 | >>isMatch("aa","a") → false
11 | >>isMatch("aa","aa") → true
12 | >>isMatch("aaa","aa") → false
13 | >>isMatch("aa", "*") → true
14 | >>isMatch("aa", "a*") → true
15 | >>isMatch("ab", "?*") → true
16 | >>isMatch("aab", "c*a*b") → false
17 | ##(二)解题
18 | 1、递归解法
19 | 看到这题首先想到的是之前做的正则表达式那题[【一天一道LeetCode】#10. Regular Expression Matching](http://blog.csdn.net/terence1212/article/details/51185042),于是想都没有想,按照之前的方法,很明显,超时了。
20 | ```cpp
21 | /*
22 | 1.如果s[i]==p[j]||p[j] == '?' ,则i++,j++
23 | 2.如果p[j] =='*',就判断s[i]和p[j+1]以后的字串能否匹配上,如果能则返回true,如果不能则i++
24 | */
25 | class Solution {
26 | public:
27 | bool isMatch(string s, string p) {
28 | int i = 0;
29 | int j = 0;
30 | while(i一天一道leetcode系列
2 | ###(一)题目:
3 | > You are given two linked lists representing two non-negative numbers. 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.
4 | >
5 | > Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8
6 |
7 | 题目意思: 输入两个倒序的多位数,输出它们的和。
8 |
9 |
10 | ###(二)代码实现:
11 | 一看到这个题,为了图简便,直接转换成int相加,然后转成链表,结果是**Memory Limit Exceeded** 提示超出内存限制
12 | ```
13 | /**
14 | * Definition for singly-linked list.
15 | * struct ListNode {
16 | * int val;
17 | * ListNode *next;
18 | * ListNode(int x) : val(x), next(NULL) {}
19 | * };
20 | */
21 | class Solution {
22 | public:
23 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
24 | int a=0,b=0;
25 | while(l1) {
26 | a=a*10+l1->val;
27 | l1=l1->next;
28 | }
29 | while(l2) {
30 | b=b*10+l2->val;
31 | l2=l2->next;
32 | }
33 | int temp = a+b;
34 | int temp_m = temp%10;
35 | temp = temp/10;
36 | ListNode* head = new ListNode(temp_m);
37 | ListNode* p = head;
38 | while(temp/10)
39 | {
40 | temp_m = temp%10;
41 | ListNode* next = new ListNode(temp_m);
42 | p->next = next;
43 | p=p->next;
44 | }
45 | return head;
46 | }
47 | };
48 | ```
49 |
50 | 无奈,只能老老实实得按加法原则来求和了。
51 |
52 | ```
53 | /**
54 | * Definition for singly-linked list.
55 | * struct ListNode {
56 | * int val;
57 | * ListNode *next;
58 | * ListNode(int x) : val(x), next(NULL) {}
59 | * };
60 | */
61 | class Solution {
62 | public:
63 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
64 | ListNode* p = l1->next;
65 | ListNode* q = l2->next;
66 | bool jwflag = false;//进位标志位
67 | int temp = l1->val + l2->val;
68 | if(temp>=10) jwflag = true;
69 | ListNode* head = new ListNode(temp%10);
70 | ListNode* m = head;
71 | while(p && q)
72 | {
73 | if(jwflag) {temp = p->val+q->val +1;jwflag = false;}
74 | else temp = p->val+q->val;
75 | ListNode* ltemp = new ListNode(temp%10);
76 | if(temp>=10) jwflag = true;//处理进位
77 | m->next = ltemp;
78 | m = ltemp;
79 | p=p->next;
80 | q=q->next;
81 | }
82 | while(!p&&q) //p为空,q非空
83 | {
84 | if(jwflag) {temp = q->val +1;jwflag = false;}
85 | else temp = q->val;
86 | ListNode* ltemp = new ListNode(temp%10);
87 | if(temp>=10) jwflag = true;
88 | m->next = ltemp;
89 | m = ltemp;
90 | q = q->next;
91 | }
92 | while(p&&!q) //q为空,p非空
93 | {
94 | if(jwflag) {temp = p->val +1;jwflag = false;}
95 | else temp = p->val;
96 | ListNode* ltemp = new ListNode(temp%10);
97 | if(temp>=10) jwflag = true;
98 | m->next = ltemp;
99 | m = ltemp;
100 | p = p->next;
101 | }
102 | //处理最后一位的进位
103 | if(jwflag)
104 | {
105 | ListNode* ltemp = new ListNode(1);
106 | jwflag = false;
107 | m->next = ltemp;
108 | m = m->next;
109 | }
110 | return head;
111 |
112 | }
113 | };
114 | ```
115 | 结果:Accepted。
--------------------------------------------------------------------------------
/5. Longest Palindromic Substring.md:
--------------------------------------------------------------------------------
1 | # 一天一道LeetCode系列
2 | ### (一)题目
3 |
4 | > Given a string S, find the longest palindromic substring in S. You may
5 | > assume that the maximum length of S is 1000, and there exists one
6 | > unique longest palindromic substring.
7 |
8 | 题意:求一个字符串的最长回文字串。
9 |
10 | ### (二)解题
11 | #### 1.中心扩展法
12 | 看到这个题首先想到的就是中心扩展法,遍历每一个字符,然后以该字符为中心向四周扩展,这种方法的时间复杂度为O(N^2),但是需要注意的是,奇数和偶数回文字符串需要区别对待,如aba和abba都是回文字符串。
13 | ```
14 | class Solution {
15 | public:
16 | string longestPalindrome(string s) {
17 | int max1=0;//奇数最长子串
18 | int max2=0;//偶数最长子串
19 | int idx1=0;//奇数最长子串的中心字符
20 | int idx2=0;//偶数最长子串的中心字符
21 | string result;
22 | for(int i = 0 ; i < s.length() ; ++i)
23 | {
24 | int j = i;
25 | int z = i;
26 | int count1=0;
27 | int count2=0;
28 | //计算奇数最长回文字符串
29 | while((++z=0) && (s[z] == s[j]))
30 | {
31 | count1+=2;
32 | if(count1 > max1)
33 | {
34 | max1=count1;
35 | idx1 = i;
36 | }
37 | }
38 | //计算偶数最长回文字符串
39 | j = i;
40 | z = i+1;
41 | while((z=0) &&(s[z] == s[j]))
42 | {
43 | count2+=2;
44 | if(count2 > max2)
45 | {
46 | max2=count2;
47 | idx2 = i;
48 | }
49 | z++;
50 | j--;
51 | }
52 | }
53 | if(max1+1>max2) result = s.substr(idx1-max1/2,max1+1);
54 | else result = s.substr(idx2-max2/2+1,max2);
55 | return result;
56 | }
57 | };
58 | ```
59 | #### 2.中心扩展法的优化
60 | 区分奇数和偶数显得程序比较臃肿,我们可以利用“改造“字符串来避免这种情况。如aba改成#a#b#a#,abba改成#a#b#b#a,这样就不用区分奇偶了。
61 | ```
62 | class Solution {
63 | public:
64 | string longestPalindrome(string s) {
65 | int max=0;
66 | int idx=0;
67 | string temp[2005];
68 | //改造字符串
69 | int j = 0;
70 | for(int i = 0; i < s.length() ; ++i)
71 | {
72 | temp[j++] = '#';
73 | temp[j++] = s[i];
74 | }
75 | temp[j++] = '#';
76 | temp[j] = '\0';
77 | for(int i = 0 ; i <2*s.length()+1 ; ++i)
78 | {
79 | int j = i;
80 | int z = i;
81 | int count=0;
82 | //计算奇数最长回文字符串
83 | while((++z<(2*s.length()+1)) && (--j>=0) && (temp[z] == temp[j]))
84 | {
85 | count++;
86 | if(count > max)
87 | {
88 | max=count;
89 | idx = i;
90 | }
91 | }
92 |
93 | }
94 | return s.substr((idx-max)/2,max);
95 | }
96 | };
97 | ```
98 | #### 3.动态规划法
99 | DP算法的思想就是记录每一个回文子串的位置,在每一次判断是否为回文子串的时候先判断它的子串是不是回文,例如,用map[i][j]记录i到j为回文数组,如果这个时候s[i-1]==s[j+1],那么就能在O(1)时间内判断[i-1,j+1]是否为回文了。
100 | 动态规划法的时间复杂度为O(n^2).
101 |
102 | ```
103 | class Solution {
104 | public:
105 | string longestPalindrome(string s) {
106 | int len = s.length();
107 | int idx = 0;//记录最长回文字符的开始处
108 | int max = 1;//记录最长回文字符的长度
109 | int map[1000][1000] = {0};//记录i到j是否为回文子串
110 | for(int i = 0 ; i < len ; ++i)
111 | {
112 | map[i][i] = 1;//初始化长度为1的回文子串
113 | }
114 | for(int i = 0 ; i < len ; ++i)
115 | {
116 | if(s[i] == s[i+1])//初始化长度为2的子串
117 | {
118 | map[i][i+1] = 1;
119 | idx = i;
120 | max = 2;
121 | }
122 | }
123 |
124 | for(int plen = 3 ; plen <= len ; plen++)//从长度为3开始算起
125 | {//plen代表当前判断的回文子串的长度
126 | for(int j = 0 ; j < len - plen +1 ; j++)
127 | {
128 | int z = plen+j-1;//z为回文子串的尾序号
129 | if (s[j] == s[z] && map[j+1][z-1]) {
130 | //O(1)时间内判断j到z是否回文
131 | map[j][z] = 1;
132 | idx = j;
133 | max = plen;
134 | }
135 | }
136 | }
137 | return s.substr(idx,max);//返回子串
138 | }
139 | };
140 | ```
141 | #### 4.经典的Manacher算法,O(n)复杂度
142 | 算法步骤:
143 |
144 | step1:跟解法2一样,改造字符串:
145 | abba --> $#a#b#b#a#
146 | 注:加'$'是为了避免处理越界问题
147 |
148 | step2:用p[i]记录以i为中心点的回文字符串长度
149 | 改造后的字符串:$#a#b#b#a#
150 | p[]数组的值:121242121
151 | 注:p[i]-1 = 源字符串中回文子串长度
152 |
153 | step3:利用DP的思想来求解p[]
154 | 利用中心扩展法求以i为中心的最长回文串
155 | `while(i+p[i] < temps.length() && temps[i-p[i]] == temps[i+p[i]]) p[i]++;`
156 | 利用p[],mx,id记录的已有回文字符串的长度来避免大量重复的匹配
157 | `if(mx > i) p[i] = p[2*id-i] < (mx-i) ? p[2*id-i]:(mx-i);`
158 | 注:p[2*id-i]为i关于j对称的点的回文串长度
159 | mx为i之前的回文串延伸到右边的最长位置,id为该回文串的中间值
160 |
161 | ```
162 | class Solution {
163 | public:
164 | string longestPalindrome(string s) {
165 | string temps;
166 | temps+="$#";//加$是为了避免处理越界情况,减小时间复杂度
167 | for(int i = 0 ; i < s.length() ; ++i)//
168 | {
169 | temps+=s[i];
170 | temps+="#";
171 | }
172 | int *p = new int[temps.length()];//p[i]记录以i为中心的回文串长度
173 | memset(p, 0, sizeof(p));
174 |
175 | int max = 0,idx = 0;//max记录最长回文串的长度,idx记录最长回文串的中心位置
176 | int mx = 0,id = 0;//mx记录i之前的最长回文串延伸到最右边的位置,id记录该字符串的中心位置
177 | for(int i = 1; i < temps.length() ; ++i)
178 | {
179 | if(mx > i)
180 | {
181 | p[i] = p[2*id-i] < (mx-i) ? p[2*id-i]:(mx-i);
182 | }
183 | else
184 | p[i] = 1;
185 |
186 | while(i+p[i] < temps.length() && temps[i-p[i]] == temps[i+p[i]])
187 | {
188 | p[i]++;
189 | }
190 | if(i+p[i]>mx)
191 | {
192 | id = i;
193 | mx = i+p[i];
194 | if(p[i]>max)
195 | {
196 | max = p[i];
197 | idx = id;
198 | }
199 | }
200 | }
201 | max--;
202 | return s.substr((idx-max)/2,max);
203 | }
204 | };
205 | ```
206 | 该算法的时间复杂度为O(n)。
207 |
208 |
209 | 以上代码在LeetCode中均Accepted。
210 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | #【一天一道LeetCode】汇总目录
2 |
3 | >这篇博客主要收藏了博主所做题目的索引目录,帮助各位读者更加快捷的跳转到对应题目
4 | >
5 | >目录按照难易程度:easy,medium,hard来划分,读者可以按照难易程度进行练习
6 | ##(一)easy
7 | + [【一天一道LeetCode】 #1 Two Sum](http://blog.csdn.net/terence1212/article/details/51014737)
8 | + [【一天一道LeetCode】#6 ZigZag Conversion](http://blog.csdn.net/terence1212/article/details/51050912)
9 | + [【一天一道LeetCode】#7. Reverse Integer](http://blog.csdn.net/terence1212/article/details/51056866)
10 | + [【一天一道LeetCode】#8. String to Integer (atoi)](http://blog.csdn.net/terence1212/article/details/51057198)
11 | + [【一天一道LeetCode】#9. Palindrome Number](http://blog.csdn.net/terence1212/article/details/51064890)
12 | + [【一天一道LeetCode】#13. Roman to Integer](http://blog.csdn.net/terence1212/article/details/51097262)
13 | + [【一天一道LeetCode】#14 Longest Common Prefix](http://blog.csdn.net/terence1212/article/details/51116033)
14 | + [【一天一道LeetCode】#19. Remove Nth Node From End of List](http://blog.csdn.net/terence1212/article/details/51170830)
15 | + [【一天一道LeetCode】#20. Valid Parentheses](http://blog.csdn.net/terence1212/article/details/51175915)
16 | + [【一天一道LeetCode】#21. Merge Two Sorted Lists](http://blog.csdn.net/terence1212/article/details/51176174)
17 | + [【一天一道LeetCode】#24. Swap Nodes in Pairs](http://blog.csdn.net/terence1212/article/details/51223267)
18 | + [【一天一道LeetCode】#26. Remove Duplicates from Sorted Array](http://blog.csdn.net/terence1212/article/details/51242161)
19 | + [【一天一道LeetCode】#27. Remove Element](http://blog.csdn.net/terence1212/article/details/51242163)
20 | + [【一天一道LeetCode】#28. Implement strStr()](http://blog.csdn.net/terence1212/article/details/51243304)
21 | + [【一天一道LeetCode】#36. Valid Sudoku](http://blog.csdn.net/terence1212/article/details/51505834)
22 | + [【一天一道LeetCode】#38. Count and Say](http://blog.csdn.net/terence1212/article/details/51288349)
23 | + [【一天一道LeetCode】#58. Length of Last Word](http://blog.csdn.net/terence1212/article/details/51484477)
24 | + [【一天一道LeetCode】#66. Plus One](http://blog.csdn.net/terence1212/article/details/51517604)
25 | + [【一天一道LeetCode】#67. Add Binary](http://blog.csdn.net/terence1212/article/details/51517620)
26 | + [【一天一道LeetCode】#70. Climbing Stairs](http://blog.csdn.net/terence1212/article/details/51530921)
27 |
28 | ##(二)medium
29 | + [【一天一道leetcode】 #2 Add Two Numbers](http://blog.csdn.net/terence1212/article/details/51016749)
30 | + [【一天一道LeetCode】 #3 Longest Substring Without Repeating Characters](http://blog.csdn.net/terence1212/article/details/51027940)
31 | + [【一天一道LeetCode】#11Container With Most Water](http://blog.csdn.net/terence1212/article/details/51079744)
32 | + [【一天一道LeetCode】#12 Integer to Roman](http://blog.csdn.net/terence1212/article/details/51097225)
33 | + [【一天一道LeetCode】#15 3Sum](http://blog.csdn.net/terence1212/article/details/51131810)
34 | + [【一天一道LeetCode】#16. 3Sum Closest](http://blog.csdn.net/terence1212/article/details/51146924)
35 | + [【一天一道LeetCode】#17. Letter Combinations of a Phone Number](http://blog.csdn.net/terence1212/article/details/51153263)
36 | + [【一天一道LeetCode】#29. Divide Two Integers](http://blog.csdn.net/terence1212/article/details/51252578)
37 | + [【一天一道LeetCode】#31. Next Permutation](http://blog.csdn.net/terence1212/article/details/51261388)
38 | + [【一天一道LeetCode】#34. Search for a Range](http://blog.csdn.net/terence1212/article/details/51289897)
39 | + [【一天一道LeetCode】#35. Search Insert Position](http://blog.csdn.net/terence1212/article/details/51297353)
40 | + [【一天一道LeetCode】#39. Combination Sum](http://blog.csdn.net/terence1212/article/details/51308668)
41 | + [【一天一道LeetCode】#40. Combination Sum II](http://blog.csdn.net/terence1212/article/details/51317539)
42 | + [【一天一道LeetCode】#43. Multiply Strings](http://blog.csdn.net/terence1212/article/details/51340460)
43 | + [【一天一道LeetCode】#46. Permutations](http://blog.csdn.net/terence1212/article/details/51362681)
44 | + [【一天一道LeetCode】#47. Permutations II](http://blog.csdn.net/terence1212/article/details/51364023)
45 | + [【一天一道LeetCode】#48. Rotate Image](http://blog.csdn.net/terence1212/article/details/51416692)
46 | + [【一天一道LeetCode】#49. Group Anagrams](http://blog.csdn.net/terence1212/article/details/51416695)
47 | + [【一天一道LeetCode】#50. Pow(x, n)](http://blog.csdn.net/terence1212/article/details/51416698)
48 | + [【一天一道LeetCode】#53. Maximum Subarray](http://blog.csdn.net/terence1212/article/details/51448318)
49 | + [【一天一道LeetCode】#54. Spiral Matrix](http://blog.csdn.net/terence1212/article/details/51459045)
50 | + [【一天一道LeetCode】#55. Jump Game](http://blog.csdn.net/terence1212/article/details/51469020)
51 | + [【一天一道LeetCode】#59. Spiral Matrix II](http://blog.csdn.net/terence1212/article/details/51491292)
52 | + [【一天一道LeetCode】#60. Permutation Sequence.](http://blog.csdn.net/terence1212/article/details/51496680)
53 | + [【一天一道LeetCode】#61. Rotate List](http://blog.csdn.net/terence1212/article/details/51502149)
54 | + [【一天一道LeetCode】#62. Unique Paths](http://blog.csdn.net/terence1212/article/details/51502144)
55 | + [【一天一道LeetCode】#63. Unique Paths II](http://blog.csdn.net/terence1212/article/details/51504344)
56 | + [【一天一道LeetCode】#64. Minimum Path Sum.md](http://blog.csdn.net/terence1212/article/details/51509750)
57 | + [【一天一道LeetCode】#69. Sqrt(x)](http://blog.csdn.net/terence1212/article/details/51526828)
58 | + [【一天一道LeetCode】#71. Simplify Path](http://blog.csdn.net/terence1212/article/details/51532596)
59 | + [【一天一道LeetCode】#73. Set Matrix Zeroes](http://blog.csdn.net/terence1212/article/details/51547465)
60 | + [【一天一道LeetCode】#74. Search a 2D Matrix](http://blog.csdn.net/terence1212/article/details/51547727)
61 | + [【一天一道LeetCode】#75. Sort Colors](http://blog.csdn.net/terence1212/article/details/51548649)
62 | + [【一天一道LeetCode】#77. Combinations](http://blog.csdn.net/terence1212/article/details/51568184)
63 | + [【一天一道LeetCode】#78. Subsets](http://blog.csdn.net/terence1212/article/details/51568512)
64 | + [【一天一道LeetCode】#79. Word Search](http://blog.csdn.net/terence1212/article/details/51582058)
65 | + [【一天一道LeetCode】#80. Remove Duplicates from Sorted Array II](http://blog.csdn.net/terence1212/article/details/51584669)
66 | + [【一天一道LeetCode】#81. Search in Rotated Sorted Array II](http://blog.csdn.net/terence1212/article/details/51586190)
67 |
68 |
69 | ##(三)hard
70 | + [【一天一道LeetCode】#4 Median of Two Sorted Arrays](http://blog.csdn.net/terence1212/article/details/51036939)
71 | + [【一天一道LeetCode】#10. Regular Expression Matching](http://blog.csdn.net/terence1212/article/details/51185042)
72 | + [【一天一道LeetCode】#23. Merge k Sorted Lists](http://blog.csdn.net/terence1212/article/details/51210115)
73 | + [【一天一道LeetCode】#25. Reverse Nodes in k-Group](http://blog.csdn.net/terence1212/article/details/51226710)
74 | + [【一天一道LeetCode】#30. Substring with Concatenation of All Words](http://blog.csdn.net/terence1212/article/details/51493920)
75 | + [【一天一道LeetCode】#32. Longest Valid Parentheses](http://blog.csdn.net/terence1212/article/details/51277914)
76 | + [【一天一道LeetCode】#41. First Missing Positive](http://blog.csdn.net/terence1212/article/details/51326195)
77 | + [【一天一道LeetCode】#42. Trapping Rain Water](http://blog.csdn.net/terence1212/article/details/51332248)
78 | + [【一天一道LeetCode】#44. Wildcard Matching](http://blog.csdn.net/terence1212/article/details/51347772)
79 | + [【一天一道LeetCode】#45. Jump Game II](http://blog.csdn.net/terence1212/article/details/51353209)
80 | + [【一天一道LeetCode】#51. N-Queens](http://blog.csdn.net/terence1212/article/details/51435966)
81 | + [【一天一道LeetCode】#52. N-Queens II](http://blog.csdn.net/terence1212/article/details/51436107)
82 | + [【一天一道LeetCode】#56. Merge Intervals](http://blog.csdn.net/terence1212/article/details/51476535)
83 | + [【一天一道LeetCode】#57. Insert Interval](http://blog.csdn.net/terence1212/article/details/51484438)
84 | + [【一天一道LeetCode】#65. Valid Number](http://blog.csdn.net/terence1212/article/details/51516693)
85 | + [【一天一道LeetCode】#68. Text Justification](http://blog.csdn.net/terence1212/article/details/51526575)
86 | + [【一天一道LeetCode】#72. Edit Distance](http://blog.csdn.net/terence1212/article/details/51541207)
87 | + [【一天一道LeetCode】#76. Minimum Window Substring](http://blog.csdn.net/terence1212/article/details/51559544)
88 |
--------------------------------------------------------------------------------