├── 10. Regular Expression Matching.java ├── 100. Same Tree.java ├── 100_Same Tree └── main.cpp ├── 101. Symmetric Tree.java ├── 101_Sysmetric Tree └── main.cpp ├── 102. Binary Tree Level Order Traversal.java ├── 102_Binary Tree Level Order Traversal └── main.cpp ├── 103_Binary Tree Zigzag Level Order Traversal └── main.cpp ├── 104_Maximum Depth of Binary Tree └── main.cpp ├── 105_Construct Binary Tree from Preorder and Inorder Traversal └── main.cpp ├── 106_Construct Binary Tree from Inorder and Postorder Traversal └── main.cpp ├── 107_Binary Tree Level Order Traversal II └── main.cpp ├── 108_Convert Sorted Array to Binary Search Tree └── main.cpp ├── 109_Convert Sorted List to Binary Search Tree └── main.cpp ├── 10_Regular Expression Matching └── 10_Regular Expression Matching.cpp ├── 11. Container With Most Water.java ├── 11. Container With Most Water.kt ├── 110_Balanced Binary Tree └── main.cpp ├── 111_Minimum Depth of Binary Tree └── main.cpp ├── 112_Path Sum └── main.cpp ├── 113_Path Sum II └── main.cpp ├── 114_Flatten Binary Tree to Linked List └── main.cpp ├── 115. Distinct Subsequences └── 115. Distinct Subsequences.cpp ├── 1160. Find Words That Can Be Formed by Characters.java ├── 116_Populating Next Right Pointers in Each Node └── main.cpp ├── 1178. Number of Valid Words for Each Puzzle.java ├── 117_Populating Next Right Pointers in Each Node II └── main.cpp ├── 1189. Maximum Number of Balloons.java ├── 118_Pascal's Triangle └── main.cpp ├── 119_Pascal's Triangle II └── main.cpp ├── 11_Container With Most Water └── main.cpp ├── 12. Integer to Roman.java ├── 1207. Unique Number of Occurrences.java ├── 120_Triangle └── main.cpp ├── 121. Best Time to Buy and Sell Stock.java ├── 121_Best Time to Buy and Sell Stock └── main.cpp ├── 122. Best Time to Buy and Sell Stock II.java ├── 1221. Split a String in Balanced Strings.java ├── 1224. Maximum Equal Frequency.java ├── 122_Best Time to Buy and Sell Stock II └── main.cpp ├── 123. Best Time to Buy and Sell Stock III.java ├── 123. Best Time to Buy and Sell Stock III.kt ├── 1237. Find Positive Integer Solution for a Given Equation.java ├── 123_Best Time to Buy and Sell Stock III └── main.cpp ├── 1248. Count Number of Nice Subarrays.java ├── 125. Valid Palindrome.kt ├── 125_Valid Palindrome └── main.cpp ├── 1261. Find Elements in a Contaminated Binary Tree.java ├── 1268. Search Suggestions System.java ├── 1283. Find the Smallest Divisor Given a Threshold.java ├── 128_Longest Consecutive Sequencs └── main.cpp ├── 1290. Convert Binary Number in a Linked List to Integer.java ├── 1295. Find Numbers with Even Number of Digits.java ├── 1296. Divide Array in Sets of K Consecutive Numbers.java ├── 1297. Maximum Number of Occurrences of a Substring.java ├── 1299. Replace Elements with Greatest Element on Right Side.java ├── 129_Sum Root to Leaf Numbers └── main.cpp ├── 13. Roman to Integer.java ├── 1300. Sum of Mutated Array Closest to Target.java ├── 1304. Find N Unique Integers Sum up to Zero.java ├── 1306. Jump Game III.java ├── 1309. Decrypt String from Alphabet to Integer Mapping.java ├── 130_Surrounded Regions.cpp ├── 131. Palindrome Partitioning └── 131. Palindrome Partitioning.cpp ├── 134. Gas Station.kt ├── 134_Gas Station └── main.cpp ├── 135. Candy.java ├── 135. Candy.kt ├── 136_Single Number └── main.cpp ├── 137_Single Number II └── main.cpp ├── 138. Copy List with Random Pointer.java ├── 138_Copy List with Random Pointer └── main.cpp ├── 14. Longest Common Prefix.java ├── 14. Longest Common Prefix.kt ├── 141. Linked List Cycle.java ├── 141_Linked List Cycle └── main.cpp ├── 142. Linked List Cycle II.java ├── 142_Linked List Cycle II └── main.cpp ├── 143. Reorder List.java ├── 143_Reorder List └── main.cpp ├── 144_Binary Tree Preorder Traversal └── main.cpp ├── 145_Binary Tree Postorder Traversal └── main.cpp ├── 147. Insertion Sort List.java ├── 147_Insertion Sort List └── main.cpp ├── 1482. Minimum Number of Days to Make m Bouquets.java ├── 149_Max Points on a Line └── main.cpp ├── 15. 3Sum.java ├── 15. 3Sum.kt ├── 150_Evaluate Reverse Polish Notation └── main.cpp ├── 151_Reverse Words in a String └── main.cpp ├── 152_Maximum Product Subarray └── main.cpp ├── 153. Find Minimum in Rotated Sorted Array.java ├── 153_Find Minimum in Rotated Sorted Array └── main.cpp ├── 154. Find Minimum in Rotated Sorted Array II.java ├── 154_Find Minimum in Rotated Sorted Array II └── main.cpp ├── 1552. Magnetic Force Between Two Balls.java ├── 155_Min Stack └── main.cpp ├── 1576. Replace All ?'s to Avoid Consecutive Repeating Characters.java ├── 1578. Minimum Deletion Cost to Avoid Repeating Letters.java ├── 16. 3Sum Closest.java ├── 160. Intersection of Two Linked Lists.java ├── 160_Intersection of Two Linked Lists └── main.cpp ├── 162. Find Peak Element.java ├── 162_Find Peak Element └── main.cpp ├── 164_Maximum Gap └── main.cpp ├── 165_Compare Version Numbers └── main.cpp ├── 166_Fraction to Recurring Decimal └── main.cpp ├── 167. Two Sum II - Input array is sorted.java ├── 168_Excel Sheet Column Title └── main.cpp ├── 169. Majority Element.java ├── 17. Letter Combinations of a Phone Number.java ├── 172_Factorial Trailing Zeroes └── main.cpp ├── 173_Binary Search Tree Iterator └── main.cpp ├── 179. Largest Number.cpp ├── 18. 4Sum.java ├── 189_Rotate Array └── main.cpp ├── 19. Remove Nth Node From End of List.java ├── 190_Reverse Bits └── main.cpp ├── 191. Number of 1 Bits.cpp ├── 2. Add Two Numbers.java ├── 20. Valid Parentheses.java ├── 200_Number of Islands └── main.cpp ├── 201_Bitwise AND of Numbers Ranage └── main.cpp ├── 202. Happy Number.java ├── 202_Happy Number └── 202_Happy Number.cpp ├── 203. Remove Linked List Elements.java ├── 203_Remove LinkedList Elements └── main.cpp ├── 204_Count Primes └── main.cpp ├── 205. Isomorphic Strings.java ├── 205_Isomorphic Strings └── main.cpp ├── 206. Reverse Linked List.java ├── 206_Reverse Linked List └── main.cpp ├── 207. Course Schedule.java ├── 209. Minimum Size Subarray Sum.java ├── 209. Minimum Size Subarray Sum.kt ├── 21. Merge Two Sorted Lists.java ├── 215_Kth Largest Element in an Array └── main.cpp ├── 216. Combination Sum III.java ├── 217. Contains Duplicate.java ├── 217_Contains Duplicate └── main.cpp ├── 219. Contains Duplicate II.java ├── 219_Contains Duplicate II └── main.cpp ├── 22. Generate Parentheses.java ├── 220_Contains Duplicate III └── main.cpp ├── 224_Basic Calculator └── main.cpp ├── 225_Implement Stack using Queues └── main.cpp ├── 226_Invert Binary Tree └── main.cpp ├── 228. Summary Ranges.java ├── 228_Summary Ranges └── main.cpp ├── 229. Majority Element II.java ├── 22_Generate Parentheses └── main.cpp ├── 23. Merge k Sorted Lists.java ├── 23. Merge k Sorted Lists.java V2 ├── 231. Power of Two.cpp ├── 232_Implement Queue using Stacks └── main.cpp ├── 234. Palindrome Linked List.java ├── 234_Palindrome Linked List └── main.cpp ├── 237. Delete Node in a Linked List.java ├── 238. Product of Array Except Self.java ├── 238. Product of Array Except Self.kt ├── 238_Product of Array Except Self └── main.cpp ├── 23_Merge K sorted Lists └── main.cpp ├── 24. Swap Nodes in Pairs.java ├── 242. Valid Anagram.java ├── 242_Valid Anagram └── main.cpp ├── 25. Reverse Nodes in k-Group.java ├── 258_Add Digits └── main.cpp ├── 26. Remove Duplicates from Sorted Array.java ├── 260_Single Number III └── main.cpp ├── 268. Missing Number.java ├── 268_Missing Number └── main.cpp ├── 27. Remove Element.java ├── 274. H-Index.kt ├── 274_H-index └── main.cpp ├── 275_H-Index II └── main.cpp ├── 278_First Bad Version └── main.cpp ├── 279_Perfect Squares └── 279_Perfect Squares.cpp ├── 28. Implement strStr().java ├── 282_Peeking Iterator └── main.cpp ├── 283. Move Zeroes.java ├── 283_Move Zeroes └── main.cpp ├── 287. Find the Duplicate Number.java ├── 287_Find The Duplicate Number └── main.cpp ├── 289_Game of Life └── main.cpp ├── 29. Divide Two Integers.java ├── 290. Word Pattern.java ├── 290_Word Pattern └── main.cpp ├── 292_Nim Game └── 292_Nim Game.cpp ├── 299. Bulls and Cows.java ├── 3. Longest Substring Without Repeating Characters.java ├── 3. Longest Substring Without Repeating Characters.kt ├── 30. Substring with Concatenation of All Words.kt ├── 303_Range Sum Query └── main.cpp ├── 304_Range Sum Query 2D - Immutable └── main.cpp ├── 306_Additive Number └── main.cpp ├── 307_Range Sum Query └── main.cpp ├── 31. Next Permutation.java ├── 32. Longest Valid Parentheses.java ├── 326. Power of Three.cpp ├── 328. Odd Even Linked List.java ├── 32_Longest Valid Parentheses └── main.cpp ├── 33. Search in Rotated Sorted Array.java ├── 34. Find First and Last Position of Element in Sorted Array.java ├── 344. Reverse String.java ├── 344_Reverse String.cpp ├── 345. Reverse Vowels of a String.java ├── 349. Intersection of Two Arrays.cpp ├── 35. Candy.java ├── 35. Search Insert Position.java ├── 350. Intersection of Two Arrays II.cpp ├── 36. Valid Sudoku.java ├── 371. Sum of Two Integers.cpp ├── 37_Sudoku Solver └── main.cpp ├── 38. Count and Say.java ├── 380. Insert Delete GetRandom O(1).kt ├── 383. Ransom Note.cpp ├── 383. Ransom Note.kt ├── 386. Lexicographical Numbers.cpp ├── 387. First Unique Character in a String.cpp ├── 389. Find the Difference.cpp ├── 39. Combination Sum.java ├── 39_Combination Sum └── main.cpp ├── 4. Median of Two Sorted Arrays.java ├── 4. Median of Two Sorted Arrays.java V2 ├── 40. Combination Sum II.java ├── 40_Combination Sum II └── main.cpp ├── 41. First Missing Positive.java ├── 41. First Missing Positive.java V2 ├── 42. Trapping Rain Water.java ├── 42_Trapping Rain Water └── main.cpp ├── 43. Multiply Strings.java ├── 448. Find All Numbers Disappeared in an Array.java ├── 44_Wildcard Matching └── main.cpp ├── 45. Jump Game II.java ├── 45_Jump Game II └── main.cpp ├── 46. Permutations.java ├── 461. Hamming Distance.java ├── 47. Permutations II.java ├── 48. Rotate Image.java ├── 49. Group Anagrams.java ├── 496. Next Greater Element I.java ├── 5. Longest Palindromic Substring.java ├── 51_N Queens └── 51_N Queens.cpp ├── 52_N-Queens II └── main.cpp ├── 53. Maximum Subarray.java ├── 54. Spiral Matrix.java ├── 55. Jump Game.java ├── 56. Merge Intervals.java ├── 56_Merge Intervals └── main.cpp ├── 57. Insert Interval.java ├── 57_Insert Interval └── main.cpp ├── 58. Length of Last Word.java ├── 58. Length of Last Word.kt ├── 6. ZigZag Conversion.java ├── 6. Zigzag Conversion.kt ├── 61. Rotate List.java ├── 62. Unique Paths.java ├── 63. Unique Paths II.java ├── 64. Minimum Path Sum.java ├── 65_Valid Number └── 65_Valid Number.cpp ├── 66. Plus One.java ├── 67. Add Binary.java ├── 68_Text Justification └── main.cpp ├── 69. Sqrt(x).java ├── 69_Sqrt(x) └── main.cpp ├── 7. Reverse Integer.java ├── 70. Climbing Stairs.java ├── 71_Simplify Path └── main.cpp ├── 72. Edit Distance.java ├── 72_Edit Distance └── 72_Edit Distance.cpp ├── 73. Set Matrix Zeroes.java ├── 739. Daily Temperatures.java ├── 73_Set Matrix Zeroes └── 73_Set Matrix Zeroes.cpp ├── 74. Search a 2D Matrix.java ├── 74_Search a 2D Matrix └── main.cpp ├── 75. Sort Colors.java ├── 75_Sort Colors └── 75_Sort Colors.cpp ├── 76_Minimum Window Substring └── main.cpp ├── 77. Combinations.java ├── 77_Combinations └── main.cpp ├── 78. Subsets.java ├── 78_subsets └── main.cpp ├── 79. Word Search.java ├── 79_Word Search └── main.cpp ├── 8. String to Integer (atoi).java ├── 80. Remove Duplicates from Sorted Array II.java ├── 80_Remove Duplicates from Sorted Array II └── main.cpp ├── 81. Search in Rotated Sorted Array II.java ├── 81_Search in Rotated Array II └── 81_main.cpp ├── 82. Remove Duplicates from Sorted List II.java ├── 82_Remove Duplicates from sorted list └── 82_main.cpp ├── 83. Remove Duplicates from Sorted List.java ├── 84_Largest Rectangle in Histogram └── main.cpp ├── 85. Maximal Rectangle.java ├── 85_Maximal Rectangle.cpp ├── 86. Partition List.java ├── 86_Partition List └── 86_Partition List.cpp ├── 87. Scramble String.cpp ├── 87_Gray Code └── 87_Gray Code.cpp ├── 88. Merge Sorted Array.java ├── 9. Palindrome Number V2 ├── 9. Palindrome Number.java ├── 90. Subsets II.java ├── 90_Subsets II └── main.cpp ├── 91. Decode Ways.java ├── 91_Decode Ways └── main.cpp ├── 92. Reverse Linked List II.java ├── 925. Long Pressed Name.java ├── 92_Reverse Linked List II └── main.cpp ├── 93. Restore IP Addresses.java ├── 93. Restore IP Addresses └── main.cpp ├── 930. Binary Sub-arrays With Sum.java ├── 94. Binary Tree Inorder Traversal.java ├── 94_Binary Tree Inorder Traversal └── 94_Binary Tree Inorder Traversal.cpp ├── 95. Unique Binary Search Trees II.java ├── 95_Unique Binary Search Trees II └── main.cpp ├── 96. Unique Binary Search Trees.java ├── 96_Unique Binary Search Trees └── main.cpp ├── 97. Interleaving String.java ├── 97. Interleaving String └── main.cpp ├── 977. Squares of a Sorted Array.java ├── 98. Validate Binary Search Tree.java ├── 98_Validate Binary Search Tree └── main.cpp ├── 99. Recover Binary Search Tree.java ├── 992. Subarrays with K Different Integers.java ├── 99_Recover Binary Search Tree └── main.cpp ├── LeetCode01 ├── LeetCode01.cpp └── Two Sum题目分析.txt ├── LeetCode02 ├── Add Two Numbers 题目分析.txt └── LeetCode02.cpp ├── LeetCode03 ├── LeetCode03.cpp └── Longest Substring.txt ├── LeetCode04 └── main.cpp ├── LeetCode06 └── main.cpp ├── LeetCode07 ├── LeetCode07.cpp └── Reverse Integer 题目分析.txt ├── LeetCode12 └── LeetCode12.cpp ├── LeetCode13 └── LeetCode13.cpp ├── LeetCode14 └── LeetCode14.cpp ├── LeetCode15 └── main.cpp ├── LeetCode16 └── main.cpp ├── LeetCode169 └── main.cpp ├── LeetCode17 └── main.cpp ├── LeetCode171 └── main.cpp ├── LeetCode18 └── main.cpp ├── LeetCode19 └── mian.cpp ├── LeetCode20 └── mian.cpp ├── LeetCode21 └── main.cpp ├── LeetCode237 └── main.cpp ├── LeetCode24 └── main.cpp ├── LeetCode25 └── main.cpp ├── LeetCode26 └── main.cpp ├── LeetCode27 └── main.cpp ├── LeetCode28 └── main.cpp ├── LeetCode29 └── main.cpp ├── LeetCode30 └── main.cpp ├── LeetCode31 └── main.cpp ├── LeetCode33 └── main.cpp ├── LeetCode34 └── main.cpp ├── LeetCode35 └── main.cpp ├── LeetCode36 └── main.cpp ├── LeetCode38 └── main.cpp ├── LeetCode41 └── main.cpp ├── LeetCode43 └── main.cpp ├── LeetCode46 └── main.cpp ├── LeetCode47 └── main.cpp ├── LeetCode48 └── main.cpp ├── LeetCode49 └── main.cpp ├── LeetCode50 └── main.cpp ├── LeetCode53 └── main.cpp ├── LeetCode54 └── main.cpp ├── LeetCode55 └── 55_Jump Game.cpp ├── LeetCode58 └── main.cpp ├── LeetCode59 └── main.cpp ├── LeetCode60 └── main.cpp ├── LeetCode61 └── main.cpp ├── LeetCode62 └── main.cpp ├── LeetCode63 └── main.cpp ├── LeetCode64 └── main.cpp ├── LeetCode66 └── main.cpp ├── LeetCode67 └── main.cpp ├── LeetCode70 └── main.cpp ├── LeetCode80 └── main.cpp ├── LeetCode88 └── main.cpp └── README.md /10. Regular Expression Matching.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/regular-expression-matching/ 3 | * 10. Regular Expression Matching 4 | */ 5 | public class NO_10 { 6 | Solution solution = new Solution(); 7 | 8 | public static void main(String[] args) { 9 | System.out.println(new NO_10().solution.isMatch("ab", ".*")); 10 | } 11 | 12 | class Solution { 13 | // Recursion 14 | public boolean isMatch(String s, String p) { 15 | if(p.isEmpty()) { 16 | return s.isEmpty(); 17 | } 18 | 19 | boolean firstMatch = !s.isEmpty() && (s.charAt(0) == p.charAt(0) || p.charAt(0) == '.'); 20 | 21 | if (p.length() >= 2 && p.charAt(1) == '*') { 22 | return isMatch(s, p.substring(2)) || (firstMatch && isMatch(s.substring(1), p)); 23 | } else { 24 | return firstMatch && isMatch(s.substring(1), p.substring(1)); 25 | } 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /100_Same Tree/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | /** 7 | * Definition for a binary tree node. 8 | * struct TreeNode { 9 | * int val; 10 | * TreeNode *left; 11 | * TreeNode *right; 12 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 13 | * }; 14 | */ 15 | 16 | struct TreeNode{ 17 | int val; 18 | TreeNode *left; 19 | TreeNode *right; 20 | 21 | TreeNode(int x) :val(x), left(NULL), right(NULL){} 22 | }; 23 | class Solution { 24 | public: 25 | bool isSameTree(TreeNode* p, TreeNode* q) { 26 | //如果两个二叉树均为空,则返回true 27 | if (!p && !q) 28 | { 29 | return true; 30 | } 31 | //如果两者其一为空树,则返回false 32 | else if (!p || !q) 33 | { 34 | return false; 35 | } 36 | else{ 37 | if (p->val != q->val) 38 | return false; 39 | else 40 | return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); 41 | } 42 | } 43 | }; 44 | 45 | //int main() 46 | //{ 47 | // Solution s; 48 | // 49 | // 50 | //} -------------------------------------------------------------------------------- /101_Sysmetric Tree/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | /** 7 | * Definition for a binary tree node. 8 | * struct TreeNode { 9 | * int val; 10 | * TreeNode *left; 11 | * TreeNode *right; 12 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 13 | * }; 14 | */ 15 | 16 | struct TreeNode{ 17 | int val; 18 | TreeNode *left; 19 | TreeNode *right; 20 | 21 | TreeNode(int x) :val(x), left(NULL), right(NULL){} 22 | }; 23 | 24 | class Solution { 25 | public: 26 | bool isSymmetric(TreeNode* root) { 27 | if (!root) 28 | return true; 29 | else 30 | //判断左右子树是否对称 31 | return isSymmetricTree(root->left, root->right); 32 | } 33 | 34 | bool isSymmetricTree(TreeNode* p, TreeNode* q) { 35 | //如果两个二叉树均为空,则返回true 36 | if (!p && !q) 37 | { 38 | return true; 39 | } 40 | //如果两者其一为空树,则返回false 41 | else if (!p || !q) 42 | { 43 | return false; 44 | } 45 | else{ 46 | if (p->val != q->val) 47 | return false; 48 | else 49 | //p左子树应与q右子树对称,同理,p右子树应与q左子树对称 50 | return isSymmetricTree(p->left, q->right) && isSymmetricTree(p->right, q->left); 51 | } 52 | } 53 | }; 54 | 55 | int main() 56 | { 57 | 58 | } -------------------------------------------------------------------------------- /108_Convert Sorted Array to Binary Search Tree/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 15 | * }; 16 | */ 17 | 18 | struct TreeNode 19 | { 20 | int val; 21 | TreeNode *left; 22 | TreeNode *right; 23 | TreeNode(int x) : val(x), left(NULL), right(NULL){} 24 | }; 25 | 26 | class Solution { 27 | public: 28 | TreeNode* sortedArrayToBST(vector& nums) { 29 | if (nums.empty()) 30 | return NULL; 31 | 32 | else 33 | return make(nums.begin(), nums.end()); 34 | 35 | } 36 | 37 | template 38 | TreeNode *make(Iter beg, Iter end) 39 | { 40 | if (beg == end) 41 | return NULL; 42 | 43 | //求元素节点个数 44 | int size = end - beg; 45 | 46 | TreeNode *root = new TreeNode(*(beg + size / 2)); 47 | 48 | root->left = make(beg, beg + size / 2); 49 | root->right = make(beg + size / 2 + 1, end); 50 | return root; 51 | } 52 | }; 53 | 54 | int main() 55 | { 56 | vector v = { 1, 2, 3, 4 }; 57 | 58 | Solution s; 59 | TreeNode *root = s.sortedArrayToBST(v); 60 | 61 | system("pause"); 62 | return 0; 63 | } -------------------------------------------------------------------------------- /10_Regular Expression Matching/10_Regular Expression Matching.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | bool isMatch(string s, string p) { 10 | //如果字符串为空,那么模式串为空则返回true,否则返回false 11 | if (p.empty()) 12 | return s.empty(); 13 | 14 | //求模式串的长度 15 | int s_len = s.length(); 16 | 17 | //求字符串的长度 18 | int p_len = p.length(); 19 | 20 | if (p[1] == '*') 21 | { 22 | while ((s[0] != '\0' && p[0] == '.') || (s[0] == p[0])) 23 | { 24 | //字符串与模式串匹配0/1/2...个字符的情况 25 | if (isMatch(s, p.substr(2, p_len - 2))) 26 | return true; 27 | s = s.substr(1, s_len - 1); 28 | } 29 | // 字符串与模式串不能匹配 30 | return isMatch(s, p.substr(2, p_len - 2)); 31 | } 32 | else 33 | { 34 | if ((s[0] != '\0' && p[0] == '.') || (s[0] == p[0])) 35 | return isMatch(s.substr(1, s_len - 1), p.substr(1, p_len - 1)); 36 | return false; 37 | } 38 | } 39 | }; 40 | 41 | int main() 42 | { 43 | Solution s; 44 | 45 | cout << s.isMatch("aa", "a") << endl; 46 | cout << s.isMatch("aa", "aa") << endl; 47 | cout << s.isMatch("aaa", "aa") << endl; 48 | cout << s.isMatch("aa", "a*") << endl; 49 | cout << s.isMatch("aa", ".*") << endl; 50 | cout << s.isMatch("ab", ".*") << endl; 51 | cout << s.isMatch("aab", "c*a*b") << endl; 52 | cout << s.isMatch("a", "ab*") << endl; 53 | system("pause"); 54 | return 0; 55 | 56 | } -------------------------------------------------------------------------------- /11. Container With Most Water.java: -------------------------------------------------------------------------------- 1 | import sun.jvm.hotspot.memory.Space; 2 | 3 | /** 4 | * 11. Container With Most Water 5 | * 6 | * 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. 7 | * 8 | * Note: You may not slant the container and n is at least 2. 9 | */ 10 | public class NO_11 { 11 | Solution solution = new Solution(); 12 | 13 | public static void main(String[] args) { 14 | System.out.println(new NO_11().solution.maxArea(new int[] {1,8,6,2,5,4,8,3,7})); 15 | } 16 | 17 | private class Solution { 18 | public int maxArea(int[] height) { 19 | int maxVolume = 0; 20 | for (int i=0, j=height.length-1; i 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | /*用删除的方法将串s变换到t,计算变换方法数*/ 11 | int numDistinct(string s, string t) { 12 | if (s.empty() || t.empty()) 13 | return 0; 14 | else if (s.length() < t.length()) 15 | return 0; 16 | else 17 | { 18 | //动态规划 19 | int ls = s.length(), lt = t.length(); 20 | /*保存由字符串s(0,i) --> t(0,j)的方法数*/ 21 | vector > dp(ls + 1, vector(lt + 1, 0)); 22 | dp[0][0] = 1; 23 | for (int i = 0; i < ls; ++i) 24 | { 25 | /*s(0,i) 转换为 t(0)的方法数为1*/ 26 | dp[i][0] = 1; 27 | }//for 28 | for (int i = 1; i <= ls; ++i) 29 | { 30 | for (int j = 1; j <= lt; ++j) 31 | { 32 | /*首先不管当前字符是否相同,为dp[i][j]赋初值*/ 33 | dp[i][j] = dp[i - 1][j]; 34 | if (s[i-1] == t[j-1]) 35 | { 36 | /*如果s和t的当前字符相同,有两种选择保留或不保留*/ 37 | dp[i][j] += dp[i - 1][j - 1]; 38 | }//if 39 | }//for 40 | }//for 41 | return dp[ls][lt]; 42 | } 43 | } 44 | }; 45 | 46 | int main() 47 | { 48 | Solution s; 49 | cout << s.numDistinct("b", "a") << endl; 50 | 51 | system("pause"); 52 | return 0; 53 | } -------------------------------------------------------------------------------- /118_Pascal's Triangle/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | vector> generate(int numRows) { 10 | if (numRows == 0) 11 | return vector>(); 12 | else if (numRows == 1) 13 | return vector>(1, vector(1, 1)); 14 | 15 | //存储当前金字塔 16 | vector > ret = generate(numRows - 1); 17 | //计算当前行 18 | vector cur(numRows, 0); 19 | cur[0] = 1; 20 | cur[numRows - 1] = 1; 21 | 22 | for (int i = 1; i < numRows - 1; ++i) 23 | { 24 | cur[i] = ret[numRows - 2][i - 1] + ret[numRows - 2][i]; 25 | }//for 26 | ret.push_back(cur); 27 | 28 | return ret; 29 | } 30 | }; 31 | 32 | int main() 33 | { 34 | Solution s; 35 | 36 | vector > ret = s.generate(6); 37 | for (size_t i = 0; i < ret.size(); ++i) 38 | { 39 | for (size_t j = 0; j < ret[i].size(); ++j) 40 | cout << ret[i][j] << "\t"; 41 | cout << endl; 42 | } 43 | 44 | system("pause"); 45 | return 0; 46 | } -------------------------------------------------------------------------------- /119_Pascal's Triangle II/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | vector getRow(int rowIndex) { 10 | if (rowIndex == 0) 11 | return vector(1,1); 12 | 13 | //存储上一行vector 14 | vector pre = getRow(rowIndex - 1); 15 | 16 | //计算当前行 17 | vector cur(rowIndex + 1, 0); 18 | //初始化首尾元素 19 | cur[0] = 1; 20 | cur[rowIndex] = 1; 21 | 22 | //计算中间元素 23 | for (int i = 1; i < rowIndex; ++i) 24 | { 25 | cur[i] = pre[i-1] + pre[i]; 26 | }//for 27 | 28 | return cur; 29 | } 30 | }; 31 | 32 | int main() 33 | { 34 | Solution s; 35 | 36 | vector ret = s.getRow(3); 37 | for (size_t j = 0; j < ret.size(); ++j) 38 | cout << ret[j] << "\t"; 39 | cout << endl; 40 | 41 | 42 | system("pause"); 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /11_Container With Most Water/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | int maxArea(vector& height) { 11 | if (height.empty()) 12 | return 0; 13 | 14 | int maxCapacity = 0; 15 | size_t lhs = 0, rhs = height.size() - 1; 16 | 17 | while (lhs < rhs) 18 | { 19 | int capacity = (rhs - lhs) * min(height[lhs], height[rhs]); 20 | if (capacity > maxCapacity) 21 | { 22 | maxCapacity = capacity; 23 | } 24 | 25 | if (height[lhs] < height[rhs]) 26 | ++lhs; 27 | else 28 | --rhs; 29 | }//while 30 | return maxCapacity; 31 | } 32 | }; 33 | 34 | int main() 35 | { 36 | Solution s; 37 | vector v = { 1, 2, 3, 4 }; 38 | cout << s.maxArea(v) << endl; 39 | 40 | system("pause"); 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /12. Integer to Roman.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String intToRoman(int num) { 3 | String[] units = new String[] {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; 4 | String[] tens = new String[] {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; 5 | String[] hundreds = new String[] {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; 6 | String[] thousands = new String[] {"", "M", "MM", "MMM"}; 7 | 8 | return thousands[num / 1000] + hundreds[num % 1000 / 100] + tens[num % 100 / 10] + units[num % 10]; 9 | } 10 | 11 | public String intToRoman1(int num) { 12 | int[] values = new int[] {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; 13 | String[] romans = new String[] {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; 14 | 15 | StringBuilder roman = new StringBuilder(); 16 | for (int i = 0; i < values.length; ++i) { 17 | while (num >= values[i]) { 18 | roman.append(romans[i]); 19 | num -= values[i]; 20 | } 21 | } 22 | 23 | return roman.toString(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /120_Triangle/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | int minimumTotal(vector>& triangle) { 11 | if (triangle.empty()) 12 | return 0; 13 | 14 | int rows = triangle.size(); 15 | 16 | //动态规划,由于空间复杂度要求,现利用原始二维数组triangle改为存储当前(i,j)位置的最小和 17 | for (int i = 1; i < rows; ++i) 18 | { 19 | int cols = triangle[i].size(); 20 | for (int j = 0; j < cols; ++j) 21 | { 22 | //本行的第一个元素 23 | if (0 == j) 24 | { 25 | triangle[i][j] = triangle[i][j] + triangle[i - 1][j]; 26 | } 27 | //本行的最后一个元素 28 | else if (j == cols - 1) 29 | { 30 | triangle[i][j] += triangle[i - 1][j - 1]; 31 | } 32 | else{ 33 | triangle[i][j] = min(triangle[i][j] + triangle[i - 1][j], triangle[i][j] + triangle[i - 1][j - 1]); 34 | }//else 35 | }//for 36 | }//for 37 | //最小路径和为最后一行的最小值 38 | int minSum = triangle[rows - 1][0]; 39 | for (int j = 0; j < triangle[rows - 1].size(); ++j) 40 | { 41 | if (minSum > triangle[rows - 1][j]) 42 | minSum = triangle[rows - 1][j]; 43 | }//for 44 | return minSum; 45 | } 46 | }; 47 | 48 | int main() 49 | { 50 | vector> v = { { 2 }, { 3, 4 }, { 6, 5, 7 }, { 4, 1, 8, 3 } }; 51 | Solution s; 52 | cout << s.minimumTotal(v) << endl; 53 | 54 | system("pause"); 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /121. Best Time to Buy and Sell Stock.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxProfit(int[] prices) { 3 | int len = prices.length; 4 | 5 | if (len <= 1) { 6 | return 0; 7 | } 8 | 9 | int bestBuy = prices[0], maxProfit = 0; 10 | 11 | for (int i = 1; i < len; ++i) { 12 | bestBuy = Math.min(bestBuy, prices[i]); 13 | 14 | int curProfit = prices[i] > bestBuy ? prices[i] - bestBuy : 0; 15 | 16 | maxProfit = Math.max(curProfit, maxProfit); 17 | } 18 | 19 | return maxProfit; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /121_Best Time to Buy and Sell Stock/main.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shineyr/LeetCode/501fbac03deff0ae9c5cbcc0d1e2d444c3779059/121_Best Time to Buy and Sell Stock/main.cpp -------------------------------------------------------------------------------- /122. Best Time to Buy and Sell Stock II.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxProfit1(int[] prices) { 3 | int maxProfit = 0; 4 | 5 | for (int i = 0; i < prices.length; ++i) { 6 | if (i > 0 && prices[i] > prices[i-1]) { 7 | maxProfit += (prices[i] - prices[i-1]); 8 | } 9 | } 10 | 11 | return maxProfit; 12 | } 13 | 14 | public int maxProfit(int[] prices) { 15 | 16 | int valley = 0, peak = 0, maxProfit = 0; 17 | 18 | for (int i = 0; i < prices.length - 1; ) { 19 | while(i < prices.length - 1 && prices[i] > prices[i+1]) { 20 | ++i; 21 | } 22 | 23 | valley = prices[i]; 24 | 25 | while(i < prices.length - 1 && prices[i] <= prices[i+1]) { 26 | ++i; 27 | } 28 | 29 | peak = prices[i]; 30 | 31 | maxProfit += (peak - valley); 32 | } 33 | 34 | return maxProfit; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /1221. Split a String in Balanced Strings.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 1221. Split a String in Balanced Strings 3 | * 4 | * Balanced strings are those who have equal quantity of 'L' and 'R' characters. 5 | * 6 | * Given a balanced string s split it in the maximum amount of balanced strings. 7 | * 8 | * Return the maximum amount of splitted balanced strings. 9 | */ 10 | 11 | public class NO_1221 { 12 | Solution solution = new Solution(); 13 | 14 | public static void main(String[] args) { 15 | System.out.println(new NO_1221().solution.balancedStringSplit("RLRRLLRLRL")); 16 | 17 | System.out.println(new NO_1221().solution.balancedStringSplit("RLLLLRRRLR")); 18 | 19 | System.out.println(new NO_1221().solution.balancedStringSplit("LLLLRRRR")); 20 | 21 | } 22 | 23 | class Solution { 24 | public int balancedStringSplit(String s) { 25 | int totalCount = 0, lCount = 0, rCount = 0; 26 | 27 | for (int i=0; i 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | int maxProfit(vector& prices) { 10 | if (prices.empty()) 11 | return 0; 12 | 13 | int sum = 0; 14 | //只要后项比前项大,这部分值就一定可以变为利润 15 | for (size_t i = 1; i < prices.size(); ++i) 16 | { 17 | if (prices[i] > prices[i - 1]) 18 | sum += (prices[i] - prices[i - 1]); 19 | } 20 | return sum; 21 | } 22 | }; 23 | 24 | int main() 25 | { 26 | vector v = { 2, 1, 3, 5, 4, 7 }; 27 | Solution s; 28 | cout << s.maxProfit(v) << endl; 29 | 30 | system("pause"); 31 | return 0; 32 | } -------------------------------------------------------------------------------- /123. Best Time to Buy and Sell Stock III.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun maxProfit(prices: IntArray): Int { 3 | val n = prices.size 4 | 5 | val firstMaxProfits: IntArray = IntArray(n) 6 | var minPrice = prices[0] 7 | var firstMaxProfit = 0 8 | 9 | for (i in 1 .. prices.size - 1) { 10 | if (prices[i] < minPrice ) { 11 | minPrice = prices[i] 12 | } else { 13 | firstMaxProfit = max(firstMaxProfit, prices[i] - minPrice) 14 | } 15 | 16 | firstMaxProfits[i] = firstMaxProfit 17 | } 18 | 19 | var secondProfits: IntArray = IntArray(n) 20 | var maxPrice = prices[n-1] 21 | var secondMaxProfit = 0 22 | for (i in prices.size - 2 downTo 0) { 23 | if (prices[i] > maxPrice) { 24 | maxPrice = prices[i] 25 | } else { 26 | secondMaxProfit = max(secondMaxProfit, maxPrice - prices[i]) 27 | } 28 | 29 | secondProfits[i] = secondMaxProfit 30 | } 31 | 32 | var maxProfit = 0 33 | for (i in prices.indices) { 34 | maxProfit = max(maxProfit, firstMaxProfits[i] + secondProfits[i]) 35 | } 36 | 37 | return maxProfit 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /125. Valid Palindrome.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun isPalindrome(s: String): Boolean { 3 | var i = 0 4 | var j = s.lastIndex 5 | var sl = s.lowercase() 6 | while (i < j) { 7 | // Character.isLetterOrDigit(sl[i]) 8 | if (!sl[i].isLetterOrDigit()) { 9 | ++i 10 | } else if (sl[j] !in ('a' .. 'z') && sl[j] !in ('0' .. '9')) { 11 | --j 12 | } else if (sl[i] != sl[j]) { 13 | return false 14 | } else { 15 | ++i 16 | --j 17 | } 18 | } 19 | 20 | return true 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /125_Valid Palindrome/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | bool isPalindrome(string s) { 10 | if (s.empty()) 11 | return true; 12 | 13 | int size = s.length(); 14 | 15 | int lhs = 0, rhs = size - 1; 16 | while (lhs < rhs) 17 | { 18 | if (!isalpha(s[lhs])) 19 | { 20 | ++lhs; 21 | continue; 22 | } 23 | if (!isalpha(s[rhs])) 24 | { 25 | --rhs; 26 | continue; 27 | }//if 28 | 29 | if (s[lhs] != s[rhs]) 30 | return false; 31 | else 32 | { 33 | ++lhs; 34 | --rhs; 35 | } 36 | 37 | }//while 38 | return true; 39 | } 40 | //判断是否是字母数字,如果是大写字母则将其转化为小写字母 41 | bool isalpha(char &c){ 42 | if ((c >= 'A'&&c <= 'Z')){ 43 | c = c - 'A' + 'a'; 44 | return true; 45 | } 46 | return (c >= 'a'&&c <= 'z') || (c >= '0'&&c <= '9'); 47 | } 48 | }; 49 | 50 | int main() 51 | { 52 | Solution s; 53 | 54 | string str = "A man, a plan, a canal: Panama"; 55 | 56 | cout << s.isPalindrome(str) << endl; 57 | 58 | system("pause"); 59 | 60 | return 0; 61 | } -------------------------------------------------------------------------------- /1283. Find the Smallest Divisor Given a Threshold.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int smallestDivisor(int[] nums, int threshold) { 3 | if (threshold < nums.length) { 4 | return -1; 5 | } 6 | 7 | int right = Arrays.stream(nums).max().getAsInt(); 8 | int left = 1; 9 | 10 | while (left < right) { 11 | int mid = left + (right - left) / 2; 12 | 13 | if (isValid(nums, threshold, mid)) { 14 | right = mid; 15 | } else { 16 | left = mid + 1; 17 | } 18 | } 19 | 20 | return left; 21 | } 22 | 23 | private boolean isValid(int[] nums, int threshold, int divisor) { 24 | int sum = 0; 25 | 26 | for (int num : nums) { 27 | sum += (int) Math.ceil((double) num / divisor); 28 | } 29 | 30 | return sum <= threshold; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /1290. Convert Binary Number in a Linked List to Integer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 1290. Convert Binary Number in a Linked List to Integer 3 | * 4 | * Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number. 5 | * 6 | * Return the decimal value of the number in the linked list. 7 | */ 8 | public class NO_1290 { 9 | /** 10 | * Definition for singly-linked list. 11 | */ 12 | class ListNode { 13 | int val; 14 | ListNode next; 15 | ListNode(int x) { val = x; } 16 | } 17 | 18 | class Solution { 19 | public int getDecimalValue(ListNode head) { 20 | int count = 0; 21 | ListNode p = head; 22 | while (p != null) { 23 | ++count; 24 | 25 | p = p.next; 26 | } 27 | 28 | int value = 0; 29 | p = head; 30 | while (p != null) { 31 | value += p.val * Math.pow(2, count - 1); 32 | --count; 33 | p = p.next; 34 | } 35 | 36 | return value; 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /1295. Find Numbers with Even Number of Digits.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 1295. Find Numbers with Even Number of Digits 3 | * 4 | * Given an array nums of integers, return how many of them contain an even number of digits. 5 | */ 6 | public class NO_1295 { 7 | Solution solution = new Solution(); 8 | 9 | public static void main(String[] args) { 10 | System.out.println(new NO_1295().solution.findNumbers(new int[] {12,345,2,6,7896})); 11 | 12 | System.out.println(new NO_1295().solution.findNumbers(new int[] {555,901,482,1771})); 13 | 14 | } 15 | 16 | class Solution { 17 | public int findNumbers(int[] nums) { 18 | int count = 0; 19 | for (int num : nums) { 20 | if (numberOfDigits(num) % 2 == 0) { 21 | ++count; 22 | } 23 | } 24 | 25 | return count; 26 | } 27 | 28 | private int numberOfDigits(int value) { 29 | int count = 1; 30 | 31 | while (value / 10 != 0) { 32 | ++count; 33 | 34 | value /= 10; 35 | } 36 | 37 | return count; 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /1299. Replace Elements with Greatest Element on Right Side.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * 1299. Replace Elements with Greatest Element on Right Side 5 | * 6 | * Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1. 7 | * 8 | * After doing so, return the array. 9 | */ 10 | public class NO_1299 { 11 | public static void main(String[] args) { 12 | System.out.println(Arrays.toString(new Solution().replaceElements(new int[] {17,18,5,4,6,1}))); 13 | } 14 | } 15 | 16 | 17 | class Solution { 18 | public int[] replaceElements(int[] arr) { 19 | int len = arr.length, maxValue = arr[len-1]; 20 | 21 | for (int i = len-1; i>=0; --i) { 22 | if (i == len - 1) { 23 | arr[i] = -1; 24 | continue; 25 | } 26 | 27 | int curValue = arr[i]; 28 | 29 | arr[i] = maxValue; 30 | 31 | maxValue = Math.max(maxValue, curValue); 32 | 33 | } 34 | return arr; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /13. Roman to Integer.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int romanToInt(String s) { 3 | Map romanToInt = new HashMap() { 4 | { 5 | put('I', 1); 6 | put('V', 5); 7 | put('X', 10); 8 | put('L', 50); 9 | put('C', 100); 10 | put('D', 500); 11 | put('M', 1000); 12 | } 13 | }; 14 | 15 | int total = 0; 16 | for (int i = 0; i < s.length(); i++) { 17 | int curInt = romanToInt.get(s.charAt(i)); 18 | 19 | if (i + 1 < s.length()) { 20 | int nextInt = romanToInt.get(s.charAt(i+1)); 21 | 22 | if (nextInt <= curInt) { 23 | total += curInt; 24 | } else { 25 | total += (nextInt - curInt); 26 | ++i; 27 | } 28 | } else { 29 | total += curInt; 30 | } 31 | } 32 | 33 | return total; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /1304. Find N Unique Integers Sum up to Zero.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * 1304. Find N Unique Integers Sum up to Zero 5 | * 6 | * Given an integer n, return any array containing n unique integers such that they add up to 0. 7 | */ 8 | public class NO_1304 { 9 | public int[] sumZero(int n) { 10 | int[] arr = new int[n]; 11 | 12 | int middle = n / 2; 13 | 14 | for (int lIdx = 0; lIdx < middle; ++lIdx) { 15 | arr[lIdx] = lIdx - middle; 16 | } 17 | 18 | for (int idx = middle; idx < n; ++idx) { 19 | if (n % 2 != 0 && idx == middle) { 20 | arr[idx] = 0; 21 | } else { 22 | arr[idx] = 0 - arr[n-idx-1]; 23 | } 24 | } 25 | 26 | return arr; 27 | } 28 | 29 | public static void main(String[] args) { 30 | System.out.println(Arrays.toString(new NO_1304().sumZero(4))); 31 | 32 | System.out.println(Arrays.toString(new NO_1304().sumZero(9))); 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /1306. Jump Game III.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canReach(int[] arr, int start) { 3 | if (start >= 0 && start < arr.length && arr[start] >= 0) { 4 | if (arr[start] == 0) { 5 | return true; 6 | } 7 | 8 | arr[start] = -arr[start]; 9 | 10 | return canReach(arr, start + arr[start]) || canReach(arr, start - arr[start]); 11 | } 12 | 13 | return false; 14 | } 15 | 16 | public boolean canReach1(int[] arr, int start) { 17 | int len = arr.length; 18 | 19 | Queue queue = new LinkedList<>(); 20 | queue.add(start); 21 | 22 | while (!queue.isEmpty()) { 23 | int curPos = queue.poll(); 24 | 25 | if (arr[curPos] == 0) { 26 | return true; 27 | } 28 | 29 | if (arr[curPos] < 0) { 30 | continue; 31 | } 32 | 33 | int forwardPos = curPos + arr[curPos]; 34 | if (forwardPos < len) { 35 | queue.offer(forwardPos); 36 | } 37 | 38 | int backwardPos = curPos - arr[curPos]; 39 | 40 | if (backwardPos >= 0) { 41 | queue.offer(backwardPos); 42 | } 43 | 44 | arr[curPos] = -arr[curPos]; 45 | } 46 | 47 | return false; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /130_Surrounded Regions.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shineyr/LeetCode/501fbac03deff0ae9c5cbcc0d1e2d444c3779059/130_Surrounded Regions.cpp -------------------------------------------------------------------------------- /131. Palindrome Partitioning/131. Palindrome Partitioning.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shineyr/LeetCode/501fbac03deff0ae9c5cbcc0d1e2d444c3779059/131. Palindrome Partitioning/131. Palindrome Partitioning.cpp -------------------------------------------------------------------------------- /134_Gas Station/main.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | int canCompleteCircuit(vector &gas, vector &cost) { 11 | if (gas.size() == 0 || cost.size() == 0 || gas.size() != cost.size()) return -1; 12 | int total = 0, sum = 0, start = 0; 13 | for (int i = 0; i < gas.size(); ++i){ 14 | total += (gas[i] - cost[i]); 15 | if (sum < 0){ //发现油箱空了,从下一个站点尝试 16 | sum = (gas[i] - cost[i]); 17 | start = i; 18 | } 19 | else 20 | sum += (gas[i] - cost[i]); 21 | } 22 | return total < 0 ? -1 : start; //用total判断start 是否是满足要求的解 23 | } 24 | }; 25 | 26 | int main() 27 | { 28 | 29 | } -------------------------------------------------------------------------------- /135. Candy.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int candy(int[] ratings) { 3 | var candies = new int[ratings.length]; 4 | Arrays.fill(candies, 1); 5 | 6 | for (int i = 1; i < ratings.length; ++i) { 7 | if (ratings[i] > ratings[i-1]) { 8 | candies[i] = candies[i-1] + 1; 9 | } 10 | } 11 | 12 | for (int i = ratings.length - 2; i >= 0; --i) { 13 | if (ratings[i] > ratings[i+1]) { 14 | candies[i] = Math.max(candies[i], candies[i+1] + 1); 15 | } 16 | } 17 | 18 | return Arrays.stream(candies).sum(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /135. Candy.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // two direction traversal 3 | fun candy(ratings: IntArray): Int { 4 | val candies = IntArray(ratings.size, {i -> 1}) 5 | 6 | for (i in 1 .. ratings.size-1) { 7 | if (ratings[i] > ratings[i-1]) { 8 | candies[i] = candies[i-1] + 1 9 | } 10 | } 11 | for (i in ratings.size-2 downTo 0) { 12 | if (ratings[i] > ratings[i+1]) { 13 | candies[i] = max(candies[i], candies[i+1] + 1) 14 | } 15 | } 16 | 17 | return candies.sum() 18 | } 19 | } 20 | 21 | 22 | // 1 0 2 23 | // 1 1 1 24 | // 1 1 2 left to right 25 | // 2 1 2 right to left 26 | 27 | 28 | // 1 3 2 2 1 29 | // 1 1 1 1 1 30 | // 1 2 1 1 1 31 | // 1 2 1 2 1 32 | -------------------------------------------------------------------------------- /136_Single Number/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | /*利用算法库的排序实现,复杂度为O(nlogn)*/ 11 | //int singleNumber(vector& nums) { 12 | // if (nums.empty()) 13 | // return -1; 14 | // sort(nums.begin(), nums.end()); 15 | // 16 | // int size = nums.size(); 17 | 18 | // for (int i = 0; i < size - 1; i += 2) 19 | // { 20 | // if (nums[i] != nums[i + 1]) 21 | // { 22 | // return nums[i]; 23 | // }//if 24 | // }//for 25 | // return nums[size - 1]; 26 | //} 27 | 28 | /*利用异或运算实现,复杂度为O(n) a^b = b^a ; a^a = 0 ; 0^a = a^0 = a*/ 29 | int singleNumber(vector& nums) { 30 | if (nums.empty()) 31 | return -1; 32 | int ret = 0 , size = nums.size(); 33 | for (int i = 0; i < size; ++i) 34 | ret = ret ^ nums[i]; 35 | return ret; 36 | } 37 | 38 | }; 39 | 40 | int main() 41 | { 42 | Solution s; 43 | vector v = { 2, 3, 4, 3, 2 }; 44 | 45 | cout << s.singleNumber(v) << endl; 46 | 47 | system("pause"); 48 | return 0; 49 | } -------------------------------------------------------------------------------- /141. Linked List Cycle.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public boolean hasCycle(ListNode head) { 14 | if (head == null || head.next == null) { 15 | return false; 16 | } 17 | 18 | ListNode slow = head, fast = head; 19 | 20 | while(fast != null && fast.next != null) { 21 | slow = slow.next; 22 | fast = fast.next.next; 23 | 24 | if (slow == fast) { 25 | return true; 26 | } 27 | } 28 | 29 | return false; 30 | } 31 | 32 | public boolean hasCycle1(ListNode head) { 33 | if (head == null || head.next == null) { 34 | return false; 35 | } 36 | 37 | ListNode slow = head, fast = head.next; 38 | 39 | while(slow != fast) { 40 | if (fast == null || fast.next == null) { 41 | return false; 42 | } 43 | 44 | slow = slow.next; 45 | fast = fast.next.next; 46 | } 47 | 48 | return true; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /141_Linked List Cycle/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | /** 7 | * Definition for singly-linked list. 8 | * struct ListNode { 9 | * int val; 10 | * ListNode *next; 11 | * ListNode(int x) : val(x), next(NULL) {} 12 | * }; 13 | */ 14 | 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 | bool hasCycle(ListNode *head) { 24 | if (head == NULL) 25 | return false; 26 | 27 | ListNode *slow = head, *fast = head; 28 | 29 | do{ 30 | if (!slow || !fast) 31 | return false; 32 | 33 | slow = slow->next; 34 | fast = fast->next; 35 | 36 | if (fast == NULL) 37 | return false; 38 | else 39 | fast = fast->next; 40 | } while (slow != fast); 41 | 42 | return true; 43 | } 44 | }; 45 | 46 | int main() 47 | { 48 | 49 | } -------------------------------------------------------------------------------- /142. Linked List Cycle II.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public ListNode detectCycle(ListNode head) { 14 | if (head == null || head.next == null) { 15 | return null; 16 | } 17 | 18 | ListNode slow = head, fast = head; 19 | 20 | while(fast != null && fast.next != null) { 21 | slow = slow.next; 22 | fast = fast.next.next; 23 | 24 | if (slow == fast) { 25 | fast = head; 26 | break; 27 | } 28 | } 29 | 30 | while(fast != null && fast.next != null) { 31 | if (fast == slow) { 32 | return slow; 33 | } 34 | 35 | fast = fast.next; 36 | slow = slow.next; 37 | } 38 | 39 | return null; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /142_Linked List Cycle II/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | /** 7 | * Definition for singly-linked list. 8 | * struct ListNode { 9 | * int val; 10 | * ListNode *next; 11 | * ListNode(int x) : val(x), next(NULL) {} 12 | * }; 13 | */ 14 | 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 *detectCycle(ListNode *head) { 24 | if (!head) 25 | return NULL; 26 | 27 | ListNode *slow = head, *fast = head; 28 | 29 | do{ 30 | if (!slow || !fast) 31 | return NULL; 32 | 33 | slow = slow->next; 34 | fast = fast->next; 35 | 36 | if (fast == NULL) 37 | return NULL; 38 | else 39 | fast = fast->next; 40 | } while (slow != fast); 41 | 42 | slow = head; 43 | while (slow != fast) 44 | { 45 | slow = slow->next; 46 | fast = fast->next; 47 | } 48 | return slow; 49 | } 50 | }; 51 | 52 | int main() 53 | { 54 | 55 | } -------------------------------------------------------------------------------- /144_Binary Tree Preorder Traversal/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | /** 7 | * Definition for a binary tree node. 8 | * struct TreeNode { 9 | * int val; 10 | * TreeNode *left; 11 | * TreeNode *right; 12 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 13 | * }; 14 | */ 15 | 16 | struct TreeNode{ 17 | int val; 18 | TreeNode *left; 19 | TreeNode *right; 20 | TreeNode(int x) : val(x), left(NULL), right(NULL){} 21 | }; 22 | 23 | class Solution { 24 | public: 25 | vector preorderTraversal(TreeNode* root) { 26 | if (!root) 27 | return vector(); 28 | 29 | preOrder.push_back(root->val); 30 | if (root->left) 31 | preorderTraversal(root->left); 32 | if (root->right) 33 | preorderTraversal(root->right); 34 | 35 | return preOrder; 36 | } 37 | 38 | private: 39 | vector preOrder; 40 | }; -------------------------------------------------------------------------------- /145_Binary Tree Postorder Traversal/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | /** 7 | * Definition for a binary tree node. 8 | * struct TreeNode { 9 | * int val; 10 | * TreeNode *left; 11 | * TreeNode *right; 12 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 13 | * }; 14 | */ 15 | 16 | struct TreeNode{ 17 | int val; 18 | TreeNode *left; 19 | TreeNode *right; 20 | TreeNode(int x) : val(x), left(NULL), right(NULL){} 21 | }; 22 | 23 | class Solution { 24 | public: 25 | vector postorderTraversal(TreeNode* root) { 26 | if (!root) 27 | return vector(); 28 | if (root->left) 29 | postorderTraversal(root->left); 30 | if (root->right) 31 | postorderTraversal(root->right); 32 | postOrder.push_back(root->val); 33 | 34 | return postOrder; 35 | } 36 | 37 | private: 38 | vector postOrder; 39 | }; -------------------------------------------------------------------------------- /1482. Minimum Number of Days to Make m Bouquets.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minDays(int[] bloomDay, int m, int k) { 3 | int max = Arrays.stream(bloomDay).max().getAsInt(); 4 | int min = Arrays.stream(bloomDay).min().getAsInt(); 5 | 6 | int left = min, right = max, ans = -1; 7 | 8 | while (left <= right) { 9 | int mid = left + (right - left) / 2; 10 | 11 | if (isValid(bloomDay, m, k, mid)) { 12 | right = mid - 1; 13 | ans = mid; 14 | } else { 15 | left = mid + 1; 16 | } 17 | 18 | } 19 | 20 | return ans; 21 | } 22 | 23 | private boolean isValid(int[] bloomDay, int m, int k, int days) { 24 | int count = 0, lastBloom = 0; 25 | 26 | for (int i = 0; i < bloomDay.length; ++i) { 27 | if (bloomDay[i] <= days) { 28 | if (lastBloom <= i && i - lastBloom + 1 >= k) { 29 | ++count; 30 | lastBloom = i + 1; 31 | } 32 | } else { 33 | lastBloom = i + 1; 34 | } 35 | } 36 | 37 | return count >= m; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /15. 3Sum.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun threeSum(nums: IntArray): List> { 3 | var sortedNums = nums.sorted() 4 | var result = mutableListOf>() 5 | 6 | for (i in 0 ..< sortedNums.size) { 7 | if (i > 0 && sortedNums[i] == sortedNums[i-1]) { 8 | continue 9 | } 10 | 11 | var beg = i + 1 12 | var end = sortedNums.lastIndex 13 | 14 | while (beg < end) { 15 | var sum = sortedNums[i] + sortedNums[beg] + sortedNums[end] 16 | 17 | if (sum == 0) { 18 | result.add(listOf(sortedNums[i], sortedNums[beg], sortedNums[end])) 19 | 20 | while (beg < end && sortedNums[beg+1] == sortedNums[beg]) { 21 | ++beg 22 | } 23 | 24 | while (beg < end && sortedNums[end-1] == sortedNums[end]) { 25 | --end 26 | } 27 | 28 | ++beg 29 | --end 30 | } else if (sum < 0) { 31 | ++beg 32 | } else { 33 | --end 34 | } 35 | } 36 | } 37 | 38 | return result 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /153. Find Minimum in Rotated Sorted Array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findMin(int[] nums) { 3 | int len = nums.length; 4 | 5 | if (len == 1) { 6 | return nums[0]; 7 | } 8 | 9 | int left = 0, right = len - 1; 10 | 11 | if (nums[left] < nums[right]) { 12 | return nums[left]; 13 | } 14 | 15 | while (left < right) { 16 | int mid = left + (right - left) / 2; 17 | 18 | if (nums[mid] > nums[mid + 1]) { 19 | return nums[mid + 1]; 20 | } 21 | 22 | if (nums[mid - 1] > nums[mid]) { 23 | return nums[mid]; 24 | } 25 | 26 | 27 | if (nums[mid] > nums[0]) { 28 | left = mid + 1; 29 | } else { 30 | right = mid - 1; 31 | } 32 | } 33 | 34 | return -1; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /153_Find Minimum in Rotated Sorted Array/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | int findMin(vector& nums) { 10 | if (nums.empty()) 11 | return INT_MIN; 12 | 13 | //元素个数 14 | int size = nums.size(); 15 | 16 | int lhs = 0, rhs = size - 1; 17 | while (lhs <= rhs) 18 | { 19 | //递增状态,返回低位值 20 | if (nums[lhs] <= nums[rhs]) 21 | return nums[lhs]; 22 | //相邻,返回较小值 23 | else if (rhs - lhs == 1) 24 | return nums[lhs] < nums[rhs] ? nums[lhs] : nums[rhs]; 25 | 26 | //判断子序列 27 | int mid = (lhs + rhs) / 2; 28 | //右侧递增,则最小值位于左半部分 29 | if (nums[mid] < nums[rhs]) 30 | { 31 | rhs = mid; 32 | } 33 | //否则,最小值位于右半部分 34 | else{ 35 | lhs = mid + 1; 36 | } 37 | }//while 38 | } 39 | 40 | //优化函数 41 | int findMin2(vector& nums) 42 | { 43 | if (nums.size() == 1) 44 | return nums[0]; 45 | 46 | int lhs = 0, rhs = nums.size() - 1; 47 | 48 | while (nums[lhs] > nums[rhs]) 49 | { 50 | int mid = (lhs + rhs) / 2; 51 | if (nums[mid] > nums[rhs]) 52 | lhs = mid + 1; 53 | else 54 | rhs = mid; 55 | }//while 56 | return nums[lhs]; 57 | } 58 | }; 59 | 60 | int main() 61 | { 62 | Solution s; 63 | vector v = { 4, 5, 6, 7, 0, 1, 2 }; 64 | cout << s.findMin2(v) << endl; 65 | 66 | system("pause"); 67 | return 0; 68 | } -------------------------------------------------------------------------------- /154. Find Minimum in Rotated Sorted Array II.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findMin(int[] nums) { 3 | int len = nums.length; 4 | 5 | if (len == 1) { 6 | return nums[0]; 7 | } 8 | 9 | int left = 0, right = len - 1; 10 | 11 | if (nums[left] < nums[right]) { 12 | return nums[left]; 13 | } 14 | 15 | while (left < right) { 16 | int mid = left + (right - left) / 2; 17 | 18 | if (nums[mid] < nums[right]) { 19 | right = mid; 20 | } else if (nums[mid] > nums[right]) { 21 | left = mid + 1; 22 | } else { 23 | --right; 24 | } 25 | } 26 | 27 | return nums[right]; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /154_Find Minimum in Rotated Sorted Array II/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | 11 | //方法一:使用stl库函数 12 | int findMin1(vector& nums) { 13 | if (nums.empty()) 14 | return 0; 15 | 16 | vector::iterator iter = min_element(nums.begin(), nums.end()); 17 | return *iter; 18 | } 19 | 20 | //方法二:整个数列除一处为最大值到最小值的跳转外,为两部分的递增 21 | int findMin2(vector& nums) 22 | { 23 | if (nums.empty()) 24 | return 0; 25 | if (nums.size() == 1) 26 | return nums[0]; 27 | for (size_t i = 1; i < nums.size(); ++i) 28 | { 29 | if (nums[i - 1] > nums[i]) 30 | return nums[i]; 31 | }//for 32 | //没有找到跳转元素,则序列无旋转 33 | return nums[0]; 34 | } 35 | 36 | //方法三:二分查找 37 | int findMin(vector &nums) 38 | { 39 | if (nums.empty()) 40 | return 0; 41 | else if (nums.size() == 1) 42 | return nums[0]; 43 | else{ 44 | int lhs = 0, rhs = nums.size() - 1; 45 | 46 | while (lhs < rhs && nums[lhs] >= nums[rhs]) 47 | { 48 | int mid = (lhs + rhs) / 2; 49 | if (nums[lhs] > nums[mid]) 50 | rhs = mid; 51 | else if (nums[lhs] == nums[mid]) 52 | ++lhs; 53 | else 54 | lhs = mid + 1; 55 | }//while 56 | return nums[lhs]; 57 | } 58 | } 59 | }; 60 | 61 | int main() 62 | { 63 | Solution s; 64 | vector v = { 10,1,10,10 }; 65 | cout << s.findMin(v) << endl; 66 | 67 | system("pause"); 68 | return 0; 69 | } -------------------------------------------------------------------------------- /1552. Magnetic Force Between Two Balls.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxDistance(int[] position, int m) { 3 | int max = Arrays.stream(position).max().getAsInt(); 4 | int min = Arrays.stream(position).min().getAsInt(); 5 | 6 | int right = max - min, left = 1; 7 | 8 | while (left < right) { 9 | int mid = right - (right - left) / 2; 10 | 11 | if (isValid(position, m, mid)) { 12 | left = mid; 13 | } else { 14 | right = mid - 1; 15 | } 16 | } 17 | 18 | return left; 19 | } 20 | 21 | private boolean isValid(int[] position, int m, int distance) { 22 | int count = 1; 23 | 24 | Arrays.sort(position); 25 | 26 | int lastPos = position[0]; 27 | for (int i = 1; i < position.length; ++i) { 28 | if (position[i] - lastPos >= distance) { 29 | ++count; 30 | lastPos = position[i]; 31 | 32 | if (count >= m) { 33 | return true; 34 | } 35 | } 36 | } 37 | 38 | return false; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /155_Min Stack/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class MinStack { 8 | public: 9 | void push(int x) { 10 | data.push(x); 11 | if (minData.empty()) 12 | minData.push(x); 13 | else{ 14 | if (minData.top() > x) 15 | minData.push(x); 16 | else 17 | minData.push(minData.top()); 18 | } 19 | } 20 | 21 | void pop() { 22 | data.pop(); 23 | minData.pop(); 24 | } 25 | 26 | int top() { 27 | return data.top(); 28 | } 29 | 30 | int getMin() { 31 | return minData.top(); 32 | } 33 | 34 | private: 35 | stack data; 36 | stack minData; 37 | }; 38 | 39 | int main() 40 | { 41 | MinStack s; 42 | s.push(2); 43 | cout << s.top() << "\t" << s.getMin() << endl; 44 | 45 | s.push(3); 46 | cout << s.top() << "\t" << s.getMin() << endl; 47 | 48 | s.push(1); 49 | cout << s.top() << "\t" << s.getMin() << endl; 50 | 51 | system("pause"); 52 | return 0; 53 | } -------------------------------------------------------------------------------- /1576. Replace All ?'s to Avoid Consecutive Repeating Characters.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String modifyString(String s) { 3 | StringBuilder newStr = new StringBuilder(s); 4 | int slen = s.length(); 5 | 6 | for (int i = 0; i < slen; ++i) { 7 | if (s.charAt(i) != '?') { 8 | continue; 9 | } 10 | 11 | for (char c = 'a'; c <= 'z'; ++c) { 12 | if (i - 1 >= 0 && c == newStr.charAt(i-1)) { 13 | continue; 14 | } else if (i + 1 < slen && c == newStr.charAt(i+1)) { 15 | continue; 16 | } else { 17 | newStr.setCharAt(i, c); 18 | } 19 | } 20 | } 21 | 22 | return newStr.toString(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /16. 3Sum Closest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/3sum-closest/ 3 | * 16. 3Sum Closest 4 | */ 5 | 6 | import java.util.Arrays; 7 | 8 | public class NO_16 { 9 | Solution solution = new Solution(); 10 | 11 | public static void main(String[] args) { 12 | System.out.println(new NO_16().solution.threeSumClosest(new int[]{-1, 2, 1, -4}, 1)); 13 | } 14 | 15 | class Solution { 16 | 17 | // Two pointers 18 | public int threeSumClosest(int[] nums, int target) { 19 | int diff = Integer.MAX_VALUE, len = nums.length; 20 | 21 | Arrays.sort(nums); 22 | 23 | for(int i = 0; i < len && diff != 0; ++i) { 24 | int low = i + 1, high = len - 1; 25 | while (low < high) { 26 | int sum = nums[i] + nums[low] + nums[high]; 27 | 28 | if (sum < target) { 29 | low += 1; 30 | } else { 31 | high -= 1; 32 | } 33 | 34 | if (Math.abs(target - sum) < Math.abs(diff)) { 35 | diff = target - sum; 36 | } 37 | } 38 | } 39 | 40 | return target - diff; 41 | } 42 | 43 | 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /162. Find Peak Element.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findPeakElement(int[] nums) { 3 | int left = 0, right = nums.length - 1; 4 | while(left < right) { 5 | int mid = left + (right - left) / 2; 6 | 7 | if (nums[mid] < nums[mid + 1]) { 8 | left = mid + 1; 9 | } else { 10 | right = mid; 11 | } 12 | } 13 | 14 | return left; 15 | } 16 | 17 | public int findPeakElement2(int[] nums) { 18 | for (int i = 0; i < nums.length; ++i) { 19 | if (i == nums.length - 1 || nums[i] > nums[i + 1]) { 20 | return i; 21 | } 22 | } 23 | 24 | return nums.length - 1; 25 | } 26 | 27 | public int findPeakElement1(int[] nums) { 28 | int len = nums.length; 29 | 30 | if (len == 0) { 31 | return -1; 32 | } 33 | 34 | int idx = 0; 35 | 36 | for (int i = 1; i < len; ++i) { 37 | if (nums[i] > nums[i-1] && (i+1) < len && nums[i+1] < nums[i]) { 38 | return i; 39 | } else if (nums[i] > nums[i-1]) { 40 | idx = i; 41 | } 42 | } 43 | 44 | return idx; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /167. Two Sum II - Input array is sorted.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] twoSum(int[] numbers, int target) { 3 | 4 | int beg = 0, end = numbers.length - 1; 5 | 6 | while(beg < end) { 7 | int sum = numbers[beg] + numbers[end]; 8 | 9 | if (sum == target) { 10 | break; 11 | } else if (sum > target) { 12 | --end; 13 | } else { 14 | ++beg; 15 | } 16 | } 17 | 18 | return new int[] {beg + 1, end + 1}; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /168_Excel Sheet Column Title/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | Solution() 12 | { 13 | for (int i = 1; i <= 26; ++i) 14 | { 15 | char c = 'A' + i - 1; 16 | levelMap.insert({ i,c }); 17 | }//for 18 | } 19 | string convertToTitle(int n) { 20 | if (n <= 0) 21 | return ""; 22 | string str = ""; 23 | while (n) 24 | { 25 | if (n >= 1 && n <= 26) 26 | { 27 | str += levelMap[n]; 28 | reverse(str.begin(), str.end()); 29 | return str; 30 | } 31 | else{ 32 | if (n % 26 == 0) 33 | { 34 | str += 'Z'; 35 | n -= 26; 36 | } 37 | else 38 | { 39 | str += levelMap[n % 26]; 40 | }//else 41 | n /= 26; 42 | } 43 | } 44 | return str; 45 | } 46 | 47 | private: 48 | map levelMap; 49 | }; 50 | 51 | int main() 52 | { 53 | Solution *s = new Solution(); 54 | 55 | cout << s->convertToTitle(27) << endl; 56 | 57 | cout << s->convertToTitle(104) << endl; 58 | 59 | system("pause"); 60 | return 0; 61 | } -------------------------------------------------------------------------------- /169. Majority Element.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int majorityElement(int[] nums) { 3 | int len = nums.length; 4 | 5 | int majority = nums[0], count = 1; 6 | 7 | for (int i = 1; i < len; ++i) { 8 | if (count == 0) { 9 | majority = nums[i]; 10 | count = 1; 11 | continue; 12 | } 13 | 14 | if (nums[i] == majority) { 15 | ++count; 16 | } else { 17 | --count; 18 | } 19 | } 20 | 21 | return majority; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /172_Factorial Trailing Zeroes/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int trailingZeroes(int n) { 9 | int count = 0; 10 | while (n) 11 | { 12 | count += n / 5; 13 | n /= 5; 14 | } 15 | return count; 16 | } 17 | }; 18 | 19 | int main() 20 | { 21 | Solution s; 22 | cout << s.trailingZeroes(5) << endl; 23 | 24 | system("pause"); 25 | return 0; 26 | } -------------------------------------------------------------------------------- /173_Binary Search Tree Iterator/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | /** 8 | * Definition for binary tree 9 | * struct TreeNode { 10 | * int val; 11 | * TreeNode *left; 12 | * TreeNode *right; 13 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 14 | * }; 15 | */ 16 | 17 | struct TreeNode{ 18 | int val; 19 | TreeNode *left; 20 | TreeNode *right; 21 | TreeNode(int x) :val(x), left(NULL), right(NULL){} 22 | }; 23 | 24 | class BSTIterator { 25 | public: 26 | BSTIterator(TreeNode *root) { 27 | //中序遍历该二叉查找树,得到有序序列 28 | inOrder(root, inOrderNodes); 29 | } 30 | 31 | /** @return whether we have a next smallest number */ 32 | bool hasNext() { 33 | if (!inOrderNodes.empty()) 34 | return true; 35 | return false; 36 | } 37 | 38 | /** @return the next smallest number */ 39 | int next() { 40 | TreeNode *node = inOrderNodes.front(); 41 | inOrderNodes.pop(); 42 | return node->val; 43 | } 44 | private: 45 | queue inOrderNodes; 46 | 47 | void inOrder(TreeNode *root, queue &inOrderNodes) 48 | { 49 | if (!root) 50 | return; 51 | if (root->left) 52 | inOrder(root->left, inOrderNodes); 53 | 54 | inOrderNodes.push(root); 55 | 56 | if (root->right) 57 | inOrder(root->right, inOrderNodes); 58 | } 59 | }; 60 | 61 | /** 62 | * Your BSTIterator will be called like this: 63 | * BSTIterator i = BSTIterator(root); 64 | * while (i.hasNext()) cout << i.next(); 65 | */ -------------------------------------------------------------------------------- /179. Largest Number.cpp: -------------------------------------------------------------------------------- 1 | /*179. Largest Number*/ 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | 10 | bool cmp(string &s1, string &s2) 11 | { 12 | string a = s1 + s2, b = s2 + s1; 13 | return a > b; 14 | } 15 | 16 | class Solution { 17 | public: 18 | string largestNumber(vector& nums) { 19 | if (nums.empty()) 20 | return ""; 21 | 22 | vector vs; 23 | int n = nums.size(); 24 | 25 | for (int i = 0; i < n; ++i) 26 | { 27 | char tmp[10]; 28 | snprintf(tmp, 10, "%d", nums[i]); 29 | 30 | vs.push_back(tmp); 31 | }//for 32 | 33 | sort(vs.begin(), vs.end(),cmp); 34 | 35 | string ret; 36 | for (int i = 0; i < n; ++i) 37 | ret += vs[i]; 38 | int idx = 0,len = ret.size(); 39 | while (idx < len - 1 && ret[idx] == '0') 40 | ++idx; 41 | 42 | return ret.substr(idx); 43 | } 44 | }; 45 | 46 | int main() 47 | { 48 | vector v = { 0,0 }; 49 | 50 | cout << Solution().largestNumber(v) << endl; 51 | 52 | system("pause"); 53 | return 0; 54 | } -------------------------------------------------------------------------------- /189_Rotate Array/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | void rotate(vector& nums, int k) { 12 | if (nums.empty()) 13 | return; 14 | 15 | int size = nums.size(); 16 | 17 | //确定最终右旋元素个数 18 | 19 | k %= size; 20 | 21 | vector::iterator beg = nums.begin(); 22 | //旋转0~(size-k) (size-k , size); 23 | reverse(beg, beg + size - k); 24 | reverse(beg + size - k, nums.end()); 25 | //最后一次全部反转,即可完成 26 | reverse(beg, nums.end()); 27 | } 28 | }; 29 | 30 | 31 | int main() 32 | { 33 | vector v = { 1, 2, 3, 4, 5, 6, 7 }; 34 | Solution s; 35 | s.rotate(v,5); 36 | 37 | for (size_t i = 0; i < v.size(); ++i) 38 | cout << v[i] << "\t"; 39 | cout << endl; 40 | 41 | system("pause"); 42 | return 0; 43 | } -------------------------------------------------------------------------------- /190_Reverse Bits/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | //方法一 11 | uint32_t reverseBits(uint32_t n) { 12 | vector bits; 13 | //利用位运算求二进制序列 14 | while (n) 15 | { 16 | bits.push_back(n & 1); 17 | n = n>> 1; 18 | } 19 | 20 | //求二进制位反转后对应的十进制数,若bits中长度不足32,以0步之 21 | uint32_t ret = 0; 22 | int size = bits.size(); 23 | for (int i = 0 ; i > i) & 1) << (31 - i)); 36 | 37 | } 38 | return res; 39 | } 40 | }; 41 | 42 | int main() 43 | { 44 | uint32_t u = 43261596; 45 | Solution s; 46 | cout << s.reverseBits2(u) << endl; 47 | 48 | system("pause"); 49 | return 0; 50 | } -------------------------------------------------------------------------------- /191. Number of 1 Bits.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shineyr/LeetCode/501fbac03deff0ae9c5cbcc0d1e2d444c3779059/191. Number of 1 Bits.cpp -------------------------------------------------------------------------------- /200_Number of Islands/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | //等价于计算连通子图的个数 10 | int numIslands(vector>& grid) { 11 | if (grid.empty()) 12 | return 0; 13 | 14 | //计算该二维数组的行列 15 | int rows = grid.size(); 16 | int cols = grid[0].size(); 17 | 18 | int count = 0; 19 | for (int i = 0; i < rows; ++i) 20 | { 21 | for (int j = 0; j < cols; ++j) 22 | { 23 | if (grid[i][j] == '1') 24 | { 25 | ++count; 26 | dfs(grid, i, j); 27 | } 28 | continue; 29 | }//for 30 | }//for 31 | return count; 32 | } 33 | 34 | void dfs(vector> &grid, int r, int c) 35 | { 36 | if (grid.empty()) 37 | return; 38 | 39 | //计算该二维数组的行列 40 | int rows = grid.size(); 41 | int cols = grid[0].size(); 42 | 43 | if (r < 0 || r >= rows || c < 0 || c >= cols) 44 | return; 45 | 46 | if (grid[r][c] == '1') 47 | { 48 | //改变当前元素值为非'1' 49 | grid[r][c] = '2'; 50 | dfs(grid, r, c + 1); 51 | dfs(grid, r + 1, c); 52 | dfs(grid, r, c - 1); 53 | dfs(grid, r - 1, c); 54 | }//if 55 | return; 56 | } 57 | }; 58 | 59 | int main() 60 | { 61 | vector> v = { { '1', '1', '0', '0', '0' }, { '1', '1', '0', '0', '0' }, 62 | { '0', '0', '1', '0', '0' }, {'0','0','0','1','1'} }; 63 | 64 | Solution s; 65 | int ret = s.numIslands(v); 66 | cout << ret << endl; 67 | system("pause"); 68 | return 0; 69 | } -------------------------------------------------------------------------------- /201_Bitwise AND of Numbers Ranage/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | //方法一,一次遍历 TLE 9 | int rangeBitwiseAnd1(int m, int n) { 10 | 11 | int ret = m; 12 | for (int i = m+1; i <= n; ++i) 13 | { 14 | ret = ret & i; 15 | }//for 16 | return ret; 17 | } 18 | 19 | //方法二,采用递归,TLE again! 20 | int rangeBitwiseAnd2(int m, int n) { 21 | if (m == n) 22 | return m; 23 | 24 | int mid = (m + n) / 2; 25 | return rangeBitwiseAnd(m, mid) & rangeBitwiseAnd(mid + 1, n); 26 | } 27 | 28 | //方法三: 29 | int rangeBitwiseAnd(int m, int n) { 30 | int offset = 0; 31 | while (m && n) 32 | { 33 | //找到最高相同位 34 | if (m == n) 35 | { 36 | return m << offset; 37 | } 38 | m >>= 1; 39 | n >>= 1; 40 | offset++; 41 | } 42 | return 0; 43 | } 44 | }; 45 | 46 | int main() 47 | { 48 | Solution s; 49 | cout << s.rangeBitwiseAnd(5, 7) << endl; 50 | 51 | system("pause"); 52 | return 0; 53 | } -------------------------------------------------------------------------------- /202. Happy Number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isHappy(int n) { 3 | if (n <= 0) { 4 | return false; 5 | } 6 | 7 | if (n == 1) { 8 | return true; 9 | } 10 | 11 | int sum = n; 12 | while(sum != 1) { 13 | sum = squareSum(sum); 14 | 15 | // loops endlessly in a cycle 16 | if (sum == n || sum == 4) { 17 | return false; 18 | } 19 | } 20 | 21 | return true; 22 | } 23 | 24 | private int squareSum(int n) { 25 | int sum = 0; 26 | while (n > 0) { 27 | int digit = n % 10; 28 | 29 | sum += digit * digit; 30 | 31 | n /= 10; 32 | } 33 | 34 | return sum; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /202_Happy Number/202_Happy Number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | bool isHappy(int n) { 9 | if (n <= 0) 10 | return false; 11 | 12 | if (n == 1) 13 | return true; 14 | int sum = n; 15 | while (sum != 1) 16 | { 17 | int tmp = sum; 18 | sum = 0; 19 | //求各个位平方和 20 | while (tmp != 0) 21 | { 22 | sum += pow(tmp % 10, 2); 23 | tmp /= 10; 24 | }//while 25 | 26 | if (sum == n || sum == 4) 27 | return false; 28 | }//while 29 | 30 | if (sum == 1) 31 | return true; 32 | else 33 | return false; 34 | } 35 | }; 36 | 37 | int main() 38 | { 39 | Solution s; 40 | int n = 2; 41 | 42 | if (s.isHappy(n)) 43 | cout << "Yes" << endl; 44 | else 45 | cout << "No" << endl; 46 | system("pause"); 47 | return 0; 48 | } -------------------------------------------------------------------------------- /205. Isomorphic Strings.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isIsomorphic(String s, String t) { 3 | if (s.length() != t.length()) { 4 | return false; 5 | } 6 | 7 | Map map = new HashMap<>(); 8 | 9 | for (int i = 0; i < s.length(); ++i) { 10 | char sChar = s.charAt(i); 11 | char tChar = t.charAt(i); 12 | 13 | if (!map.containsKey(sChar) && !map.containsValue(tChar)) { 14 | map.put(sChar, tChar); 15 | } 16 | 17 | if (map.get(sChar) == null || map.get(sChar) != tChar) { 18 | return false; 19 | } 20 | } 21 | 22 | return true; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /205_Isomorphic Strings/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | bool isIsomorphic(string s, string t) { 10 | if (s.size() != t.size()) 11 | return false; 12 | //求两个字符串的长度 13 | int len = s.size(); 14 | 15 | //首先验证字符串s—>t的映射 16 | unordered_map um; 17 | for (int i = 0; i < len; ++i) 18 | { 19 | auto pos = um.find(s[i]); 20 | if (pos == um.end()) 21 | um.insert({ s[i], t[i] }); 22 | else{ 23 | if ((*pos).second != t[i]) 24 | return false; 25 | }//else 26 | }//for 27 | 28 | //再验证字符串t—>s的映射 29 | um.clear(); 30 | for (int i = 0; i < len; ++i) 31 | { 32 | auto pos = um.find(t[i]); 33 | if (pos == um.end()) 34 | um.insert({ t[i], s[i] }); 35 | else{ 36 | if ((*pos).second != s[i]) 37 | return false; 38 | }//else 39 | }//for 40 | return true; 41 | } 42 | }; 43 | 44 | int main() 45 | { 46 | Solution s; 47 | 48 | cout << s.isIsomorphic("egg", "add") << endl; 49 | cout << s.isIsomorphic("title", "paper") << endl; 50 | cout << s.isIsomorphic("foo", "bar") << endl; 51 | system("pause"); 52 | 53 | } -------------------------------------------------------------------------------- /206. Reverse Linked List.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode reverseList(ListNode head) { 13 | if (head == null || head.next == null) { 14 | return head; 15 | } 16 | 17 | ListNode p = head, newHead = null; 18 | 19 | while (p != null) { 20 | ListNode r = p.next; 21 | 22 | p.next = newHead; 23 | 24 | newHead = p; 25 | 26 | p = r; 27 | } 28 | 29 | return newHead; 30 | } 31 | 32 | public ListNode reverseList1(ListNode head) { 33 | if (head == null || head.next == null) { 34 | return head; 35 | } 36 | 37 | ListNode nextHead = reverseList(head.next); 38 | 39 | ListNode p = nextHead; 40 | while(p.next != null) { 41 | p = p.next; 42 | } 43 | 44 | p.next = head; 45 | head.next = null; 46 | 47 | return nextHead; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /209. Minimum Size Subarray Sum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minSubArrayLen(int s, int[] nums) { 3 | int len = nums.length; 4 | 5 | int minCount = Integer.MAX_VALUE; 6 | 7 | int left = 0, sum = 0; 8 | for (int i = 0; i < len; ++i) { 9 | sum += nums[i]; 10 | 11 | while (sum >= s) { 12 | minCount = Math.min(minCount, i + 1 - left); 13 | 14 | sum -= nums[left]; 15 | ++left; 16 | } 17 | } 18 | 19 | return minCount != Integer.MAX_VALUE ? minCount : 0; 20 | } 21 | 22 | public int minSubArrayLen1(int s, int[] nums) { 23 | int len = nums.length; 24 | 25 | int minCount = Integer.MAX_VALUE; 26 | for (int i = 0; i < len; ++i) { 27 | int sum = nums[i]; 28 | int count = 1; 29 | if (sum >= s) { 30 | minCount = Math.min(count, minCount); 31 | break; 32 | } 33 | 34 | for (int j = i + 1; j < len; ++j) { 35 | sum += nums[j]; 36 | ++count; 37 | 38 | if (sum >= s) { 39 | minCount = Math.min(count, minCount); 40 | break; 41 | } 42 | } 43 | } 44 | 45 | return minCount != Integer.MAX_VALUE ? minCount : 0; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /209. Minimum Size Subarray Sum.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun minSubArrayLen(target: Int, nums: IntArray): Int { 3 | var i = 0 4 | var left = 0 5 | var subArraySum = 0 6 | var minLength = Int.MAX_VALUE 7 | 8 | while (i < nums.size) { 9 | if (subArraySum < target) { 10 | subArraySum += nums[i] 11 | } 12 | 13 | while (subArraySum >= target && left <= i) { 14 | minLength = min(minLength, i - left + 1) 15 | 16 | subArraySum -= nums[left] 17 | ++left 18 | } 19 | 20 | ++i 21 | } 22 | 23 | return if (minLength == Int.MAX_VALUE) 0 else minLength 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /215_Kth Largest Element in an Array/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | //方法一:直观解法 时间复杂度O(nlogn) 11 | int findKthLargest1(vector& nums, int k) { 12 | int len = nums.size(); 13 | if (len <= 0 || k > len || k < 0) 14 | return INT_MIN; 15 | 16 | sort(nums.begin(), nums.end()); 17 | 18 | return nums[len - k]; 19 | } 20 | 21 | //方法二:快速选择算法,利用两个辅助数组 22 | int findKthLargest(vector& nums, int k) { 23 | int len = nums.size(); 24 | if (len <= 0 || k > len || k < 0) 25 | return INT_MIN; 26 | vector A1, A2; 27 | int idx = rand() % len; 28 | int key = nums[idx]; 29 | for (int i = 0; i < len; ++i) 30 | { 31 | if (nums[i] < key) 32 | A1.push_back(nums[i]); 33 | else if (nums[i] < key) 34 | A2.push_back(nums[i]); 35 | else 36 | continue; 37 | }//for 38 | 39 | if (k <= A1.size()) 40 | return findKthLargest(A1, k); 41 | else if (k > (len - A2.size())) 42 | return findKthLargest(A2, k - (len - A2.size())); 43 | else 44 | return key; 45 | } 46 | }; 47 | 48 | int main() 49 | { 50 | Solution s; 51 | vector v = { 3, 2, 1, 5, 6, 4 }; 52 | cout << s.findKthLargest1(v, 2) << endl; 53 | 54 | system("pause"); 55 | return 0; 56 | } -------------------------------------------------------------------------------- /216. Combination Sum III.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> combinationSum3(int k, int n) { 3 | List> combinations = new ArrayList<>(); 4 | 5 | dfs(combinations, new ArrayList<>(), 1, n, k); 6 | 7 | return combinations; 8 | } 9 | 10 | private void dfs(List> combinations, List combination, int idx, int diff, int k) { 11 | if (diff == 0 && combination.size() == k) { 12 | combinations.add(new ArrayList<>(combination)); 13 | return; 14 | } else if (diff < 0 || combination.size() == k) { 15 | return; 16 | } 17 | 18 | for (int i = idx; i <= 9; ++i) { 19 | combination.add(i); 20 | 21 | dfs(combinations, combination, i + 1, diff - i, k); 22 | 23 | combination.remove(combination.size() - 1); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /217. Contains Duplicate.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean containsDuplicate(int[] nums) { 3 | Set counts = new HashSet(); 4 | 5 | for(int i = 0; i < nums.length; ++i) { 6 | if (counts.contains(nums[i])) { 7 | return true; 8 | } else { 9 | counts.add(nums[i]); 10 | } 11 | } 12 | 13 | return false; 14 | } 15 | 16 | public boolean containsDuplicate1(int[] nums) { 17 | Arrays.sort(nums); 18 | 19 | for (int i = 1; i < nums.length; ++i) { 20 | if (nums[i] == nums[i-1]) { 21 | return true; 22 | } 23 | } 24 | 25 | return false; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /217_Contains Duplicate/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | bool containsDuplicate(vector& nums) { 10 | if (nums.empty()) 11 | return false; 12 | 13 | unordered_set us; 14 | int len = nums.size(); 15 | 16 | for (int i = 0; i < len; ++i) 17 | { 18 | if (us.count(nums[i]) != 0) 19 | return true; 20 | else 21 | us.insert(nums[i]); 22 | } 23 | return false; 24 | 25 | } 26 | }; 27 | 28 | int main() 29 | { 30 | Solution s; 31 | vector v = { 1, 2, 3 }; 32 | cout << s.containsDuplicate(v) << endl; 33 | 34 | system("pause"); 35 | return 0; 36 | } -------------------------------------------------------------------------------- /219. Contains Duplicate II.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean containsNearbyDuplicate(int[] nums, int k) { 3 | Map positions = new HashMap<>(); 4 | 5 | for (int i = 0; i < nums.length; ++i) { 6 | if (positions.containsKey(nums[i])) { 7 | int previousPos = positions.get(nums[i]); 8 | if (k >= (i - previousPos)) { 9 | return true; 10 | } 11 | } 12 | 13 | positions.put(nums[i], i); 14 | } 15 | 16 | return false; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /219_Contains Duplicate II/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | bool containsNearbyDuplicate(vector& nums, int k) { 10 | if (nums.empty()) 11 | return false; 12 | 13 | int sz = nums.size(); 14 | //使用容器unordered_set 其查找性能为常量 15 | unordered_set us; 16 | int start = 0, end = 0; 17 | for (int i = 0; i < sz; ++i) 18 | { 19 | if (us.count(nums[i]) == 0) 20 | { 21 | us.insert(nums[i]); 22 | ++end; 23 | } 24 | else{ 25 | return true; 26 | } 27 | 28 | if (end - start > k) 29 | { 30 | us.erase(nums[start]); 31 | ++start; 32 | } 33 | }//for 34 | return false; 35 | 36 | } 37 | }; 38 | 39 | int main() 40 | { 41 | vector v = { 1, 2, 3, 4, 5, 6, 2 }; 42 | Solution s; 43 | bool ret = s.containsNearbyDuplicate(v, 6); 44 | 45 | cout << ret; 46 | system("pause"); 47 | return 0; 48 | } -------------------------------------------------------------------------------- /22. Generate Parentheses.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | /** 5 | * 22. Generate Parentheses 6 | * Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 7 | */ 8 | public class NO_22 { 9 | Solution solution = new Solution(); 10 | 11 | public static void main(String[] args) { 12 | 13 | System.out.println(new NO_22().solution.generateParenthesis(3)); 14 | } 15 | 16 | class Solution { 17 | public List generateParenthesis(int n) { 18 | List strings = new ArrayList<>(); 19 | 20 | dfs(strings, "", 0, 0, n); 21 | 22 | return strings; 23 | } 24 | 25 | private void dfs(List strings, String str, int left, int right, int n) { 26 | if (right > left) { 27 | return; 28 | } 29 | 30 | if (left == n && right == n) { 31 | strings.add(str); 32 | } else { 33 | if (left < n) { 34 | dfs(strings, str + "(", left + 1, right, n); 35 | } 36 | 37 | if (right < n) { 38 | dfs(strings, str + ")", left, right + 1, n); 39 | } 40 | } 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /225_Implement Stack using Queues/main.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Stack { 9 | public: 10 | // Push element x onto stack. 11 | void push(int x) { 12 | que[flag].push(x); 13 | } 14 | 15 | // Removes the element on top of the stack. 16 | void pop() { 17 | while (que[flag].size() > 1) 18 | { 19 | que[1 - flag].push(que[flag].front()); 20 | que[flag].pop(); 21 | }//while 22 | que[flag].pop(); 23 | flag = 1 - flag; 24 | } 25 | 26 | // Get the top element. 27 | int top() { 28 | while (que[flag].size() > 1) 29 | { 30 | que[1 - flag].push(que[flag].front()); 31 | que[flag].pop(); 32 | }//while 33 | int ret = que[flag].front(); 34 | que[1 - flag].push(que[flag].front()); 35 | que[flag].pop(); 36 | 37 | flag = 1 - flag; 38 | 39 | return ret; 40 | } 41 | 42 | // Return whether the stack is empty. 43 | bool empty() { 44 | return que[flag].empty(); 45 | } 46 | 47 | private: 48 | queue que[2]; 49 | int flag = 0; //作为存储队列 50 | }; 51 | 52 | int main() 53 | { 54 | Stack s; 55 | s.push(1); 56 | s.push(2); 57 | s.push(3); 58 | cout << s.top() << endl; 59 | 60 | s.pop(); 61 | cout << s.top() << endl; 62 | 63 | system("pause"); 64 | return 0; 65 | } -------------------------------------------------------------------------------- /226_Invert Binary Tree/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | /** 8 | * Definition for a binary tree node. 9 | * struct TreeNode { 10 | * int val; 11 | * TreeNode *left; 12 | * TreeNode *right; 13 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 14 | * }; 15 | */ 16 | 17 | struct TreeNode{ 18 | int val; 19 | TreeNode *left; 20 | TreeNode *right; 21 | TreeNode(int x) :val(x), left(NULL), right(NULL){} 22 | }; 23 | 24 | class Solution { 25 | public: 26 | //递归实现 27 | TreeNode* invertTree(TreeNode* root) { 28 | if (!root) 29 | return root; 30 | 31 | TreeNode *tmp = root->left; 32 | root->left = invertTree(root->right); 33 | root->right = invertTree(tmp); 34 | 35 | return root; 36 | } 37 | 38 | //非递归实现 39 | TreeNode* invertTree2(TreeNode* root) { 40 | if (root == NULL) 41 | return root; 42 | queue tree_queue; 43 | tree_queue.push(root); 44 | 45 | while (!tree_queue.empty()){ 46 | TreeNode * pNode = tree_queue.front(); 47 | tree_queue.pop(); 48 | 49 | TreeNode * pLeft = pNode->left; 50 | pNode->left = pNode->right; 51 | pNode->right = pLeft; 52 | 53 | if (pNode->left) 54 | tree_queue.push(pNode->left); 55 | if (pNode->right) 56 | tree_queue.push(pNode->right); 57 | } 58 | return root; 59 | } 60 | }; -------------------------------------------------------------------------------- /228. Summary Ranges.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List summaryRanges(int[] nums) { 3 | List ranges = new ArrayList<>(); 4 | 5 | int len = nums.length; 6 | 7 | if (len == 0) { 8 | return ranges; 9 | } else if (len == 1) { 10 | ranges.add(String.valueOf(nums[0])); 11 | return ranges; 12 | } 13 | 14 | int start = nums[0], count = 1; 15 | for(int i = 1; i < len; ++i) { 16 | if (nums[i] == (nums[i-1] + 1)) { 17 | ++count; 18 | } else { 19 | if (count == 1) { 20 | ranges.add(String.valueOf(nums[i-1])); 21 | } else { 22 | ranges.add(String.join("->", String.valueOf(start), String.valueOf(nums[i-1]))); 23 | } 24 | 25 | start = nums[i]; 26 | count = 1; 27 | } 28 | } 29 | 30 | if (count == 1) { 31 | ranges.add(String.valueOf(nums[len - 1])); 32 | } else { 33 | ranges.add(String.join("->", String.valueOf(start), String.valueOf(nums[len-1]))); 34 | } 35 | 36 | return ranges; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /22_Generate Parentheses/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | vector generateParenthesis(int n) { 11 | if (n == 0) 12 | return vector(); 13 | 14 | vector ret; 15 | 16 | dfs(ret, "", n, n); 17 | 18 | return ret; 19 | } 20 | 21 | //利用二叉树递归思想 22 | void dfs(vector &ret, string tmp, int left, int right) 23 | { 24 | if (0 == left && 0 == right) 25 | { 26 | ret.push_back(tmp); 27 | return; 28 | } 29 | else if (left > 0) 30 | dfs(ret, tmp + '(', left - 1, right); 31 | 32 | if (left < right) 33 | dfs(ret, tmp + ')', left, right - 1); 34 | } 35 | 36 | 37 | }; 38 | 39 | int main() 40 | { 41 | Solution s; 42 | vector v = s.generateParenthesis(3); 43 | 44 | for (size_t i = 0; i < v.size(); i++) 45 | cout << v[i] << endl; 46 | 47 | system("pause"); 48 | return 0; 49 | 50 | } 51 | -------------------------------------------------------------------------------- /231. Power of Two.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | bool isPowerOfTwo(int n) { 9 | if (n <= 0) 10 | return false; 11 | return (n & (n - 1)) == 0 ? true : false; 12 | } 13 | }; 14 | 15 | int main() 16 | { 17 | cout << Solution().isPowerOfTwo(2) << endl; 18 | 19 | system("pause"); 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /232_Implement Queue using Stacks/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Queue { 9 | public: 10 | // Push element x to the back of queue. 11 | void push(int x) { 12 | inStack.push(x); 13 | } 14 | 15 | // Removes the element from in front of queue. 16 | void pop(void) { 17 | if (outStack.empty()) 18 | { 19 | while (!inStack.empty()) 20 | { 21 | outStack.push(inStack.top()); 22 | inStack.pop(); 23 | } 24 | } 25 | outStack.pop(); 26 | } 27 | 28 | // Get the front element. 29 | int peek(void) { 30 | if (outStack.empty()) 31 | { 32 | while (!inStack.empty()) 33 | { 34 | outStack.push(inStack.top()); 35 | inStack.pop(); 36 | } 37 | } 38 | return outStack.top(); 39 | } 40 | 41 | // Return whether the queue is empty. 42 | bool empty(void) { 43 | if (outStack.empty() && inStack.empty()) 44 | return true; 45 | return false; 46 | } 47 | 48 | private: 49 | stack inStack; 50 | stack outStack; 51 | }; 52 | 53 | int main() 54 | { 55 | Queue q; 56 | q.push(1); 57 | q.push(2); 58 | q.push(3); 59 | 60 | cout << q.peek() << endl; 61 | q.pop(); 62 | cout << q.peek() << endl; 63 | 64 | system("pause"); 65 | return 0; 66 | } -------------------------------------------------------------------------------- /237. Delete Node in a Linked List.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | class Solution { 10 | public void deleteNode(ListNode node) { 11 | node.val = node.next.val; 12 | 13 | // now delete node.next 14 | node.next = node.next.next; 15 | } 16 | 17 | public void deleteNode1(ListNode node) { 18 | if (node == null) { 19 | return; 20 | } 21 | 22 | ListNode pre = node, next = node.next; 23 | 24 | while(next != null) { 25 | int tmp = node.val; 26 | node.val = next.val; 27 | next.val = tmp; 28 | 29 | pre = node; 30 | node = next; 31 | next = node.next; 32 | } 33 | 34 | pre.next = null; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /238. Product of Array Except Self.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] productExceptSelf(int[] nums) { 3 | int len = nums.length; 4 | int[] product = new int[len]; 5 | product[0] = 1; 6 | 7 | for (int i = 1; i < len; ++i) { 8 | product[i] = product[i-1] * nums[i-1]; 9 | } 10 | 11 | int rightMultiple = 1; 12 | for (int j = len - 1; j >= 0; --j) { 13 | product[j] *= rightMultiple; 14 | 15 | rightMultiple *= nums[j]; 16 | } 17 | 18 | return product; 19 | } 20 | 21 | public int[] productExceptSelf1(int[] nums) { 22 | int len = nums.length; 23 | int[] product = new int[len]; 24 | 25 | int[] leftProduct = new int[len]; 26 | leftProduct[0] = 1; 27 | 28 | int[] rightProduct = new int[len]; 29 | rightProduct[len - 1] = 1; 30 | 31 | for (int i = 1; i < len; ++i) { 32 | leftProduct[i] = leftProduct[i-1] * nums[i-1]; 33 | } 34 | 35 | for (int j = len-2; j >= 0; --j) { 36 | rightProduct[j] = rightProduct[j+1] * nums[j+1]; 37 | } 38 | 39 | for (int i = 0; i < len; ++i) { 40 | product[i] = leftProduct[i] * rightProduct[i]; 41 | } 42 | 43 | return product; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /238_Product of Array Except Self/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | vector productExceptSelf(vector& nums) { 10 | if (nums.empty()) 11 | return vector(); 12 | 13 | int sz = nums.size(); 14 | vector ret(sz, 0); 15 | 16 | //对每个i位置的元素得到ret[i] = nums[0] * nums[1] * ... *nums[i-1] 17 | ret[0] = 1; 18 | for (int i = 1; i < sz; ++i) 19 | { 20 | ret[i] = ret[i - 1] * nums[i-1]; 21 | }//for 22 | 23 | //对每个i位置的元素当前乘积ret[i] *= nums[i+1] ... nums[sz-1] 24 | int tmp = 1; 25 | for (int i = sz - 1; i >= 0; --i) 26 | { 27 | ret[i] *= tmp; 28 | tmp *= nums[i]; 29 | } 30 | return ret; 31 | } 32 | }; 33 | 34 | int main() 35 | { 36 | Solution s; 37 | vector v = { 1, 2, 3, 4 }; 38 | 39 | v = s.productExceptSelf(v); 40 | 41 | for (unsigned i = 0; i < v.size(); ++i) 42 | cout << v[i] << endl; 43 | cout << endl; 44 | 45 | system("pause"); 46 | return 0; 47 | } -------------------------------------------------------------------------------- /242. Valid Anagram.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isAnagram(String s, String t) { 3 | if (s.length() != t.length()) { 4 | return false; 5 | } 6 | 7 | int[] counts = new int[26]; 8 | 9 | for (char c : s.toCharArray()) { 10 | counts[c - 'a'] += 1; 11 | } 12 | 13 | for (char c : t.toCharArray()) { 14 | counts[c - 'a'] -= 1; 15 | 16 | if (counts[c - 'a'] < 0) { 17 | return false; 18 | } 19 | } 20 | 21 | return true; 22 | } 23 | 24 | public boolean isAnagram1(String s, String t) { 25 | if (s.length() != t.length()) { 26 | return false; 27 | } 28 | 29 | char[] sArr = s.toCharArray(); 30 | char[] tArr = t.toCharArray(); 31 | 32 | Arrays.sort(sArr); 33 | Arrays.sort(tArr); 34 | 35 | return Arrays.equals(sArr, tArr); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /242_Valid Anagram/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | //方法一:排序判断 11 | bool isAnagram1(string s, string t) { 12 | if (s.empty() && t.empty()) 13 | return true; 14 | else if (s.empty() || t.empty()) 15 | return false; 16 | 17 | sort(s.begin(), s.end()); 18 | sort(t.begin(), t.end()); 19 | 20 | if (s == t) 21 | return true; 22 | return false; 23 | } 24 | //方法二:字母个数判相等 25 | bool isAnagram(string s, string t) { 26 | vector count(26, 0); 27 | for (int i = 0; i < s.size(); i++) 28 | count[s[i] - 'a'] ++; 29 | for (int i = 0; i < t.size(); i++) 30 | count[t[i] - 'a'] --; 31 | for (int i = 0; i < 26; i++) 32 | if (count[i] != 0) 33 | return false; 34 | return true; 35 | } 36 | }; 37 | 38 | int main() 39 | { 40 | Solution s; 41 | string s1 = "anagram", s2 = "nagaram"; 42 | cout << s.isAnagram(s1, s2) << endl; 43 | 44 | system("pause"); 45 | return 0; 46 | } -------------------------------------------------------------------------------- /258_Add Digits/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | //常规方法计算 10 | int addDigits1(int num) { 11 | if (num / 10 == 0) 12 | return num; 13 | 14 | while (num / 10 != 0) 15 | { 16 | //求出num的各个位数字之和 17 | int tmp = 0; 18 | while (num) 19 | { 20 | tmp += num % 10; 21 | num /= 10; 22 | }//while 23 | num = tmp; 24 | }//while 25 | return num; 26 | } 27 | //结果为:(num - 1) % 9 + 1 28 | int addDigits(int num) { 29 | return (num - 1) % 9 + 1; 30 | } 31 | 32 | }; 33 | 34 | int main() 35 | { 36 | Solution s; 37 | cout << s.addDigits(38) << endl; 38 | 39 | system("pause"); 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /26. Remove Duplicates from Sorted Array.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/remove-duplicates-from-sorted-array/solution/ 3 | * 26. Remove Duplicates from Sorted Array 4 | */ 5 | public class NO_26 { 6 | Solution solution = new Solution(); 7 | 8 | public static void main(String[] args) { 9 | System.out.println(new NO_26().solution.removeDuplicates(new int[] {1,1,2})); 10 | } 11 | 12 | class Solution { 13 | public int removeDuplicates(int[] nums) { 14 | int len = nums.length; 15 | 16 | if(len <= 1) { 17 | return len; 18 | } 19 | 20 | int count = 1, idx = 1; 21 | while (idx < len) { 22 | if (nums[idx] != nums[idx-1]) { 23 | nums[count] = nums[idx]; 24 | ++count; 25 | } 26 | ++idx; 27 | } 28 | 29 | return count; 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /260_Single Number III/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | //方法一:借助数据结构unordered_set,占用了额外O(n)的空间 11 | vector singleNumber1(vector& nums) { 12 | if (nums.empty()) 13 | return vector(); 14 | 15 | int len = nums.size(); 16 | 17 | unordered_set us; 18 | for (int i = 0; i < len; ++i) 19 | { 20 | if (us.count(nums[i]) == 0) 21 | us.insert(nums[i]); 22 | else 23 | us.erase(nums[i]); 24 | }//for 25 | 26 | return vector(us.begin(), us.end()); 27 | } 28 | 29 | //方法二:线性时间复杂度,常量空间复杂度 30 | vector singleNumber(vector& nums) { 31 | if (nums.empty()) 32 | return vector(); 33 | 34 | int len = nums.size(); 35 | int res = 0; 36 | for (int i = 0; i < len; ++i) 37 | { 38 | res ^= nums[i]; 39 | }//for 40 | 41 | vector ret(2, 0); 42 | //利用位运算,将原数组一分为二,每个部分含有一个只出现一次的数字,其余数字出现两次 43 | int n = res & (~(res - 1)); 44 | for (int i = 0; i < len; ++i) 45 | { 46 | if ((n & nums[i]) != 0) 47 | { 48 | ret[0] ^= nums[i]; 49 | } 50 | else{ 51 | ret[1] ^= nums[i]; 52 | }//else 53 | }//for 54 | 55 | return ret; 56 | } 57 | }; 58 | 59 | int main() 60 | { 61 | Solution s; 62 | vector nums = { 1, 2, 1, 3, 2, 5 }; 63 | 64 | vector ret = s.singleNumber(nums); 65 | 66 | cout << ret[0] << "\t" << ret[1] << endl; 67 | 68 | system("pause"); 69 | return 0; 70 | } -------------------------------------------------------------------------------- /268. Missing Number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int missingNumber(int[] nums) { 3 | int n = nums.length; 4 | 5 | int sum = 0; 6 | for (int i = 0; i < n; ++i) { 7 | sum += nums[i]; 8 | } 9 | 10 | return n * (n + 1) / 2 - sum; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /268_Missing Number/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | /*方法一:排序法,时间复杂度为O(nlogn)*/ 10 | int missingNumber1(vector& nums) { 11 | if (nums.empty()) 12 | return 0; 13 | 14 | sort(nums.begin(), nums.end()); 15 | 16 | for (unsigned i = 0; i < nums.size(); ++i) 17 | { 18 | if (nums[i] != i) 19 | return i; 20 | }//for 21 | return nums.size(); 22 | } 23 | 24 | /*方法二:等差数列,期望序列元素为 0 - n ; 实际元素缺失一个,用(0+1+...+n)-(实际元素之和)即是缺失元素*/ 25 | int missingNumber(vector& nums) { 26 | if (nums.empty()) 27 | return 0; 28 | int n = nums.size(); 29 | 30 | //先求得0+1+2+...+n的和 31 | int sum = 0, i = 0; 32 | while (i <= n) 33 | { 34 | sum += (i++); 35 | } 36 | //找出缺失元素 37 | for (int i = 0; i < n; ++i) 38 | { 39 | sum -= nums[i]; 40 | }//for 41 | return sum; 42 | } 43 | }; 44 | 45 | int main() 46 | { 47 | Solution s; 48 | vector v = { 0, 1, 2 }; 49 | cout << s.missingNumber(v) << endl; 50 | 51 | system("pause"); 52 | return 0; 53 | } -------------------------------------------------------------------------------- /27. Remove Element.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/remove-element/submissions/ 3 | * 27. Remove Element 4 | */ 5 | public class NO_27 { 6 | Solution solution = new Solution(); 7 | 8 | public static void main(String[] args) { 9 | System.out.println(new NO_27().solution.removeElement(new int[]{0,1,2,2,3,0,4,2}, 2)); 10 | } 11 | 12 | class Solution { 13 | 14 | // Two pointers 15 | public int removeElement(int[] nums, int val) { 16 | int i = 0, j = 0; 17 | while (j < nums.length) { 18 | if (nums[j] != val) { 19 | nums[i] = nums[j]; 20 | ++i; 21 | } 22 | 23 | ++j; 24 | } 25 | return i; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /274. H-Index.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun hIndex(citations: IntArray): Int { 3 | val sortedCitations = citations.sorted() 4 | 5 | var maxH = 0 6 | 7 | for (i in 0 .. sortedCitations.size - 1) { 8 | val h = sortedCitations.size - i // at least h papers to the end 9 | 10 | if (sortedCitations[i] >= h) { // have each been cited at least h times. 11 | maxH = max(maxH, h) 12 | } 13 | } 14 | 15 | return maxH 16 | } 17 | } 18 | 19 | 20 | // 3, 0, 6, 1 5 21 | // 0, 1, 3, 5, 6 22 | -------------------------------------------------------------------------------- /274_H-index/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | int hIndex(vector& citations) { 11 | if (citations.empty()) 12 | return 0; 13 | //对所给序列排序 14 | sort(citations.begin(), citations.end()); 15 | 16 | int len = citations.size(),maxH = 0; 17 | for (int i = len - 1; i >= 0; --i) 18 | { 19 | int h = len - i; 20 | if (citations[i] >= h && h > maxH) 21 | { 22 | maxH = h; 23 | } 24 | else{ 25 | break; 26 | } 27 | }//for 28 | return maxH; 29 | } 30 | }; 31 | 32 | int main() 33 | { 34 | vector v = { 3, 0, 6, 1, 5 }; 35 | Solution s; 36 | 37 | cout << s.hIndex(v) << endl; 38 | 39 | system("pause"); 40 | return 0; 41 | } -------------------------------------------------------------------------------- /275_H-Index II/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | //所给元素递增 11 | int hIndex(vector& citations) { 12 | if (citations.empty()) 13 | return 0; 14 | 15 | int len = citations.size(), maxH = 0; 16 | for (int i = len - 1; i >= 0; --i) 17 | { 18 | int h = len - i; 19 | if (citations[i] >= h && h > maxH) 20 | { 21 | maxH = h; 22 | } 23 | else{ 24 | break; 25 | } 26 | }//for 27 | return maxH; 28 | } 29 | }; 30 | 31 | int main() 32 | { 33 | vector v = { 0, 1, 3, 5, 6 }; 34 | Solution s; 35 | 36 | cout << s.hIndex(v) << endl; 37 | 38 | system("pause"); 39 | return 0; 40 | } -------------------------------------------------------------------------------- /278_First Bad Version/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | // Forward declaration of isBadVersion API. 8 | bool isBadVersion(int version); 9 | 10 | class Solution { 11 | public: 12 | int firstBadVersion(int n) { 13 | if (n < 1) 14 | return -1; 15 | int lhs = 1, rhs = n; 16 | 17 | while (lhs < rhs) 18 | { 19 | int mid = lhs + (rhs - lhs) / 2; 20 | //找到bad version 21 | if (isBadVersion(mid)) 22 | { 23 | rhs = mid; 24 | } 25 | //mid并不是bad version 则first bad肯定在右边 26 | else{ 27 | lhs = mid + 1; 28 | } 29 | }//while 30 | return lhs; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /279_Perfect Squares/279_Perfect Squares.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | 8 | class Solution { 9 | public: 10 | /* 如果一个数x可以表示为一个任意数a加上一个平方数bxb,也就是x = a + bxb, 11 | * 那么能组成这个数x最少的平方数个数,就是能组成a最少的平方数个数加上1(因为b*b已经是平方数了)。 12 | */ 13 | int numSquares(int n) { 14 | // 将所有非平方数的结果置最大,保证之后比较的时候不被选中 15 | vector nums(n + 1, INT_MAX); 16 | 17 | // 将所有整平方数的结果置1 18 | for (int i = 0; i*i <= n; ++i) 19 | { 20 | nums[i*i] = 1; 21 | }//for 22 | 23 | // 从小到大找任意数a 24 | for (int a = 0; a <= n; ++a) 25 | { 26 | // 从小到大找平方数b*b 27 | for (int b = 0; a + b*b <= n; ++b) 28 | { 29 | // 因为a+b*b可能本身就是平方数,所以我们要取两个中较小的 30 | nums[a + b*b] = min(nums[a] + 1, nums[a + b*b]); 31 | }//for 32 | }//for 33 | return nums[n]; 34 | } 35 | }; 36 | 37 | int main() 38 | { 39 | Solution s; 40 | cout << s.numSquares(12) << endl; 41 | 42 | cout << s.numSquares(13) << endl; 43 | 44 | system("pause"); 45 | return 0; 46 | } -------------------------------------------------------------------------------- /28. Implement strStr().java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int strStr(String haystack, String needle) { 3 | int hLen = haystack.length(); 4 | int nLen = needle.length(); 5 | 6 | if (nLen == 0) { 7 | return 0; 8 | } 9 | 10 | for (int i = 0; i < hLen; ++i) { 11 | boolean find = true; 12 | 13 | for (int j = 0; j < nLen; ++j) { 14 | if (i + j >= hLen || haystack.charAt(i + j) != needle.charAt(j)) { 15 | find = false; 16 | break; 17 | } 18 | } 19 | 20 | if (find) { 21 | return i; 22 | } 23 | } 24 | 25 | return -1; 26 | } 27 | 28 | public int strStr1(String haystack, String needle) { 29 | return haystack.indexOf(needle); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /283. Move Zeroes.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void moveZeroes1(int[] nums) { 3 | int len = nums.length; 4 | 5 | int lastNonZeroIdx = 0; 6 | for (int i = 0; i < len; ++i) { 7 | if (nums[i] != 0) { 8 | nums[lastNonZeroIdx++] = nums[i]; 9 | } 10 | } 11 | 12 | while (lastNonZeroIdx < len) { 13 | nums[lastNonZeroIdx++] = 0; 14 | } 15 | } 16 | 17 | public void moveZeroes(int[] nums) { 18 | int len = nums.length; 19 | int lastNonZeroIdx = 0; 20 | 21 | for (int i = 0; i < len; ++i) { 22 | if (nums[i] != 0) { 23 | if (lastNonZeroIdx == i) { 24 | ++lastNonZeroIdx; 25 | continue; 26 | } 27 | 28 | int temp = nums[lastNonZeroIdx]; 29 | nums[lastNonZeroIdx++] = nums[i]; 30 | nums[i] = temp; 31 | } 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /283_Move Zeroes/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | void moveZeroes(vector& nums) { 10 | if (nums.empty()) 11 | return; 12 | 13 | int sz = nums.size(); 14 | 15 | int count = 0; 16 | for (int i = 0, k = 0; i < sz; ++i) 17 | { 18 | if (nums[i] != 0) 19 | { 20 | nums[count] = nums[i]; 21 | ++count; 22 | } 23 | continue; 24 | } 25 | while (count < sz){ 26 | nums[count++] = 0; 27 | } 28 | return; 29 | } 30 | }; 31 | 32 | int main() 33 | { 34 | Solution s; 35 | vector v = { 0, 1, 0, 3, 12 }; 36 | s.moveZeroes(v); 37 | 38 | for (unsigned i = 0; i < v.size(); ++i) 39 | { 40 | cout << v[i] << "\t"; 41 | }//for 42 | cout << endl; 43 | 44 | system("pause"); 45 | return 0; 46 | } -------------------------------------------------------------------------------- /287. Find the Duplicate Number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findDuplicate(int[] nums) { 3 | int tortoise = nums[0]; 4 | int hare = nums[0]; 5 | 6 | do { 7 | tortoise = nums[tortoise]; 8 | hare = nums[nums[hare]]; 9 | } while(hare != tortoise); 10 | 11 | tortoise = nums[0]; 12 | while(tortoise != hare) { 13 | tortoise = nums[tortoise]; 14 | hare = nums[hare]; 15 | } 16 | 17 | return hare; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /287_Find The Duplicate Number/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | int findDuplicate(vector& nums) { 10 | if (nums.empty()) 11 | return 0; 12 | //数组中共有n个元素 范围在1-(n-1) 13 | int len = nums.size(); 14 | int min = 0, max = len - 1; 15 | while (min <= max){ 16 | // 找到中间那个数 17 | int mid = min + (max - min) / 2; 18 | int cnt = 0; 19 | // 计算总数组中有多少个数小于等于中间数 20 | for (int i = 0; i < len; i++){ 21 | if (nums[i] <= mid){ 22 | cnt++; 23 | } 24 | } 25 | // 如果小于等于中间数的数量大于中间数,说明前半部分必有重复 26 | if (cnt > mid){ 27 | max = mid - 1; 28 | // 否则后半部分必有重复 29 | } 30 | else { 31 | min = mid + 1; 32 | } 33 | } 34 | return min; 35 | } 36 | }; 37 | 38 | int main() 39 | { 40 | vector v = { 1, 2, 2, 3, 4 }; 41 | Solution s; 42 | cout << s.findDuplicate(v) << endl; 43 | 44 | system("pause"); 45 | return 0; 46 | } -------------------------------------------------------------------------------- /29. Divide Two Integers.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int divide(int dividend, int divisor) { 3 | boolean isNegative = ( dividend > 0 && divisor < 0 ) || ( dividend < 0 && divisor > 0); 4 | 5 | int ret = 0; 6 | 7 | if (divisor == Integer.MIN_VALUE) { 8 | if (dividend == Integer.MIN_VALUE) { 9 | return 1; 10 | } else { 11 | return 0; 12 | } 13 | } 14 | 15 | if (dividend == Integer.MIN_VALUE) { 16 | if (divisor == 1) { 17 | return Integer.MIN_VALUE; 18 | } else if (divisor == -1) { 19 | return Integer.MAX_VALUE; 20 | } else { 21 | ++ret; 22 | dividend += Math.abs(divisor); 23 | } 24 | } 25 | 26 | dividend = Math.abs(dividend); 27 | divisor = Math.abs(divisor); 28 | 29 | while (dividend >= divisor) { 30 | ++ret; 31 | dividend -= divisor; 32 | } 33 | 34 | return isNegative ? -ret : ret; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /292_Nim Game/292_Nim Game.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | bool canWinNim(int n) { 10 | if (n % 4 == 0) 11 | return false; 12 | return true; 13 | } 14 | }; 15 | 16 | int main() 17 | { 18 | Solution s; 19 | cout << s.canWinNim(4) << endl; 20 | 21 | system("pause"); 22 | return 0; 23 | } 24 | 25 | -------------------------------------------------------------------------------- /3. Longest Substring Without Repeating Characters.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun lengthOfLongestSubstring(s: String): Int { 3 | var charMap = mutableMapOf() 4 | var left = 0 5 | var i = 0 6 | var maxLen = 0 7 | 8 | while (i < s.length) { 9 | while (charMap.contains(s[i])) { 10 | maxLen = max(maxLen, i - left) 11 | 12 | charMap.remove(s[left++]) 13 | } 14 | charMap.put(s[i++], 1) 15 | } 16 | 17 | maxLen = max(maxLen, i-left) 18 | 19 | return maxLen 20 | } 21 | } 22 | 23 | -------------------------------------------------------------------------------- /303_Range Sum Query/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class NumArray { 8 | public: 9 | NumArray(vector &nums) { 10 | if (nums.empty()) 11 | return ; 12 | else 13 | { 14 | sums.push_back(nums[0]); 15 | //求得给定数列长度 16 | int len = nums.size(); 17 | for (int i = 1; i < len; ++i) 18 | { 19 | sums.push_back(sums[i - 1] + nums[i]); 20 | }//for 21 | } 22 | } 23 | 24 | //计算[i,j]序列和 25 | int sumRange(int i, int j) { 26 | if (0 == i) 27 | return sums[j]; 28 | int len = sums.size(); 29 | 30 | if (i < 0 || i >= len || j < 0 || j >= len || i > j) 31 | { 32 | return 0; 33 | }//if 34 | return sums[j] - sums[i-1]; 35 | } 36 | 37 | private: 38 | //存储数列和 39 | vector sums; 40 | }; 41 | 42 | 43 | // Your NumArray object will be instantiated and called as such: 44 | // NumArray numArray(nums); 45 | // numArray.sumRange(0, 1); 46 | // numArray.sumRange(1, 2); 47 | 48 | int main() 49 | { 50 | vector nums = { -2, 0, 3, -5, 2, -1 }; 51 | 52 | NumArray na(nums); 53 | cout << na.sumRange(0, 2) << endl; 54 | cout << na.sumRange(2, 5) << endl; 55 | cout << na.sumRange(0, 5) << endl; 56 | 57 | system("pause"); 58 | return 0; 59 | } -------------------------------------------------------------------------------- /326. Power of Three.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfThree(int n) { 4 | return n > 0 && 1162261467 % n == 0; 5 | } 6 | }; -------------------------------------------------------------------------------- /328. Odd Even Linked List.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode oddEvenList(ListNode head) { 13 | if (head == null || head.next == null) { 14 | return head; 15 | } 16 | 17 | ListNode odd = head, even = head.next, evenHead = even; 18 | 19 | while(even != null && even.next != null) { 20 | odd.next = even.next; 21 | odd = odd.next; 22 | 23 | even.next = odd.next; 24 | even = even.next; 25 | } 26 | 27 | odd.next = evenHead; 28 | 29 | return head; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /32_Longest Valid Parentheses/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | int longestValidParentheses(string s) { 11 | if (s.empty()) 12 | return 0; 13 | 14 | //求括号字符串长度 15 | int len = s.length(); 16 | 17 | //定义一个长度vector,i处值计量从i开始的到len-1长度字符串的最长有效匹配括号长度 18 | vector dp(len, 0); 19 | int maxlen = 0; 20 | 21 | for (int i = len - 2; i >= 0; --i) 22 | { 23 | if (s[i] == '(') 24 | { 25 | int j = i + 1 + dp[i + 1]; 26 | if (j < len && s[j] == ')') 27 | { 28 | dp[i] = dp[i + 1] + 2; 29 | if (j + 1 < len) 30 | dp[i] += dp[j + 1]; 31 | } 32 | } 33 | 34 | //实时求最长有效匹配长度 35 | if (dp[i] > maxlen) 36 | maxlen = dp[i]; 37 | }//for 38 | return maxlen; 39 | } 40 | }; 41 | 42 | int main() 43 | { 44 | Solution s; 45 | cout << s.longestValidParentheses(")()())") << endl; 46 | cout << s.longestValidParentheses(")(((((()())()()))()(()))(") << endl; 47 | system("pause"); 48 | 49 | return 0; 50 | } -------------------------------------------------------------------------------- /33. Search in Rotated Sorted Array.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/search-in-rotated-sorted-array/ 3 | * 33. Search in Rotated Sorted Array 4 | */ 5 | public class NO_33 { 6 | Solution solution = new Solution(); 7 | 8 | public static void main(String[] args) { 9 | System.out.println(new NO_33().solution.search(new int[]{4,5,6,7,0,1,2}, 1)); 10 | } 11 | 12 | class Solution { 13 | public int search(int[] nums, int target) { 14 | int left = 0, right = nums.length - 1; 15 | 16 | while (left <= right) { 17 | int mid = left + (right - left) / 2; 18 | 19 | if (nums[mid] == target) { 20 | return mid; 21 | } 22 | 23 | if (nums[left] <= nums[mid]) { 24 | if (nums[left] <= target && target < nums[mid]) { 25 | right = mid - 1; 26 | } else { 27 | left = mid + 1; 28 | } 29 | } else { 30 | if (nums[mid] < target && target <= nums[right]) { 31 | left = mid + 1; 32 | } else { 33 | right = mid - 1; 34 | } 35 | } 36 | } 37 | 38 | return -1; 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /344. Reverse String.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void reverseString(char[] s) { 3 | int left = 0, right = s.length - 1; 4 | while(left < right) { 5 | char tmp = s[left]; 6 | s[left] = s[right]; 7 | s[right] = tmp; 8 | 9 | ++left; 10 | --right; 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /344_Reverse String.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 344. Reverse String 3 | */ 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | 10 | class Solution { 11 | public: 12 | string reverseString(string s) { 13 | if (s.empty()) 14 | return s; 15 | 16 | int l = 0, r = s.size() - 1; 17 | string ret = s; 18 | while (l < r) 19 | { 20 | char t = ret[l]; 21 | ret[l] = ret[r]; 22 | ret[r] = t; 23 | 24 | ++l; 25 | --r; 26 | } 27 | return ret; 28 | } 29 | }; -------------------------------------------------------------------------------- /345. Reverse Vowels of a String.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String reverseVowels(String s) { 3 | Set vowels = new HashSet<>(); 4 | vowels.addAll(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')); 5 | 6 | int left = 0, right = s.length() - 1; 7 | char[] chars = s.toCharArray(); 8 | 9 | while (left < right) { 10 | if (!vowels.contains(chars[left])) { 11 | ++left; 12 | continue; 13 | } 14 | 15 | if (!vowels.contains(chars[right])) { 16 | --right; 17 | continue; 18 | } 19 | 20 | char tmp = chars[left]; 21 | chars[left++] = chars[right]; 22 | chars[right--] = tmp; 23 | } 24 | 25 | return String.valueOf(chars); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /349. Intersection of Two Arrays.cpp: -------------------------------------------------------------------------------- 1 | /*349. Intersection of Two Arrays*/ 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | 10 | class Solution { 11 | public: 12 | vector intersection(vector& nums1, vector& nums2) { 13 | int l1 = nums1.size(), l2 = nums2.size(); 14 | 15 | map m; 16 | set s; 17 | for (int i = 0; i < l1; ++i) 18 | { 19 | ++m[nums1[i]]; 20 | }//for 21 | 22 | vector ret; 23 | for (int i = 0; i < l2; ++i) 24 | { 25 | if (m[nums2[i]] > 0) 26 | s.insert(nums2[i]); 27 | 28 | }//for 29 | 30 | return vector(s.begin(), s.end()); 31 | } 32 | }; 33 | 34 | int main() 35 | { 36 | vector v1 = { 1 }, v2 = { 1}; 37 | 38 | vector ret = Solution().intersection(v1, v2); 39 | 40 | for (auto iter = ret.begin(); iter != ret.end(); ++iter) 41 | cout << *iter << "\t"; 42 | cout << endl; 43 | 44 | system("pause"); 45 | return 0; 46 | } -------------------------------------------------------------------------------- /35. Candy.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int candy(int[] ratings) { 3 | var candies = new int[ratings.length]; 4 | Arrays.fill(candies, 1); 5 | 6 | for (int i = 1; i < ratings.length; ++i) { 7 | if (ratings[i] > ratings[i-1]) { 8 | candies[i] = candies[i-1] + 1; 9 | } 10 | } 11 | 12 | for (int i = ratings.length - 2; i >= 0; --i) { 13 | if (ratings[i] > ratings[i+1]) { 14 | candies[i] = Math.max(candies[i], candies[i+1] + 1); 15 | } 16 | } 17 | 18 | return Arrays.stream(candies).sum(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /35. Search Insert Position.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/search-insert-position/ 3 | * 35. Search Insert Position 4 | */ 5 | public class NO_35 { 6 | Solution solution = new Solution(); 7 | 8 | public static void main(String[] args) { 9 | System.out.println(new NO_35().solution.searchInsert(new int[]{1,3,5,6}, 0)); 10 | } 11 | 12 | class Solution { 13 | public int searchInsert(int[] nums, int target) { 14 | int left = 0, right = nums.length - 1; 15 | 16 | while (left <= right) { 17 | int mid = (right - left) / 2 + left; 18 | 19 | if (nums[mid] == target) { 20 | return mid; 21 | } else if (nums[mid] < target) { 22 | left = mid + 1; 23 | } else { 24 | right = mid - 1; 25 | } 26 | } 27 | 28 | return left; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /350. Intersection of Two Arrays II.cpp: -------------------------------------------------------------------------------- 1 | //350. Intersection of Two Arrays II 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | 10 | class Solution { 11 | public: 12 | vector intersect(vector& nums1, vector& nums2) { 13 | if (nums1.empty() || nums2.empty()) 14 | return vector(); 15 | 16 | int l1 = nums1.size(), l2 = nums2.size(); 17 | map m; 18 | for (int i = 0; i < l1; ++i) 19 | { 20 | ++m[nums1[i]]; 21 | }//for 22 | 23 | vector ret; 24 | for (int i = 0; i < l2; ++i) 25 | { 26 | if (m[nums2[i]] > 0) 27 | { 28 | ret.push_back(nums2[i]); 29 | --m[nums2[i]]; 30 | }//if 31 | }//for 32 | 33 | return ret; 34 | } 35 | }; 36 | 37 | int main() 38 | { 39 | vector v1 = { 1,2,2,1 }, v2 = { 2,2 }; 40 | vector ret = Solution().intersect(v1, v2); 41 | 42 | system("pause"); 43 | return 0; 44 | } -------------------------------------------------------------------------------- /371. Sum of Two Integers.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shineyr/LeetCode/501fbac03deff0ae9c5cbcc0d1e2d444c3779059/371. Sum of Two Integers.cpp -------------------------------------------------------------------------------- /38. Count and Say.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Solution 1 3 | public String countAndSay(int n) { 4 | String[] say = new String[n+1]; 5 | say[1] = "1"; 6 | 7 | for (int i = 2; i < n + 1; ++i) { 8 | say[i] = nextSay(say[i-1]); 9 | } 10 | 11 | return say[n]; 12 | } 13 | 14 | // Solution 2 15 | public String countAndSay1(int n) { 16 | if (n == 1) { 17 | return "1"; 18 | } 19 | 20 | String pre = countAndSay(n - 1); 21 | 22 | return nextSay(pre); 23 | } 24 | 25 | private String nextSay(String pre) { 26 | String ret = ""; 27 | for (int i = 0; i < pre.length(); ) { 28 | char c = pre.charAt(i); 29 | int count = 1; 30 | 31 | int j = i + 1; 32 | while (j < pre.length()) { 33 | if (pre.charAt(j) != c) { 34 | break; 35 | } else { 36 | ++count; 37 | ++j; 38 | } 39 | } 40 | 41 | i = j; 42 | ret = ret + count + c; 43 | } 44 | 45 | return ret; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /380. Insert Delete GetRandom O(1).kt: -------------------------------------------------------------------------------- 1 | import kotlin.random.Random 2 | class RandomizedSet() { 3 | val nums = ArrayList() 4 | val indexMap = mutableMapOf() 5 | 6 | fun insert(value: Int): Boolean { 7 | if (!indexMap.contains(value)) { 8 | nums.add(value) 9 | indexMap.put(value, nums.size - 1) 10 | return true 11 | } 12 | return false 13 | } 14 | 15 | fun remove(`val`: Int): Boolean { 16 | if (!indexMap.contains(`val`)) { 17 | return false 18 | } 19 | 20 | val valIdx = indexMap.get(`val`)!! 21 | nums[valIdx] = nums[nums.size - 1] 22 | indexMap.put(nums[nums.size-1], valIdx) 23 | 24 | indexMap.remove(`val`) 25 | nums.removeAt(nums.size-1) 26 | 27 | return true 28 | } 29 | 30 | fun getRandom(): Int { 31 | val randomIdx = Random.nextInt(0, nums.size) 32 | return nums[randomIdx] 33 | } 34 | 35 | } 36 | 37 | /** 38 | * Your RandomizedSet object will be instantiated and called as such: 39 | * var obj = RandomizedSet() 40 | * var param_1 = obj.insert(`val`) 41 | * var param_2 = obj.remove(`val`) 42 | * var param_3 = obj.getRandom() 43 | */ 44 | -------------------------------------------------------------------------------- /383. Ransom Note.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | bool canConstruct(string ransomNote, string magazine) { 11 | int rL = ransomNote.length(), mL = magazine.length(); 12 | 13 | vector v(256, 0); 14 | for (int i = 0; i < mL; ++i) 15 | { 16 | ++v[magazine[i]]; 17 | }//for 18 | 19 | for (int i = 0; i < rL; ++i) 20 | { 21 | --v[ransomNote[i]]; 22 | 23 | if (v[ransomNote[i]] < 0) 24 | return false; 25 | }//for 26 | 27 | return true; 28 | } 29 | }; 30 | 31 | int main() 32 | { 33 | cout << Solution().canConstruct("a", "b") << endl; 34 | 35 | system("pause"); 36 | 37 | return 0; 38 | } -------------------------------------------------------------------------------- /383. Ransom Note.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun canConstruct(ransomNote: String, magazine: String): Boolean { 3 | var magazineMap = mutableMapOf() 4 | 5 | for (i in 0 until magazine.length) { 6 | magazineMap.put(magazine[i], (magazineMap.get(magazine[i]) ?: 0) + 1) 7 | } 8 | 9 | for (i in 0 until ransomNote.length) { 10 | if ((magazineMap.get(ransomNote[i]) ?: 0) <= 0) { 11 | return false 12 | } else { 13 | magazineMap.put(ransomNote[i], (magazineMap.get(ransomNote[i]) ?: 0) - 1) 14 | } 15 | } 16 | 17 | return true 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /386. Lexicographical Numbers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 386. Lexicographical Numbers 3 | */ 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | using namespace std; 11 | 12 | class Solution { 13 | public: 14 | vector lexicalOrder(int n) { 15 | vector rs; 16 | 17 | int i = 1, j; 18 | int k; 19 | for (;;) 20 | { 21 | // append as many zeroes as possible to the previous number 22 | for (k = 0; i*pow(10, k) <= n; ++k) rs.push_back(i*pow(10, k)); 23 | 24 | // count continuously until we reach a number that ends with consecutive '9's 25 | for (j = rs.back() + 1; j <= n && (j % 10) != 0; ++j) rs.push_back(j); 26 | 27 | // backtrace 28 | if (j % 10 == 0) 29 | { 30 | j--; 31 | } 32 | else 33 | { 34 | j /= 10; 35 | } 36 | 37 | // find the last non-'9' digit 38 | while (j % 10 == 9) j /= 10; 39 | 40 | // start a new sub-sequence 41 | i = j + 1; 42 | 43 | if (rs.size() >= n) break; 44 | } 45 | 46 | return rs; 47 | } 48 | }; 49 | 50 | int main() 51 | { 52 | vector res = Solution().lexicalOrder(120); 53 | 54 | for (auto iter = res.begin(); iter != res.end(); ++iter) 55 | cout << *iter << endl; 56 | 57 | system("pause"); 58 | return 0; 59 | } 60 | 61 | -------------------------------------------------------------------------------- /387. First Unique Character in a String.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shineyr/LeetCode/501fbac03deff0ae9c5cbcc0d1e2d444c3779059/387. First Unique Character in a String.cpp -------------------------------------------------------------------------------- /389. Find the Difference.cpp: -------------------------------------------------------------------------------- 1 | // 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | char findTheDifference(string s, string t) { 12 | int sL = s.length(), tL = t.length(); 13 | 14 | vector v(256, 0); 15 | for (int i = 0; i < sL; ++i) 16 | ++v[s[i]]; 17 | 18 | for (int i = 0; i < tL; ++i) 19 | { 20 | --v[t[i]]; 21 | if (v[t[i]] < 0) 22 | return t[i]; 23 | }//for 24 | return ' '; 25 | } 26 | 27 | }; 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /41. First Missing Positive.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 41. First Missing Positive 3 | * Given an unsorted integer array, find the smallest missing positive integer. 4 | */ 5 | public class NO_41 { 6 | private Solution solution = new Solution(); 7 | 8 | public static void main(String[] args) { 9 | System.out.println(new NO_41().solution.firstMissingPositive(new int[] {1,1})); 10 | } 11 | 12 | class Solution { 13 | public int firstMissingPositive(int[] nums) { 14 | for (int i=0; i nums.length) { 18 | nums[i] = 0; 19 | break; 20 | } 21 | 22 | if (nums[cur - 1] == cur) { 23 | break; 24 | } 25 | 26 | nums[i] = nums[cur - 1]; 27 | nums[cur - 1] = cur; 28 | 29 | } 30 | } 31 | 32 | for (int i=0; i 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | int trap(vector& height) { 11 | if (height.empty()) 12 | return 0; 13 | 14 | int len = height.size(); 15 | 16 | int lhs = 0, rhs = len - 1, secHeight = 0; 17 | 18 | int area = 0; 19 | 20 | //从两边向中间统计,分别统计每个竖立格子可以盛的水量 21 | while (lhs < rhs) 22 | { 23 | if (height[lhs] < height[rhs]) 24 | { 25 | secHeight = max(height[lhs], secHeight); 26 | //加上lhs竖格的盛水量 27 | area += secHeight - height[lhs]; 28 | //左侧右移一格 29 | lhs++; 30 | } 31 | else{ 32 | secHeight = max(height[rhs], secHeight); 33 | //加上rhs竖格的盛水量 34 | area += secHeight - height[rhs]; 35 | //右侧左移一格 36 | rhs--; 37 | }//fi 38 | }//while 39 | 40 | return area; 41 | } 42 | }; 43 | 44 | int main() 45 | { 46 | Solution s; 47 | 48 | vector height = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; 49 | 50 | cout << s.trap(height) << endl; 51 | 52 | system("pause"); 53 | return 0; 54 | } -------------------------------------------------------------------------------- /43. Multiply Strings.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String multiply(String num1, String num2) { 3 | if (num1.isEmpty() || num2.isEmpty()) { 4 | return "0"; 5 | } 6 | 7 | int[] result = new int[num1.length() + num2.length()]; 8 | 9 | int r1Pos = 0, r2Pos = 0; 10 | for (int i = num1.length() - 1; i >= 0; --i) { 11 | r2Pos = 0; 12 | int carry = 0; 13 | 14 | for (int j = num2.length() - 1; j >= 0; --j) { 15 | int product = result[r1Pos + r2Pos] + ((num1.charAt(i) - '0') * (num2.charAt(j) - '0')) + carry; 16 | 17 | result[r1Pos + r2Pos] = product % 10; 18 | carry = product / 10; 19 | ++r2Pos; 20 | } 21 | 22 | if (carry != 0) { 23 | result[r1Pos + r2Pos] += carry; 24 | } 25 | ++r1Pos; 26 | } 27 | 28 | int idx = result.length - 1; 29 | while (idx >= 0 && result[idx] == 0 ) { 30 | --idx; 31 | } 32 | 33 | if (idx == -1) { 34 | return "0"; 35 | } 36 | 37 | StringBuilder strResult = new StringBuilder(); 38 | while (idx >= 0) { 39 | strResult.append(result[idx]); 40 | --idx; 41 | } 42 | 43 | return strResult.toString(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /45. Jump Game II.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | //https://www.youtube.com/watch?v=cfdwhSmLt3w 3 | public int jump(int[] nums) { 4 | int len = nums.length; 5 | 6 | if (len <= 1 || nums[0] == 0) { 7 | return 0; 8 | } 9 | 10 | int minJumps = 1, farthest = nums[0], curEnd = nums[0]; 11 | 12 | for (int i = 1; i < len; ++i) { 13 | if (i == len - 1) { 14 | return minJumps; 15 | } 16 | 17 | farthest = Math.max(farthest, i + nums[i]); 18 | 19 | if (i == curEnd) { 20 | ++minJumps; 21 | curEnd = farthest; 22 | } 23 | } 24 | 25 | return minJumps; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /461. Hamming Distance.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 461. Hamming Distance 3 | * 4 | * The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 5 | * 6 | * Given two integers x and y, calculate the Hamming distance. 7 | */ 8 | public class NO_461 { 9 | private Solution solution = new Solution(); 10 | 11 | public static void main(String[] args) { 12 | System.out.println(new NO_461().solution.hammingDistance(1, 4)); 13 | } 14 | 15 | class Solution { 16 | public int hammingDistance(int x, int y) { 17 | int ret = x ^ y; 18 | 19 | int count = 0; 20 | while (ret != 0) { 21 | if ((ret & 1) != 0) { 22 | ++count; 23 | } 24 | 25 | ret >>= 1; 26 | } 27 | 28 | return count; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /47. Permutations II.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> permuteUnique(int[] nums) { 3 | List> permutations = new ArrayList<>(); 4 | 5 | boolean[] visited = new boolean[nums.length]; 6 | for (int i = 0; i < nums.length; ++i) { 7 | visited[i] = false; 8 | } 9 | 10 | Arrays.sort(nums); 11 | 12 | permuteUnique(permutations, new ArrayList<>(), nums, visited, 0); 13 | 14 | return permutations; 15 | } 16 | 17 | private void permuteUnique(List> permutations, List permutation, int[] nums, boolean[] visited, int count) { 18 | if (count == nums.length) { 19 | permutations.add(new ArrayList<>(permutation)); 20 | } 21 | 22 | for (int i = 0; i < nums.length; ++i) { 23 | if (!visited[i]) { 24 | if (i != 0 && nums[i] == nums[i-1] && !visited[i-1]) { 25 | continue; 26 | } 27 | permutation.add(nums[i]); 28 | visited[i] = true; 29 | 30 | permuteUnique(permutations, permutation, nums, visited, count + 1); 31 | 32 | permutation.remove(permutation.size() - 1); 33 | visited[i] = false; 34 | } 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /48. Rotate Image.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void rotate(int[][] matrix) { 3 | if (matrix.length <= 0) { 4 | return; 5 | } 6 | 7 | int m = matrix.length, n = matrix[0].length; 8 | 9 | // First swap 10 | for (int i = 0; i < m; ++i) { 11 | for (int j = i; j < n; ++j) { 12 | int temp = matrix[i][j]; 13 | matrix[i][j] = matrix[j][i]; 14 | matrix[j][i] = temp; 15 | } 16 | } 17 | 18 | // Second swap 19 | for (int i = 0; i < m; ++i) { 20 | for (int j = 0; j < n/2; ++j) { 21 | int temp = matrix[i][j]; 22 | matrix[i][j] = matrix[i][n - j - 1]; 23 | matrix[i][n - j - 1] = temp; 24 | } 25 | } 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /49. Group Anagrams.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> groupAnagrams(String[] strs) { 3 | Map> groups = new HashMap<>(); 4 | 5 | for (String str : strs) { 6 | char[] chars = str.toCharArray(); 7 | Arrays.sort(chars); 8 | String key = String.valueOf(chars); 9 | 10 | if (!groups.containsKey(key)) { 11 | groups.put(key, new ArrayList<>()); 12 | } 13 | groups.get(key).add(str); 14 | } 15 | 16 | return new ArrayList<>(groups.values()); 17 | } 18 | 19 | 20 | } 21 | -------------------------------------------------------------------------------- /52_N-Queens II/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | private: 10 | int ret = 0; 11 | public: 12 | int totalNQueens(int n) { 13 | if (n <= 0) 14 | return 0; 15 | 16 | //存储安置皇后的当前解(存储N皇后所在的列数,初始化为-1) 17 | vector state(n, -1); 18 | set_queens(state, 0); 19 | return ret; 20 | } 21 | 22 | void set_queens(vector &state, int row) 23 | { 24 | int n = state.size(); 25 | if (row == n) 26 | { 27 | ret++; 28 | return; 29 | } 30 | else{ 31 | for (int col = 0; col < n; col++) 32 | { 33 | if (isValid(state, row, col)) 34 | { 35 | state[row] = col; 36 | set_queens(state, row + 1); 37 | state[row] = -1; 38 | }//if 39 | }//for 40 | } 41 | } 42 | 43 | //判断在row行col列位置放一个皇后,是否是合法的状态 44 | //已经保证了每行一个皇后,只需要判断列是否合法以及对角线是否合法。 45 | bool isValid(vector &state, int row, int col) 46 | { 47 | for (int i = 0; i < row; i++) 48 | { 49 | if (state[i] == col || abs(row - i) == abs(col - state[i])) 50 | return false; 51 | }//for 52 | return true; 53 | } 54 | }; 55 | 56 | int main() 57 | { 58 | Solution s; 59 | int ret = s.totalNQueens(4); 60 | cout << ret << endl; 61 | 62 | system("pause"); 63 | return 0; 64 | } 65 | -------------------------------------------------------------------------------- /53. Maximum Subarray.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * 53. Maximum Subarray 4 | * 5 | * Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. 6 | */ 7 | public class NO_53 { 8 | Solution solution = new Solution(); 9 | 10 | public static void main(String[] args) { 11 | System.out.println(new NO_53().solution.maxSubArray(new int[] {-2,1,-3,4,-1,2,1,-5,4})); 12 | } 13 | 14 | class Solution { 15 | public int maxSubArray(int[] nums) { 16 | 17 | int maxSum = Integer.MIN_VALUE, tempSum = 0; 18 | for (int i=0; i maxSum) { 22 | maxSum = tempSum; 23 | } 24 | 25 | if (tempSum < 0) { 26 | tempSum = 0; 27 | } 28 | } 29 | return maxSum; 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /54. Spiral Matrix.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List spiralOrder(int[][] matrix) { 3 | int rowLen = matrix.length, colLen = rowLen > 0 ? matrix[0].length : 0; 4 | 5 | List res = new ArrayList<>(); 6 | 7 | int r1 = 0, r2 = rowLen - 1, c1 = 0, c2 = colLen - 1; 8 | 9 | while(r1 <= r2 && c1 <= c2) { 10 | for (int c = c1; c <= c2; ++c) { 11 | res.add(matrix[r1][c]); 12 | } 13 | 14 | for (int r = r1 + 1; r <= r2; ++r) { 15 | res.add(matrix[r][c2]); 16 | } 17 | 18 | if (r1 < r2 && c1 < c2) { 19 | for (int c = c2 - 1; c >= c1; --c) { 20 | res.add(matrix[r2][c]); 21 | } 22 | 23 | for (int r = r2 - 1; r > r1; --r) { 24 | res.add(matrix[r][c1]); 25 | } 26 | } 27 | 28 | r1++; 29 | r2--; 30 | c1++; 31 | c2--; 32 | 33 | } 34 | 35 | return res; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /57. Insert Interval.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[][] insert(int[][] intervals, int[] newInterval) { 3 | int len = intervals.length; 4 | if (len == 0) { 5 | return new int[][] {newInterval}; 6 | } 7 | 8 | List ret = new ArrayList<>(); 9 | 10 | // Add current intervals before overlapping 11 | int idx = 0; 12 | while(idx < len && intervals[idx][1] < newInterval[0]) { 13 | ret.add(intervals[idx]); 14 | 15 | ++idx; 16 | } 17 | 18 | // Find new [beg, end] while overlapping 19 | while (idx < len && intervals[idx][0] <= newInterval[1]) { 20 | newInterval[0] = Math.min(intervals[idx][0], newInterval[0]); 21 | newInterval[1] = Math.max(intervals[idx][1], newInterval[1]); 22 | 23 | ++idx; 24 | } 25 | 26 | ret.add(newInterval); 27 | 28 | // Add rest intervals after overlapping 29 | while (idx < len) { 30 | ret.add(intervals[idx]); 31 | 32 | ++idx; 33 | } 34 | 35 | return ret.toArray(new int[ret.size()][2]); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /58. Length of Last Word.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int lengthOfLastWord(String s) { 3 | if (s == null || s == "") { 4 | return 0; 5 | } 6 | 7 | int lastWordLen = 0; 8 | boolean isLastWord = false; 9 | for (int i = s.length() - 1; i >= 0; --i) { 10 | if (s.charAt(i) == ' ' && isLastWord) { 11 | return lastWordLen; 12 | } 13 | 14 | if (s.charAt(i) != ' ') { 15 | ++lastWordLen; 16 | isLastWord = true; 17 | } 18 | } 19 | 20 | return lastWordLen; 21 | } 22 | 23 | public int lengthOfLastWord1(String s) { 24 | if (s == null || s == "") { 25 | return 0; 26 | } 27 | 28 | int idx = s.lastIndexOf(" "); 29 | if (idx < 0) { 30 | return s.length(); 31 | } 32 | 33 | while (idx > 0 && idx == s.length() - 1) { 34 | s = s.substring(0, idx); 35 | idx = s.lastIndexOf(" "); 36 | } 37 | 38 | return (s.substring(idx + 1)).length(); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /58. Length of Last Word.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun lengthOfLastWord(s: String): Int { 3 | var wordList = s.trim().split(' ') 4 | 5 | return wordList.get(wordList.size - 1).length 6 | } 7 | 8 | 9 | fun lengthOfLastWord1(s: String): Int { 10 | var lastWordLen = 0 11 | 12 | for (i in s.length-1 downTo 0) { 13 | if (s[i] == ' ') { 14 | if (lastWordLen == 0) { 15 | continue 16 | } else { 17 | return lastWordLen 18 | } 19 | } else { 20 | ++lastWordLen 21 | } 22 | } 23 | 24 | return lastWordLen 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /6. ZigZag Conversion.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | import java.util.stream.Collectors; 4 | 5 | /** 6 | * https://leetcode.com/problems/zigzag-conversion/ 7 | * 6. ZigZag Conversion 8 | */ 9 | public class NO_6 { 10 | Solution solution = new Solution(); 11 | 12 | public static void main(String[] args) { 13 | System.out.println(new NO_6().solution.convert("AB", 1)); 14 | } 15 | 16 | class Solution { 17 | public String convert(String s, int numRows) { 18 | if (numRows == 1) { 19 | return s; 20 | } 21 | 22 | numRows = Math.min(s.length(), numRows); 23 | List strRows = new ArrayList<>(numRows); 24 | for (int idx = 0; idx < numRows; ++idx) { 25 | strRows.add(new StringBuilder()); 26 | } 27 | 28 | int rowIdx = 0; 29 | boolean goDown = false; 30 | for (char c : s.toCharArray()) { 31 | strRows.get(rowIdx).append(c); 32 | 33 | // Should switch 34 | if (rowIdx == 0 || rowIdx == numRows - 1) { 35 | goDown = !goDown; 36 | } 37 | 38 | rowIdx += goDown ? 1 : -1; 39 | } 40 | 41 | return String.join("", strRows); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /6. Zigzag Conversion.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun convert(s: String, numRows: Int): String { 3 | var result = Array(numRows, {i -> ""}) 4 | 5 | var i = 0 6 | while (i < s.length) { 7 | // fill the first column 8 | for (row in 0 .. numRows - 1) { 9 | if (i < s.length) { 10 | result[row] = result[row].plus(s[i++]) 11 | } else { 12 | break 13 | } 14 | } 15 | 16 | // handle the rest numRows - 2 columns 17 | for (row in numRows - 2 downTo 1) { 18 | if (i < s.length) { 19 | result[row] = result[row].plus(s[i++]) 20 | } else { 21 | break 22 | } 23 | } 24 | } 25 | 26 | return result.joinToString("") 27 | } 28 | } 29 | 30 | // rows - 2, .. 1 31 | // 0: P 32 | // 1: A 33 | // 2: Y 34 | // 3: P 35 | 36 | 37 | -------------------------------------------------------------------------------- /62. Unique Paths.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 62. Unique Paths 3 | * 4 | * A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). 5 | * 6 | * 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). 7 | * 8 | * How many possible unique paths are there? 9 | */ 10 | public class NO_62 { 11 | private Solution solution = new Solution(); 12 | 13 | public static void main(String[] args) { 14 | System.out.println(new NO_62().solution.uniquePaths(7, 3)); 15 | } 16 | 17 | class Solution { 18 | public int uniquePaths(int m, int n) { 19 | int[][] dp = new int[m][n]; 20 | dp[0][0] = 1; 21 | 22 | for(int i=0; i 0 ? obstacleGrid[0].length : 0; 4 | if (m <= 0 || n <= 0) { 5 | return 0; 6 | } 7 | 8 | int[][] uniquePaths = new int[m][n]; 9 | uniquePaths[0][0] = obstacleGrid[0][0] == 1 ? 0 : 1; 10 | 11 | for (int i = 1; i < m; ++i) { 12 | uniquePaths[i][0] = obstacleGrid[i][0] == 0 ? uniquePaths[i-1][0] : 0; 13 | } 14 | 15 | for (int j = 1; j < n; ++j) { 16 | uniquePaths[0][j] = obstacleGrid[0][j] == 0 ? uniquePaths[0][j-1] : 0; 17 | } 18 | 19 | for (int i = 1; i < m; ++i) { 20 | for (int j = 1; j < n; ++j) { 21 | if (obstacleGrid[i][j] == 0) { 22 | uniquePaths[i][j] = uniquePaths[i][j-1] + uniquePaths[i-1][j]; 23 | } else { 24 | uniquePaths[i][j] = 0; 25 | } 26 | 27 | } 28 | } 29 | 30 | return uniquePaths[m-1][n-1]; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /64. Minimum Path Sum.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 64. Minimum Path Sum 3 | * Given a m x n grid filled with non-negative numbers, 4 | * find a path from top left to bottom right which minimizes the sum of all numbers along its path. 5 | */ 6 | public class NO_64 { 7 | private Solution solution = new Solution(); 8 | 9 | public static void main(String[] args) { 10 | System.out.println(new NO_64().solution.minPathSum(new int[][]{{1,3,1},{1,5,1},{4,2,1}})); 11 | } 12 | 13 | class Solution { 14 | public int minPathSum(int[][] grid) { 15 | if (grid.length <= 0) { 16 | return 0; 17 | } 18 | 19 | int m = grid.length, n = grid[0].length; 20 | 21 | int[][] minPath = new int[m][n]; 22 | minPath[0][0] = grid[0][0]; 23 | 24 | for (int i=0; i 0 && j == 0) { 27 | minPath[i][j] = minPath[i-1][j] + grid[i][j]; 28 | } else if (i ==0 && j > 0) { 29 | minPath[i][j] = minPath[i][j-1] + grid[i][j]; 30 | } else if (i > 0 && j > 0) { 31 | minPath[i][j] = Math.min(minPath[i-1][j], minPath[i][j-1]) + grid[i][j]; 32 | } 33 | } 34 | } 35 | 36 | return minPath[m-1][n-1]; 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /66. Plus One.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/plus-one/ 3 | * 66. Plus One 4 | */ 5 | 6 | import java.util.Arrays; 7 | 8 | public class NO_66 { 9 | Solution solution = new Solution(); 10 | 11 | public static void main(String[] args) { 12 | System.out.println(Arrays.toString(new NO_66().solution.plusOne(new int[] {9, 9, 9}))); 13 | } 14 | 15 | class Solution { 16 | public int[] plusOne(int[] digits) { 17 | int carry = 1; 18 | for (int i = digits.length - 1; i >= 0; --i) { 19 | int tmp = digits[i] + carry; 20 | 21 | if (tmp >= 10) { 22 | digits[i] = tmp % 10; 23 | carry = tmp / 10; 24 | } else { 25 | digits[i] = tmp; 26 | carry = 0; 27 | break; 28 | } 29 | } 30 | 31 | if (carry != 0) { 32 | int[] ret = new int[digits.length + 1]; 33 | ret[0] = carry; 34 | 35 | System.arraycopy(digits, 0, ret, 1, digits.length); 36 | return ret; 37 | } 38 | 39 | return digits; 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /67. Add Binary.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String addBinary(String a, String b) { 3 | if (a == null || a.isEmpty()) { 4 | return b; 5 | } 6 | 7 | if (b == null || b.isEmpty()) { 8 | return a; 9 | } 10 | 11 | int aIdx = a.length() - 1, bIdx = b.length() - 1; 12 | 13 | StringBuilder sum = new StringBuilder(); 14 | int carry = 0; 15 | while (aIdx >= 0 || bIdx >= 0) { 16 | int unitSum; 17 | 18 | if (aIdx >= 0 && bIdx >= 0) { 19 | unitSum = (a.charAt(aIdx) - '0') + (b.charAt(bIdx) - '0') + carry; 20 | --aIdx; 21 | --bIdx; 22 | } else if (aIdx >= 0) { 23 | unitSum = (a.charAt(aIdx) - '0') + carry; 24 | --aIdx; 25 | } else if (bIdx >= 0) { 26 | unitSum = (b.charAt(bIdx) - '0') + carry; 27 | --bIdx; 28 | } else { 29 | break; 30 | } 31 | 32 | if (unitSum >= 2) { 33 | unitSum -= 2; 34 | carry = 1; 35 | } else { 36 | carry = 0; 37 | } 38 | 39 | sum.append(unitSum); 40 | } 41 | 42 | if (carry == 1) { 43 | sum.append('1'); 44 | } 45 | 46 | return sum.reverse().toString(); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /69. Sqrt(x).java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int mySqrt(int x) { 3 | if (x < 2) { 4 | return x; 5 | } 6 | long low = 1, high = x / 2; 7 | 8 | while (low <= high) { 9 | long mid = low + (high - low) / 2; 10 | if (mid * mid == x) { 11 | return (int) mid; 12 | } else if (mid * mid < x) { 13 | low = mid + 1; 14 | } else { 15 | high = mid - 1; 16 | } 17 | } 18 | 19 | return (int) (low - 1); 20 | } 21 | 22 | public int mySqrt1(int x) { 23 | return (int) Math.sqrt(x); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /69_Sqrt(x)/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int mySqrt(int x) { 9 | if (x < 0) 10 | return -1; 11 | 12 | //使用二分法求解 13 | unsigned long long lhs = 0, rhs = (x + 1) / 2; 14 | 15 | while (lhs <= rhs) 16 | { 17 | unsigned long long mid = (lhs + rhs) / 2; 18 | //注意溢出问题,使用无符号长整型存储临时乘积 19 | unsigned long long tmp1 = mid * mid; 20 | if (tmp1 == x) 21 | { 22 | return mid; 23 | } 24 | else if (tmp1 < x) 25 | { 26 | lhs = mid + 1; 27 | } 28 | else{ 29 | rhs = mid - 1; 30 | }//else 31 | }//while 32 | 33 | unsigned long long tmp = lhs * lhs; 34 | if (tmp <= x) 35 | return lhs; 36 | else 37 | return rhs; 38 | } 39 | 40 | //牛顿迭代法 41 | int mySqrt2(int x) 42 | { 43 | if (x < 0) 44 | return -1; 45 | 46 | double pre, cur = 1; 47 | do 48 | { 49 | pre = cur; 50 | cur = x / (2 * pre) + pre / 2.0; 51 | } while (abs(cur - pre) > 0.00001); 52 | 53 | return (int)cur; 54 | } 55 | }; 56 | 57 | 58 | int main() 59 | { 60 | Solution s; 61 | cout << s.mySqrt(3) << endl; 62 | cout << s.mySqrt(10) << endl; 63 | system("pause"); 64 | return 0; 65 | } -------------------------------------------------------------------------------- /7. Reverse Integer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/reverse-integer/ 3 | * 7. Reverse Integer 4 | */ 5 | public class NO_7 { 6 | Solution solution = new Solution(); 7 | public static void main(String[] args) { 8 | System.out.println(new NO_7().solution.reverse(1534236469)); 9 | } 10 | 11 | class Solution { 12 | public int reverse(int x) { 13 | int ret = 0; 14 | while(x != 0) { 15 | int digit = x % 10; 16 | x /= 10; 17 | 18 | // Check overflow 19 | if (ret > Integer.MAX_VALUE / 10 || ret < Integer.MIN_VALUE) { 20 | return 0; 21 | } 22 | 23 | ret = ret * 10 + digit; 24 | } 25 | return ret; 26 | } 27 | 28 | public int reverse2(int x) { 29 | 30 | String values = String.valueOf(Math.abs(x)); 31 | String reverseValues = new StringBuilder(values).reverse().toString(); 32 | 33 | try { 34 | return x < 0 ? Integer.parseInt(reverseValues) * -1 : Integer.parseInt(reverseValues); 35 | } catch (NumberFormatException e) { 36 | return 0; 37 | } 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /70. Climbing Stairs.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 70. Climbing Stairs 3 | * You are climbing a stair case. It takes n steps to reach to the top. 4 | * 5 | * Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 6 | * 7 | * Note: Given n will be a positive integer. 8 | */ 9 | public class NO_70 { 10 | private Solution solution = new Solution(); 11 | 12 | public static void main(String[] args) { 13 | System.out.println(new NO_70().solution.climbStairs(3)); 14 | } 15 | 16 | class Solution { 17 | public int climbStairs(int n) { 18 | if (n == 0) { 19 | return 1; 20 | } 21 | 22 | if (n == 1) { 23 | return 1; 24 | } 25 | 26 | int[] dp = new int[n+1]; 27 | dp[0] = 1; 28 | dp[1] = 1; 29 | 30 | for (int i=2; i<=n; ++i) { 31 | dp[i] = dp[i-1] + dp[i-2]; 32 | } 33 | 34 | return dp[n]; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /71_Simplify Path/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | string simplifyPath(string path) { 11 | if (path.empty()) 12 | return string(); 13 | 14 | stack st; 15 | int len = path.length(); 16 | 17 | for (int i = 0; i < len;) 18 | { 19 | //跳过/ 20 | while (i < len && path[i] == '/') 21 | i++; 22 | //找到以/分隔的目录名 23 | string s = ""; 24 | while ( i < len && path[i] != '/') 25 | { 26 | s += path[i]; 27 | i++; 28 | } 29 | 30 | //如果为..则需要弹栈 31 | if (s == ".." && !st.empty()) 32 | st.pop(); 33 | //如果既不是. 也不是.. 则需要入栈 34 | else if (s != "" && s != "." && s != "..") 35 | st.push(s); 36 | 37 | } 38 | //如果栈空,则为根目录 39 | if (st.empty()) 40 | { 41 | return "/"; 42 | } 43 | 44 | //否则链接各级目录并返回 45 | string ret; 46 | while (!st.empty()) 47 | { 48 | ret = '/' + st.top() + ret; 49 | st.pop(); 50 | } 51 | 52 | return ret; 53 | } 54 | 55 | }; 56 | 57 | int main() 58 | { 59 | Solution s; 60 | 61 | string path = "/a/./b/../../c/"; 62 | 63 | cout << s.simplifyPath(path) << endl; 64 | 65 | system("pause"); 66 | return 0; 67 | } -------------------------------------------------------------------------------- /72_Edit Distance/72_Edit Distance.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | //编辑距离问题属于动态规划 10 | class Solution { 11 | public: 12 | int minDistance(string word1, string word2) { 13 | //若其中一个字符串为空,则最短编辑距离为另一字符串的长度 14 | if (word1.empty()) 15 | return word2.size(); 16 | else if (word2.empty()) 17 | return word1.size(); 18 | 19 | //注意下标处理 20 | int m = word1.size() + 1, n = word2.size() + 1; 21 | 22 | //记录编辑距离的二维数组 23 | vector > distance(m, vector(n, 0)); 24 | for (int i = 0; i < m; i++) 25 | distance[i][0] = i; 26 | for (int j = 0; j < n; j++) 27 | distance[0][j] = j; 28 | 29 | for (int i = 1; i < m; i++) 30 | { 31 | for (int j = 1; j < n; j++) 32 | { 33 | if (word1[i-1] == word2[j-1]) 34 | distance[i][j] = distance[i - 1][j - 1]; 35 | else 36 | distance[i][j] = distance[i - 1][j - 1] + 1; 37 | 38 | distance[i][j] = min(distance[i][j], min(distance[i - 1][j] + 1, distance[i][j - 1] + 1)); 39 | }//for 40 | }//for 41 | return distance[m - 1][n - 1]; 42 | } 43 | }; 44 | 45 | int main() 46 | { 47 | Solution s; 48 | cout << s.minDistance("eeba", "abca") << endl; 49 | 50 | system("pause"); 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /739. Daily Temperatures.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * 739. Daily Temperatures 5 | * Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. 6 | * If there is no future day for which this is possible, put 0 instead. 7 | * 8 | * For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0]. 9 | */ 10 | public class NO_739 { 11 | private Solution solution = new Solution(); 12 | 13 | public static void main(String[] args) { 14 | System.out.println(Arrays.toString(new NO_739().solution.dailyTemperatures(new int[]{73, 74, 75, 71, 69, 72, 76, 73}))); 15 | } 16 | 17 | class Solution { 18 | public int[] dailyTemperatures(int[] T) { 19 | int[] nextWarmers = new int[T.length]; 20 | Arrays.fill(nextWarmers, 0); 21 | 22 | for (int i=0; i T[i]) { 25 | nextWarmers[i] = j - i; 26 | break; 27 | } 28 | } 29 | } 30 | 31 | return nextWarmers; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /75_Sort Colors/75_Sort Colors.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | void sortColors(vector& nums) { 10 | if (nums.empty()) 11 | return; 12 | 13 | //初始化一个count数组,count[0] , count[1] , count[2] 分别记录nums中0 , 1 , 2出现个数 14 | vector count(3, 0); 15 | 16 | vector::iterator iter = nums.begin(); 17 | 18 | for (; iter != nums.end(); iter++) 19 | { 20 | if (*iter == 0) 21 | count[0]++; 22 | else if (*iter == 1) 23 | count[1]++; 24 | else if (*iter == 2) 25 | count[2]++; 26 | }//for 27 | 28 | //对原数组排序 29 | int i = 0; 30 | while (i < count[0]) 31 | nums[i++] = 0; 32 | while (i < (count[0] + count[1])) 33 | nums[i++] = 1; 34 | while (i < (count[0] + count[1] + count[2])) 35 | nums[i++] = 2; 36 | 37 | return; 38 | 39 | } 40 | }; 41 | 42 | int main() 43 | { 44 | Solution s; 45 | vector v = { 0, 1, 1, 1, 2, 2, 2, 0, 0, 0, 1 }; 46 | 47 | for (int i = 0; i < v.size(); i++) 48 | cout << v[i] << "\t"; 49 | cout << endl; 50 | 51 | s.sortColors(v); 52 | 53 | for (int i = 0; i < v.size(); i++) 54 | cout << v[i] << "\t"; 55 | cout << endl; 56 | 57 | system("pause"); 58 | return 0; 59 | } -------------------------------------------------------------------------------- /76_Minimum Window Substring/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | string minWindow(string S, string T) { 11 | if (S.empty() || T.empty()) 12 | { 13 | return ""; 14 | } 15 | int count = T.size(); 16 | int require[128] = { 0 }; 17 | bool chSet[128] = { false }; 18 | for (int i = 0; i < count; ++i) 19 | { 20 | require[T[i]]++; 21 | chSet[T[i]] = true; 22 | } 23 | int i = -1; 24 | int j = 0; 25 | int minLen = INT_MAX; 26 | int minIdx = 0; 27 | while (i < (int)S.size() && j < (int)S.size()) 28 | { 29 | if (count) 30 | { 31 | i++; 32 | require[S[i]]--; 33 | if (chSet[S[i]] && require[S[i]] >= 0) 34 | { 35 | count--; 36 | } 37 | }//if 38 | else 39 | { 40 | if (minLen > i - j + 1) 41 | { 42 | minLen = i - j + 1; 43 | minIdx = j; 44 | } 45 | require[S[j]]++; 46 | if (chSet[S[j]] && require[S[j]] > 0) 47 | { 48 | count++; 49 | } 50 | j++; 51 | }//else 52 | }//while 53 | if (minLen == INT_MAX) 54 | { 55 | return ""; 56 | } 57 | return S.substr(minIdx, minLen); 58 | } 59 | }; 60 | 61 | int main() 62 | { 63 | Solution so; 64 | string s = "ADOBECODEBANC", t = "ABC"; 65 | cout << so.minWindow(s, t) << endl; 66 | 67 | system("pause"); 68 | return 0; 69 | } -------------------------------------------------------------------------------- /77. Combinations.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> combine(int n, int k) { 3 | List> combinations = new ArrayList<>(); 4 | 5 | combine(combinations, new ArrayList<>(), n, k, 1); 6 | 7 | return combinations; 8 | } 9 | 10 | private void combine(List> combinations, List combination, int n, int k, int idx) { 11 | if (combination.size() == k) { 12 | combinations.add(new ArrayList<>(combination)); 13 | return; 14 | } 15 | 16 | for (int i = idx; i <= n; ++i) { 17 | 18 | combination.add(i); 19 | 20 | combine(combinations, combination, n, k, i + 1); 21 | 22 | combination.remove(combination.size() - 1); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /78. Subsets.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | /** 5 | * 78. Subsets 6 | * 7 | * Given a set of distinct integers, nums, return all possible subsets (the power set). 8 | * 9 | * Note: The solution set must not contain duplicate subsets. 10 | */ 11 | public class NO_78 { 12 | private Solution solution = new Solution(); 13 | 14 | public static void main(String[] args) { 15 | System.out.println(new NO_78().solution.subsets(new int[] {1,2,3})); 16 | } 17 | 18 | class Solution { 19 | public List> subsets(int[] nums) { 20 | List> res = new ArrayList<>(); 21 | 22 | dfs(res, new ArrayList<>(), 0, nums); 23 | 24 | return res; 25 | } 26 | 27 | private void dfs(List> res, List subnet, int idx, int[] nums) { 28 | res.add(subnet); 29 | 30 | for (int j = idx; j < nums.length; ++j) { 31 | List newSubnet = new ArrayList<>(subnet); 32 | newSubnet.add(nums[j]); 33 | 34 | dfs(res, newSubnet, j+1, nums); 35 | } 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /79. Word Search.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean exist(char[][] board, String word) { 3 | 4 | // Use each point as a beginning, see whether it can finish the tracking. 5 | for (int i = 0; i < board.length; ++i) { 6 | for (int j = 0; j < board[0].length; ++j) { 7 | if (backTracking(board, i, j, word, 0)) { 8 | return true; 9 | } 10 | } 11 | } 12 | 13 | return false; 14 | } 15 | 16 | private boolean backTracking(char[][] board, int x, int y, String word, int idx) { 17 | if (x < 0 || x == board.length || y < 0 || y >= board[0].length || board[x][y] == '-' || board[x][y] != word.charAt(idx)) { 18 | return false; 19 | } 20 | 21 | if (idx == word.length() - 1) { 22 | return true; 23 | } 24 | 25 | char curVal = board[x][y]; 26 | board[x][y] = '-'; 27 | 28 | boolean goUp = backTracking(board, x, y-1, word, idx + 1); 29 | boolean goDown = backTracking(board, x, y+1, word, idx + 1); 30 | boolean goLeft = backTracking(board, x-1, y, word, idx + 1); 31 | boolean goRight = backTracking(board, x+1, y, word, idx + 1); 32 | 33 | if (goUp || goDown || goLeft || goRight) { 34 | return true; 35 | } else { 36 | board[x][y] = curVal; 37 | return false; 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /80. Remove Duplicates from Sorted Array II.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ 3 | * 80. Remove Duplicates from Sorted Array II 4 | */ 5 | public class NO_80 { 6 | Solution solution = new Solution(); 7 | 8 | public static void main(String[] args) { 9 | System.out.println(new NO_80().solution.removeDuplicates(new int[] {0,0,1,1,1,1,2,3,3})); 10 | } 11 | 12 | class Solution { 13 | public int removeDuplicates(int[] nums) { 14 | int idx = 0, dup = 0; 15 | 16 | for(int i=0; i 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | int removeDuplicates(vector& nums) { 10 | if (nums.empty()) 11 | return 0; 12 | 13 | int len = nums.size(); 14 | if (len <= 2) 15 | return len; 16 | 17 | vector ret; 18 | for (int i = 0; i < len; i++) 19 | { 20 | int temp = nums[i]; 21 | int count = 1; 22 | while (i < (len-1) &&nums[i + 1] == temp) 23 | { 24 | i++; 25 | count++; 26 | } 27 | if (count >= 2) 28 | { 29 | ret.push_back(nums[i]); 30 | ret.push_back(nums[i]); 31 | } 32 | else if (count == 1) 33 | ret.push_back(nums[i]); 34 | }//for 35 | 36 | nums.clear(); 37 | nums = ret; 38 | 39 | return ret.size(); 40 | } 41 | }; 42 | 43 | int main() 44 | { 45 | Solution s; 46 | vector v = { 1, 1, 1, 2, 2, 3 }; 47 | 48 | cout << s.removeDuplicates(v) << endl; 49 | 50 | system("pause"); 51 | return 0; 52 | } -------------------------------------------------------------------------------- /81_Search in Rotated Array II/81_main.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool search(vector& nums, int target) { 4 | if (nums.empty()) 5 | return false; 6 | 7 | //求所给序列的长度 8 | int len = nums.size(); 9 | 10 | int lhs = 0, rhs = len - 1; 11 | while (lhs <= rhs) 12 | { 13 | //右移一位减半,提升效能 14 | int mid = (lhs + rhs) >> 1; 15 | if (target == nums[mid]) 16 | return true; 17 | 18 | //若左侧、中间、右侧值相等 则左右同时内移一位 19 | if (nums[lhs] == nums[mid] && nums[mid] == nums[rhs]) 20 | { 21 | lhs++; 22 | rhs--; 23 | }//if 24 | else if (nums[lhs] <= nums[mid]) 25 | { 26 | if (nums[lhs] <= target && target < nums[mid]) 27 | { 28 | rhs = mid - 1; 29 | } 30 | else{ 31 | lhs = mid + 1; 32 | }//else 33 | }//elif 34 | else{ 35 | if (nums[mid] < target && target <= nums[rhs]) 36 | { 37 | lhs = mid + 1; 38 | }//if 39 | else{ 40 | rhs = mid - 1; 41 | }//else 42 | }//else 43 | }//while 44 | return false; 45 | } 46 | }; -------------------------------------------------------------------------------- /82. Remove Duplicates from Sorted List II.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode deleteDuplicates(ListNode head) { 13 | if (head == null || head.next == null) { 14 | return head; 15 | } 16 | 17 | ListNode preHead = new ListNode(0, head); 18 | 19 | ListNode pre = preHead, p = head; 20 | 21 | while (p != null) { 22 | if (p.next == null) { 23 | break; 24 | } else if (p.next != null && p.next.val != p.val) { 25 | pre = p; 26 | p = p.next; 27 | } else { 28 | int curVal = p.val; 29 | 30 | while(p != null && p.val == curVal) { 31 | p = p.next; 32 | } 33 | 34 | pre.next = p; 35 | } 36 | } 37 | 38 | return preHead.next; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /83. Remove Duplicates from Sorted List.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode deleteDuplicates(ListNode head) { 13 | if (head == null || head.next == null) { 14 | return head; 15 | } 16 | 17 | ListNode p = head, q = head.next; 18 | 19 | while(q != null) { 20 | if (q.val != p.val) { 21 | p.next = q; 22 | p = q; 23 | } 24 | q = q.next; 25 | } 26 | 27 | p.next = q; 28 | 29 | return head; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /85_Maximal Rectangle.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shineyr/LeetCode/501fbac03deff0ae9c5cbcc0d1e2d444c3779059/85_Maximal Rectangle.cpp -------------------------------------------------------------------------------- /86. Partition List.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode partition(ListNode head, int x) { 13 | if (head == null || head.next == null) { 14 | return head; 15 | } 16 | 17 | ListNode preHead = new ListNode(0, head); 18 | 19 | ListNode pre = preHead, p = head; 20 | 21 | while(p != null) { 22 | if (p.val < x) { 23 | pre = p; 24 | p = p.next; 25 | continue; 26 | } 27 | 28 | ListNode q = p, r = p.next; 29 | while (r != null && r.val >= x) { 30 | q = q.next; 31 | r = r.next; 32 | } 33 | 34 | // Find the one which is less than x 35 | if (r == null) { 36 | break; 37 | } 38 | 39 | q.next = r.next; 40 | r.next = p; 41 | pre.next = r; 42 | 43 | 44 | pre = r; 45 | } 46 | 47 | return preHead.next; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /87. Scramble String.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shineyr/LeetCode/501fbac03deff0ae9c5cbcc0d1e2d444c3779059/87. Scramble String.cpp -------------------------------------------------------------------------------- /87_Gray Code/87_Gray Code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | vector grayCode(int n) { 10 | //n位构成的二进制序列值为0~2^n-1 11 | 12 | if (n == 0) 13 | return vector(1,0); 14 | //1左移n位 得到2^n 15 | int size = 1 << n; 16 | 17 | vector ret; 18 | 19 | for (int i = 0; i < size; i++) 20 | { 21 | ret.push_back(i ^ (i >> 1)); 22 | } 23 | 24 | return ret; 25 | } 26 | }; 27 | 28 | int main() 29 | { 30 | Solution s; 31 | vector v = s.grayCode(0); 32 | 33 | typedef vector::iterator iter; 34 | 35 | for (iter i = v.begin(); i != v.end(); i++) 36 | cout << *i << endl; 37 | 38 | system("pause"); 39 | return 0; 40 | } -------------------------------------------------------------------------------- /88. Merge Sorted Array.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/merge-sorted-array/ 3 | * 88. Merge Sorted Array 4 | */ 5 | 6 | import java.util.Arrays; 7 | 8 | public class NO_88 { 9 | Solution solution = new Solution(); 10 | 11 | public static void main(String args[]) { 12 | int[] nums1 = new int[] {1,2,3,0,0,0}; 13 | int[] nums2 = new int[] {2,5,6}; 14 | 15 | new NO_88().solution.merge(nums1, 3, nums2, 3); 16 | 17 | System.out.println(Arrays.toString(nums1)); 18 | } 19 | class Solution { 20 | public void merge(int[] nums1, int m, int[] nums2, int n) { 21 | 22 | int i = m - 1, j = n - 1, k = m + n - 1; 23 | 24 | while (i >= 0 && j >= 0) { 25 | if (nums1[i] > nums2[j]) { 26 | nums1[k--] = nums1[i--]; 27 | } else { 28 | nums1[k--] = nums2[j--]; 29 | } 30 | } 31 | 32 | while (i >= 0) { 33 | nums1[k--] = nums1[i--]; 34 | } 35 | 36 | while (j >= 0) { 37 | nums1[k--] = nums2[j--]; 38 | } 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /9. Palindrome Number V2: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int reverse(int x) { 3 | int reverse = 0; 4 | 5 | while (x != 0) { 6 | int remainder = x % 10; 7 | 8 | // judge the edge case 9 | if (reverse > Integer.MAX_VALUE / 10 || (reverse == Integer.MAX_VALUE / 10 && remainder > 7)) { 10 | return 0; 11 | } 12 | 13 | if (reverse < Integer.MIN_VALUE / 10 || reverse == Integer.MIN_VALUE / 10 && remainder < -8) { 14 | return 0; 15 | } 16 | 17 | reverse *= 10; 18 | 19 | reverse += remainder; 20 | 21 | x /= 10; 22 | } 23 | 24 | return reverse; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /90. Subsets II.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/subsets-ii/ 3 | * 90. Subsets II 4 | */ 5 | 6 | import java.util.ArrayList; 7 | import java.util.Arrays; 8 | import java.util.Collections; 9 | import java.util.List; 10 | 11 | public class NO_90 { 12 | Solution solution = new Solution(); 13 | 14 | public static void main(String[] args) { 15 | System.out.println(new NO_90().solution.subsetsWithDup(new int[]{1,2,2})); 16 | } 17 | 18 | class Solution { 19 | public List> subsetsWithDup(int[] nums) { 20 | if (nums.length < 1) { 21 | return Collections.emptyList(); 22 | } 23 | 24 | Arrays.sort(nums); 25 | List> result = new ArrayList<>(); 26 | 27 | dfs(result, new ArrayList<>(), nums, 0); 28 | 29 | return result; 30 | } 31 | 32 | public void dfs(List> res, List subset, int[] nums, int idx) { 33 | if (!res.contains(subset)) { 34 | res.add(subset); 35 | } 36 | 37 | for (int j = idx; j < nums.length; ++j) { 38 | List nextSubset = new ArrayList<>(subset); 39 | nextSubset.add(nums[j]); 40 | 41 | dfs(res, nextSubset, nums, j + 1); 42 | } 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /90_Subsets II/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | vector> subsetsWithDup(vector& nums) { 11 | vector > ret(1, vector()); 12 | 13 | if (nums.empty()) 14 | return ret; 15 | 16 | sort(nums.begin(), nums.end()); 17 | 18 | int size = nums.size(); 19 | for (int i = 0; i < size; ++i) 20 | { 21 | ret = subSets(ret, nums, i); 22 | } 23 | return ret; 24 | } 25 | 26 | vector > subSets(vector > &ret, vector &nums, int &idx) 27 | { 28 | vector tmp; 29 | int count = ret.size(); 30 | 31 | //对于每一个已有子集合,加入新元素 32 | for (int i = 0; i < count; ++i) 33 | { 34 | //当前集合 35 | tmp = ret[i]; 36 | //加入第idx个元素 37 | tmp.push_back(nums[idx]); 38 | //判重 39 | if (find(ret.begin(), ret.end(), tmp) != ret.end()) 40 | continue; 41 | ret.push_back(tmp); 42 | }//for 43 | 44 | return ret; 45 | } 46 | }; 47 | 48 | int main() 49 | { 50 | Solution s; 51 | vector nums = { 1, 2, 2 }; 52 | vector > ret = s.subsetsWithDup(nums); 53 | 54 | for (size_t i = 0; i < ret.size(); ++i) 55 | { 56 | cout << "["; 57 | for (size_t j = 0; j < ret[i].size(); ++j) 58 | { 59 | cout << " " << ret[i][j]; 60 | } 61 | cout << "]" << endl; 62 | }//for 63 | 64 | system("pause"); 65 | return 0; 66 | } -------------------------------------------------------------------------------- /91. Decode Ways.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numDecodings(String s) { 3 | int len = s.length(); 4 | if (len <= 0) { 5 | return 0; 6 | } 7 | 8 | int[] dp = new int[len + 1]; 9 | dp[0] = 1; 10 | dp[1] = s.charAt(0) == '0' ? 0 : 1; 11 | 12 | for (int i = 2; i <= len; ++i) { 13 | int oneDigitVal = Integer.valueOf(s.substring(i-1, i)); 14 | if (oneDigitVal > 0 && oneDigitVal <= 9) { 15 | dp[i] += dp[i-1]; 16 | } 17 | 18 | int twoDigitVal = Integer.valueOf(s.substring(i-2, i)); 19 | if (twoDigitVal >= 10 && twoDigitVal <= 26) { 20 | dp[i] += dp[i-2]; 21 | } 22 | } 23 | 24 | return dp[len]; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /92. Reverse Linked List II.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode reverseBetween(ListNode head, int m, int n) { 13 | if (head == null || head.next == null || m >= n) { 14 | return head; 15 | } 16 | 17 | ListNode root = new ListNode(0), preHead = root; 18 | root.next = head; 19 | 20 | ListNode pre = root, p = head, next = null, tail = null; 21 | 22 | int idx = 1; 23 | while(p != null && idx < m) { 24 | preHead = p; 25 | p = p.next; 26 | ++idx; 27 | } 28 | 29 | if (p == null || idx != m) { 30 | return head; 31 | } 32 | 33 | tail = p; 34 | pre = p; 35 | p = p.next; 36 | ++idx; 37 | 38 | while(p != null && idx <= n) { 39 | next = p.next; 40 | p.next = pre; 41 | pre = p; 42 | p = next; 43 | ++idx; 44 | } 45 | 46 | tail.next = next; 47 | preHead.next = pre; 48 | 49 | return root.next; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /93. Restore IP Addresses.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List restoreIpAddresses(String s) { 3 | List allIpAddresses = new ArrayList<>(); 4 | 5 | snapshotIpAddress(allIpAddresses, s, 0, new String[4], 0); 6 | 7 | return allIpAddresses; 8 | } 9 | 10 | private void snapshotIpAddress(List allIpAddresses, String s, int idx, String[] ipSnapshot, int segment) { 11 | // Find a valid IP address 12 | if (segment == 4 && idx == s.length()) { 13 | String ipAddress = String.join(".", ipSnapshot[0], ipSnapshot[1], ipSnapshot[2], ipSnapshot[3]); 14 | allIpAddresses.add(ipAddress); 15 | } else if (segment == 4 && idx != s.length()) { 16 | return; 17 | } 18 | 19 | for (int len = 1; len <= 3 && idx + len <= s.length(); ++len) { 20 | String snapshot = s.substring(idx, idx + len); 21 | int value = Integer.parseInt(snapshot); 22 | 23 | if (value > 255 || (len >= 2 && s.charAt(idx) == '0')) { 24 | break; 25 | } 26 | 27 | ipSnapshot[segment] = snapshot; 28 | 29 | snapshotIpAddress(allIpAddresses, s, idx + len, ipSnapshot, segment + 1); 30 | 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /930. Binary Sub-arrays With Sum.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * 930. Binary Sub-arrays With Sum 4 | * 5 | * https://leetcode.com/problems/binary-subarrays-with-sum/ 6 | * 7 | * In an array A of 0s and 1s, how many non-empty sub-arrays have sum S? 8 | */ 9 | public class NO_930 { 10 | Solution solution = new Solution(); 11 | 12 | public static void main(String[] args) { 13 | System.out.println(new NO_930().solution.numSubArraysWithSum(new int[]{1,0,1,0,1}, 2)); 14 | 15 | System.out.println(new NO_930().solution.numSubArraysWithSum(new int[]{0,0,0,0,0}, 0)); 16 | 17 | } 18 | 19 | class Solution { 20 | public int numSubArraysWithSum(int[] A, int S) { 21 | int[] preSum = new int[A.length + 1]; 22 | 23 | for(int i = 0; i < A.length; i++) { 24 | preSum[i + 1] = preSum[i] + A[i]; 25 | } 26 | 27 | int totalCount = 0; 28 | for(int i = 1; i <= A.length; i++) { 29 | for(int j = 0; j < i; j++) { 30 | if(preSum[i] - preSum[j] == S) { 31 | totalCount++; 32 | } 33 | } 34 | } 35 | return totalCount; 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /94_Binary Tree Inorder Traversal/94_Binary Tree Inorder Traversal.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shineyr/LeetCode/501fbac03deff0ae9c5cbcc0d1e2d444c3779059/94_Binary Tree Inorder Traversal/94_Binary Tree Inorder Traversal.cpp -------------------------------------------------------------------------------- /95. Unique Binary Search Trees II.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode() {} 8 | * TreeNode(int val) { this.val = val; } 9 | * TreeNode(int val, TreeNode left, TreeNode right) { 10 | * this.val = val; 11 | * this.left = left; 12 | * this.right = right; 13 | * } 14 | * } 15 | */ 16 | class Solution { 17 | public List generateTrees(int n) { 18 | if (n == 0) { 19 | return new ArrayList(); 20 | } 21 | 22 | return generateTrees(1, n); 23 | } 24 | 25 | private List generateTrees(int beg, int end) { 26 | List trees = new ArrayList(); 27 | 28 | if (beg > end) { 29 | trees.add(null); 30 | return trees; 31 | } 32 | 33 | for (int r = beg; r <= end; ++r) { 34 | List leftTrees = generateTrees(beg, r - 1); 35 | List rightTrees = generateTrees(r + 1, end); 36 | 37 | for(TreeNode leftTree : leftTrees) { 38 | for (TreeNode rightTree : rightTrees) { 39 | TreeNode root = new TreeNode(r, leftTree, rightTree); 40 | trees.add(root); 41 | } 42 | } 43 | } 44 | 45 | return trees; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /95_Unique Binary Search Trees II/main.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shineyr/LeetCode/501fbac03deff0ae9c5cbcc0d1e2d444c3779059/95_Unique Binary Search Trees II/main.cpp -------------------------------------------------------------------------------- /96. Unique Binary Search Trees.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // numTrees[4] = numTrees[0] * numTrees[3] + 3 | // numTrees[1] * numTrees[2] + 4 | // numTrees[2] * numTrees[1] + 5 | // numTrees[3] * numTrees[0] 6 | public int numTrees(int n) { 7 | int[] numTrees = new int[n+1]; 8 | 9 | numTrees[0] = 1; // empty tree 10 | numTrees[1] = 1; // tree with only one root 11 | 12 | for (int node = 1; node < n + 1; ++node) { 13 | int totalTrees = 0; 14 | 15 | for (int root = 1; root < node + 1; ++root) { 16 | int leftNodes = root - 1; 17 | int rightNodes = node - root; 18 | 19 | totalTrees += numTrees[leftNodes] * numTrees[rightNodes]; 20 | } 21 | 22 | numTrees[node] = totalTrees; 23 | } 24 | 25 | return numTrees[n]; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /96_Unique Binary Search Trees/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | int numTrees(int n) { 10 | if (n <= 0) 11 | return 0; 12 | //保存[1,n]每个值对应的二叉查找树个数 13 | vector nums(n+1, 0); 14 | 15 | //空子树也算一颗 16 | nums[0] = 1; 17 | 18 | for (int r = 1; r <= n; ++r) 19 | { 20 | //当 n == 1 或者 n == 2时,满足要求的树的个数为n 21 | if (r <= 2) 22 | { 23 | nums[r] = r; 24 | continue; 25 | }//if 26 | 27 | //对于 [1 , r]之间的每个元素都可作为根节点 28 | for (int i = 1; i <= r; i++) 29 | { 30 | //此时能构成的二叉查找树个数 = [1,i-1]构成的左子树数目 * [i+1 , r]构成的右子树数目 31 | int lefts = nums[i - 1]; 32 | 33 | //[i+1 , r]为连续的 r-i 个元素,所构成的树数目等于元素[1 , r-i]构成的数目 34 | int rights = nums[r - i]; 35 | 36 | // 37 | nums[r] += lefts * rights; 38 | }//for 39 | }//for 40 | return nums[n]; 41 | } 42 | }; 43 | 44 | int main(){ 45 | Solution s; 46 | int c = s.numTrees(3); 47 | cout << c << endl; 48 | 49 | system("pause"); 50 | return 0; 51 | } -------------------------------------------------------------------------------- /LeetCode01/LeetCode01.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution 9 | { 10 | public: 11 | vector twoSum(vector &numbers, int target) 12 | { 13 | vector index; 14 | map hashMap; 15 | for (unsigned int i = 0; i < numbers.size(); i++) 16 | { 17 | if (!hashMap.count(numbers[i])) 18 | hashMap.insert(make_pair(numbers[i], i)); 19 | if (hashMap.count(target - numbers[i])) 20 | { 21 | int pos = hashMap[target - numbers[i]]; 22 | if (pos < i) 23 | { 24 | index.push_back(pos + 1); 25 | index.push_back(i + 1); 26 | } 27 | }//if 28 | }//for 29 | return index; 30 | }//twoSum 31 | }; 32 | 33 | int main() 34 | { 35 | Solution s; 36 | int arr[3] = { 3, 2, 4 }; 37 | int target = 6; 38 | vector numbers(arr, arr + 3); 39 | vector index; 40 | index = s.twoSum(numbers, target); 41 | 42 | cout << "index1=" << index[0] << ", index2=" << index[1] << endl; 43 | 44 | system("pause"); 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /LeetCode03/LeetCode03.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | int lengthOfLongestSubstring(string s) { 11 | if (s.empty()) 12 | return 0; 13 | 14 | int hash_tab[256]; //保存当前字符上一次出现的下标 15 | memset(hash_tab, -1, sizeof(hash_tab)); //hash_tab中初始化所有值为-1 16 | int max_len = 0, pos = -1;//max_len即是最长子串长度 , pos为当前子串的开始位置 17 | 18 | for (int i = 0; i pos) 22 | { 23 | pos = hash_tab[s[i]]; 24 | }//if 25 | 26 | if (i - pos > max_len) 27 | { 28 | max_len = i - pos; 29 | }//if 30 | 31 | //更改首次出现字符的位置 32 | hash_tab[s[i]] = i; 33 | }//for 34 | return max_len; 35 | } 36 | }; 37 | 38 | int main() 39 | { 40 | Solution s; 41 | cout << s.lengthOfLongestSubstring("aaabbbbbbaaaa") << endl; 42 | 43 | system("pause"); 44 | 45 | return 0; 46 | } -------------------------------------------------------------------------------- /LeetCode03/Longest Substring.txt: -------------------------------------------------------------------------------- 1 | 题目: 2 | 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. 3 | 提示标签: hashtable 、 Two Pointers 、 String 4 | 5 | 分析: 6 | 该题目是一个求最长连续子串的长度问题,根据提示标签,题解应该涉及到哈希表的应用,严格控制每个字符的出现下标,以及更新子串位置同时对比当前最长子串的位置。 7 | 8 | 算法: 9 | 10 | class Solution { 11 | public: 12 | int lengthOfLongestSubstring(string s) { 13 | if(s.empty()) 14 | return 0; 15 | 16 | int hash_tab[256]; //保存当前字符上一次出现的下标 17 | memset(hash_tab , -1 , sizeof(hash_tab)); //hash_tab中初始化所有值为-1 18 | int max_len = 0, pos = -1;//max_len即是最长子串长度 , pos为当前子串的开始位置 19 | 20 | for(int i=0 ; i pos) 24 | { 25 | pos = hash_tab[s[i]]; 26 | }//if 27 | 28 | if(i-pos > max_len) 29 | { 30 | max_len = i-pos; 31 | }//if 32 | 33 | //更改首次出现字符的位置 34 | hash_tab[s[i]] = i; 35 | }//for 36 | return max_len; 37 | } 38 | }; -------------------------------------------------------------------------------- /LeetCode06/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | string convert(string s, int numRows) { 10 | 11 | if (s.empty() || numRows == 1) 12 | return s; 13 | //声明numRows个字符串,对该之字型序列处理 14 | string *res = new string[numRows]; 15 | int i = 0, j, gap = numRows - 2; 16 | while (i < s.size()){ 17 | for (j = 0; i < s.size() && j < numRows; ++j) res[j] += s[i++]; 18 | for (j = gap; i < s.size() && j > 0; --j) res[j] += s[i++]; 19 | } 20 | string str = ""; 21 | for (i = 0; i < numRows; ++i) 22 | str += res[i]; 23 | return str; 24 | } 25 | 26 | }; 27 | 28 | int main() 29 | { 30 | Solution s; 31 | 32 | cout << s.convert("PAYPALISHIRING", 3) << endl; 33 | 34 | system("pause"); 35 | return 0; 36 | } -------------------------------------------------------------------------------- /LeetCode07/LeetCode07.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution 7 | { 8 | public: 9 | int reverse(int x) 10 | { 11 | if (overflow(x) == true) 12 | { 13 | return 0; 14 | } 15 | 16 | int result = 0; 17 | 18 | while (x != 0) 19 | { 20 | result = 10 * result + x % 10; 21 | x /= 10; 22 | } 23 | 24 | return result; 25 | } 26 | private: 27 | bool overflow(int x) 28 | { 29 | if (x / 1000000000 == 0) // x的绝对值小于1000000000, 不越界 30 | { 31 | return false; 32 | } 33 | else if (x == INT_MIN) // INT_MIN反转后越界,也没法按下述方法取绝对值(需要特判),直接返回true 34 | { 35 | return true; 36 | } 37 | x = abs(x); 38 | // x = d463847412 -> 2147483647. (参数x,本身没有越界,所以d肯定是1或2) 39 | // or -d463847412 -> -2147483648. 40 | for (int cmp = 463847412; cmp != 0; cmp /= 10, x /= 10) 41 | { 42 | if (x % 10 > cmp % 10) 43 | { 44 | return true; 45 | } 46 | else if (x % 10 < cmp % 10) 47 | { 48 | return false; 49 | } 50 | } 51 | 52 | return false; 53 | } 54 | }; 55 | 56 | int main() 57 | { 58 | Solution s; 59 | cout << s.reverse(2147482345) << endl; 60 | system("pause"); 61 | return 0; 62 | } -------------------------------------------------------------------------------- /LeetCode13/LeetCode13.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution{ 7 | public: 8 | 9 | Solution() 10 | { 11 | 12 | } 13 | 14 | ~Solution() 15 | { 16 | 17 | } 18 | int Value(char c) 19 | { 20 | switch (c) 21 | { 22 | case 'I': 23 | return 1; break; 24 | case 'V': 25 | return 5; break; 26 | case 'X': 27 | return 10; break; 28 | case 'L': 29 | return 50; break; 30 | case 'C': 31 | return 100; break; 32 | case 'D': 33 | return 500; break; 34 | case 'M': 35 | return 1000; break; 36 | default: 37 | return 0; break; 38 | } 39 | } 40 | int romanToInt(string s) { 41 | int ret = 0; 42 | if (s == "") 43 | return ret; 44 | ret += Value(s[0]); 45 | for (int i = 0; s[i+1] != '\0'; i++) 46 | { 47 | if (Value(s[i + 1]) <= Value(s[i])) 48 | ret += Value(s[i + 1]); 49 | else 50 | ret = ret + Value(s[i + 1]) - 2 * Value(s[i]); 51 | } 52 | return ret; 53 | } 54 | }; 55 | 56 | int main() 57 | { 58 | Solution *s = new Solution(); 59 | cout << s->romanToInt("I") << endl; 60 | cout << s->romanToInt("IV") << endl; 61 | cout << s->romanToInt("MDCCCLXXXIV") << endl; 62 | cout << s->romanToInt("MCMXCVI") << endl; 63 | system("pause"); 64 | return 0; 65 | } -------------------------------------------------------------------------------- /LeetCode14/LeetCode14.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | string longestCommonPrefix(vector& strs) { 11 | if (strs.size() == 0) 12 | return ""; 13 | else if (strs.size() == 1) 14 | return *(strs.begin()); 15 | 16 | vector::iterator beg, end; 17 | beg = strs.begin(); 18 | 19 | //先得到前两个串的公共前缀 20 | string str = CommonPrefix(*beg, *(beg+1)); 21 | 22 | //迭代器后移两个位置 23 | beg += 2; 24 | 25 | while (beg != strs.end()) 26 | { 27 | if (str == "") 28 | break; 29 | str = CommonPrefix(str, *(beg++)); 30 | } 31 | 32 | return str; 33 | } 34 | 35 | string CommonPrefix(const string &str1, const string &str2) 36 | { 37 | string common = ""; 38 | if (str1 == "" || str2 == "") 39 | return common; 40 | 41 | int len1 = strlen(str1.c_str()) , len2 = strlen(str2.c_str()); 42 | 43 | int len = len1 > len2 ? len2 : len1 ; 44 | 45 | for (int i = 0; i < len; i++) 46 | { 47 | if (str1[i] == str2[i]) 48 | common += str1[i]; 49 | else 50 | break; 51 | } 52 | 53 | return common; 54 | } 55 | }; 56 | 57 | int main() 58 | { 59 | Solution *s = new Solution(); 60 | 61 | //vector v = {"abc" , "abcd" , "abc12342143","abc3434"}; 62 | vector v = {}; 63 | cout << s->longestCommonPrefix(v) << endl; 64 | 65 | system("pause"); 66 | 67 | return 0; 68 | } -------------------------------------------------------------------------------- /LeetCode169/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | int majorityElement(vector& nums) { 11 | //题目假设输入数组非空,且出现次数大于[n/2]的元素存在 12 | int len = nums.size() , count = len/2; 13 | 14 | sort(nums.begin(), nums.end()); 15 | 16 | if (len == 1) 17 | return nums[0]; 18 | int tmp = 1; 19 | for (int i = 0; i < len-1; i++) 20 | { 21 | if (nums[i + 1] == nums[i]) 22 | { 23 | ++tmp; 24 | if (tmp > count) 25 | return nums[i]; 26 | } 27 | else{ 28 | tmp = 1; 29 | }//if 30 | }//for 31 | return -1; 32 | } 33 | }; 34 | 35 | int main() 36 | { 37 | int arr[10] = { 1, 2, 3, 4, 4, 6, 4, 4, 5, 6 }; 38 | //int arr[1] = { 1}; 39 | vector v(arr, arr + 10); 40 | 41 | Solution s; 42 | cout << s.majorityElement(v) << endl; 43 | 44 | system("pause"); 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /LeetCode20/mian.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | bool isValid(string s) { 11 | int len = strlen(s.c_str()); 12 | if (len == 0) 13 | return true; 14 | if (len % 2 != 0) 15 | return false; 16 | 17 | //括号匹配问题,用数据结构栈辅助实现 18 | stack sta; 19 | for (int i = 0; i < len; i++) 20 | { 21 | if (s[i] != ')' && s[i] != ']' && s[i] != '}') 22 | sta.push(s[i]); 23 | else 24 | { 25 | if (sta.size() <= 0) 26 | return false; 27 | if (s[i] == PairLetter(sta.top())) 28 | sta.pop(); 29 | else 30 | return false; 31 | }//else 32 | }//for 33 | if (sta.size() == 0) 34 | return true; 35 | else 36 | return false; 37 | } 38 | 39 | char PairLetter(const char &c) 40 | { 41 | switch (c) 42 | { 43 | case '(': 44 | return ')'; break; 45 | case '[': 46 | return ']'; break; 47 | case '{': 48 | return '}'; break; 49 | default: 50 | return 0; break; 51 | } 52 | } 53 | }; 54 | 55 | int main() 56 | { 57 | //string str = "()"; 58 | //string str = ""; 59 | //string str = "()()[][]{}{}"; 60 | string str = "([{]}){}"; 61 | 62 | Solution *s = new Solution(); 63 | if (s->isValid(str)) 64 | cout << str <<" : "<< "true" << endl; 65 | else 66 | cout << str << " : " << "false" << endl; 67 | 68 | system("pause"); 69 | return 0; 70 | 71 | } -------------------------------------------------------------------------------- /LeetCode26/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | int removeDuplicates(vector& nums) { 11 | if (nums.size() <= 1) 12 | return nums.size(); 13 | 14 | int i = 0, j = 1; 15 | while (j < nums.size()) 16 | { 17 | if (nums[i] == nums[j]) 18 | { 19 | ++j; 20 | } 21 | else 22 | { 23 | nums[++i] = nums[j++]; 24 | } 25 | } 26 | return i + 1; 27 | } 28 | }; 29 | 30 | int main() 31 | { 32 | int arr[3] = { 1, 2 , 2}; 33 | vector v(arr, arr +3); 34 | 35 | Solution *s = new Solution(); 36 | int len = s->removeDuplicates(v); 37 | cout << len << endl; 38 | for (int i = 0; i < len; i++) 39 | cout << v[i] << "\t"; 40 | system("pause"); 41 | 42 | return 0; 43 | 44 | } -------------------------------------------------------------------------------- /LeetCode27/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | int removeElement(vector& nums, int val) { 10 | int i = 0 , k = 0; 11 | while (i < nums.size()) 12 | { 13 | if (nums[i] != val) 14 | nums[k++] = nums[i]; 15 | i++; 16 | } 17 | return k; 18 | } 19 | }; 20 | 21 | int main() 22 | { 23 | int arr[10] = { 1, 2, 5, 5, 6, 23, 5, 6, 7, 10 }; 24 | vector v(arr, arr + 10); 25 | Solution *s = new Solution(); 26 | int len = s->removeElement(v , 5); 27 | 28 | for (int i = 0; i < len; i++) 29 | cout << v[i] << "\t"; 30 | 31 | cout << endl; 32 | 33 | system("pause"); 34 | return 0; 35 | 36 | } 37 | -------------------------------------------------------------------------------- /LeetCode31/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | //寻找整数序列num的下一个全排序列 10 | void nextPermutation(vector &num) { 11 | if (num.size() < 2) return; 12 | 13 | int i, k; 14 | for (i = num.size() - 2; i >= 0; --i) 15 | if (num[i] < num[i + 1]) 16 | break; 17 | //若不存在子升序,则说明当前排列是最大排列,此时i = -1,下一排列即是最小排列,翻转整个序列即可 18 | if (i < 0) 19 | { 20 | reverse(num.begin() , num.end()); 21 | return; 22 | } 23 | //找到了子升序 24 | for (k = num.size() - 1; i >= 0 && k > i ; --k) 25 | if (num[i] < num[k]) 26 | break; 27 | if (i >= 0) 28 | { 29 | swap(num[i], num[k]); 30 | reverse(num.begin() + i + 1, num.end()); 31 | return; 32 | } 33 | } 34 | }; 35 | 36 | int main() 37 | { 38 | int arr[3] = { 3, 2, 1}; 39 | vector v(arr, arr + 3); 40 | 41 | Solution *s = new Solution(); 42 | s->nextPermutation(v); 43 | 44 | for (int i = 0; i < 3; i++) 45 | cout << v[i] << "\t"; 46 | cout << endl; 47 | system("pause"); 48 | 49 | return 0; 50 | } -------------------------------------------------------------------------------- /LeetCode35/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | int searchInsert(vector& nums, int target) { 10 | if (nums.size() == 0) 11 | return 0; 12 | else if (nums.size() == 1) 13 | { 14 | if (nums[0] >= target) 15 | return 0; 16 | else 17 | return 1; 18 | } 19 | else{ 20 | return BinarySearch(nums, target); 21 | } 22 | } 23 | 24 | int BinarySearch(vector & nums, int target) 25 | { 26 | int left = 0, right = nums.size() - 1; 27 | 28 | while (left <= right) 29 | { 30 | int mid = (left + right) / 2; 31 | if (nums[mid] == target) 32 | return mid; 33 | else if (nums[mid] < target) 34 | { 35 | if (mid == right || nums[mid + 1] > target) 36 | return mid + 1; 37 | else 38 | left = mid + 1; 39 | } 40 | else{ 41 | if (mid == left || nums[mid - 1] < target) 42 | return mid; 43 | else 44 | right = mid - 1; 45 | } 46 | }//while 47 | 48 | return -1; 49 | } 50 | }; 51 | 52 | int main() 53 | { 54 | int arr1[4] = { 1, 3, 5, 6 }; 55 | //5 → 2 56 | int arr2[4] = { 1, 3, 5, 6 }; 57 | //2 → 1 58 | int arr3[4] = { 1, 3, 5, 6 }; 59 | //7 → 4 60 | int arr4[4] = { 1 }; 61 | //0 → 0 62 | 63 | vector v(arr4, arr4 + 1); 64 | Solution s; 65 | cout << s.searchInsert(v, 2); 66 | 67 | system("pause"); 68 | return 0; 69 | } -------------------------------------------------------------------------------- /LeetCode38/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | string countAndSay(int n) { 11 | if (n <= 0) 12 | return NULL; 13 | 14 | //n=1时,结果为"1" 15 | string ret = "1"; 16 | if (n == 1) 17 | return ret; 18 | else 19 | { 20 | for (int i = 2; i <= n; i++) 21 | ret = Count(ret); 22 | }//else 23 | return ret; 24 | 25 | } 26 | 27 | string Count(const string &str) 28 | { 29 | int size = strlen(str.c_str()); 30 | //保存结果 31 | stringstream ret; 32 | //保存标识字符 33 | char flag = str[0]; 34 | //计算标识字符的出现次数 35 | int count = 0 , i = 0; 36 | while( i < size ) 37 | { 38 | //临时循环位 39 | int pos = i; 40 | while (str[pos] == flag) 41 | { 42 | count++; 43 | pos++; 44 | }//while 45 | ret << count << flag; 46 | flag = str[pos]; 47 | count = 0; 48 | //设置下一个循环位 49 | i = pos; 50 | }//for 51 | return ret.str(); 52 | } 53 | }; 54 | 55 | int main() 56 | { 57 | Solution s; 58 | for (int i = 1; i <= 10; i++) 59 | cout <<"n = "< 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | vector> permute(vector& nums) { 11 | vector > ret; 12 | 13 | if (nums.empty()) 14 | return ret; 15 | 16 | sort(nums.begin(), nums.end()); 17 | ret.push_back(nums); 18 | while (next_permutation(nums.begin(), nums.end())) 19 | ret.push_back(nums); 20 | 21 | return ret; 22 | } 23 | }; 24 | 25 | int main() 26 | { 27 | Solution s; 28 | vector > v = s.permute(vector{0, -1, 1}); 29 | 30 | for (int i = 0; i < v.size(); i++) 31 | cout << v[i][0] << "\t" << v[i][1] << "\t" << v[i][2] << endl; 32 | 33 | system("pause"); 34 | 35 | return 0; 36 | } -------------------------------------------------------------------------------- /LeetCode47/main.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | vector> permuteUnique(vector& nums) { 12 | vector > ret; 13 | 14 | if (nums.empty()) 15 | return ret; 16 | 17 | sort(nums.begin(), nums.end()); 18 | ret.push_back(nums); 19 | while (next_permutation(nums.begin(), nums.end())) 20 | ret.push_back(nums); 21 | 22 | return ret; 23 | } 24 | }; 25 | 26 | int main() 27 | { 28 | Solution s; 29 | vector > v = s.permute(vector{1, 1, 2}); 30 | 31 | for (int i = 0; i < v.size(); i++) 32 | cout << v[i][0] << "\t" << v[i][1] << "\t" << v[i][2] << endl; 33 | 34 | system("pause"); 35 | 36 | return 0; 37 | } -------------------------------------------------------------------------------- /LeetCode48/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | void rotate(vector>& matrix) { 10 | if (matrix.empty()) 11 | return; 12 | 13 | int n = matrix.size(); 14 | 15 | //首先,沿主对角线交换元素 16 | for (int i = 0; i < n; i++) 17 | { 18 | for (int j = 0; j <= i; j++) 19 | swap(matrix[i][j], matrix[j][i]); 20 | } 21 | //然后,交换对称列 22 | for (int i = 0, j = n - 1; i < j; i++, j--) 23 | { 24 | for (int k = 0; k < n; k++) 25 | swap(matrix[k][i], matrix[k][j]); 26 | } 27 | } 28 | }; 29 | 30 | int main() 31 | { 32 | Solution s; 33 | 34 | vector > ret = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, {13,14,15,16} }; 35 | 36 | for (int i = 0; i < 4; i++) 37 | { 38 | for (int j = 0; j < 4; j++) 39 | cout << ret[i][j] << "\t"; 40 | cout << endl; 41 | } 42 | 43 | s.rotate(ret); 44 | cout << endl; 45 | cout << endl; 46 | cout << endl; 47 | for (int i = 0; i < 4; i++) 48 | { 49 | for (int j = 0; j < 4; j++) 50 | cout << ret[i][j] << "\t"; 51 | cout << endl; 52 | } 53 | 54 | system("pause"); 55 | return 0; 56 | } -------------------------------------------------------------------------------- /LeetCode54/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | vector spiralOrder(vector>& matrix) { 10 | if (matrix.empty()) 11 | return vector(); 12 | 13 | vector ret; 14 | 15 | //输入矩阵行数 16 | int m = matrix.size() - 1; 17 | 18 | //输入矩阵的列数 19 | int n = matrix[0].size() - 1; 20 | 21 | for (int x = 0, y = 0; x <= m && y <= n; x++, y++) 22 | { 23 | //输出矩阵首行 24 | for(int j=y ; j<=n ; ++j) 25 | { 26 | ret.push_back(matrix[x][j]); 27 | }//while 28 | 29 | 30 | //输出矩阵最右列 31 | for (int i = x + 1; i <= m; ++i) 32 | { 33 | ret.push_back(matrix[i][n]); 34 | }//while 35 | 36 | //输出矩阵最底行 37 | for (int j = n - 1; j >= y && x != m; --j) 38 | { 39 | ret.push_back(matrix[m][j]); 40 | } 41 | 42 | //输出矩阵最左列 43 | for (int i = m - 1; i > x && y != n; --i) 44 | { 45 | ret.push_back(matrix[i][y]); 46 | } 47 | 48 | m--; 49 | n--; 50 | }//for 51 | 52 | return ret; 53 | } 54 | }; 55 | 56 | int main() 57 | { 58 | Solution s; 59 | vector > v = { { 1, 2, 3, 4 }/*, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }*/ }; 60 | 61 | vector ret = s.spiralOrder(v); 62 | 63 | for (int i = 0; i < ret.size(); i++) 64 | cout << ret[i] << "\t"; 65 | cout << endl; 66 | 67 | system("pause"); 68 | return 0; 69 | } -------------------------------------------------------------------------------- /LeetCode55/55_Jump Game.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | //贪心算法 9 | class Solution { 10 | public: 11 | bool canJump(vector& nums) { 12 | if (nums.empty()) 13 | return false; 14 | 15 | int maxStep = nums[0]; 16 | int len = nums.size(); 17 | 18 | for (int i = 1; i < len; ++i) 19 | { 20 | if (maxStep <= 0) 21 | return false; 22 | else{ 23 | maxStep = max(--maxStep, nums[i]); 24 | }//else 25 | }//for 26 | 27 | return true; 28 | } 29 | }; 30 | 31 | 32 | 33 | int main() 34 | { 35 | Solution s; 36 | vector v1 = { 2, 3, 1, 1, 4 }; 37 | vector v2 = { 3, 2, 1, 0, 4 }; 38 | bool ret = s.canJump(v1); 39 | 40 | cout << ret << endl; 41 | 42 | system("pause"); 43 | return 0; 44 | 45 | } -------------------------------------------------------------------------------- /LeetCode58/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | vector> generateMatrix(int n) { 10 | vector > ret(n,vector(n , 0)); 11 | if (n <= 0) 12 | return ret; 13 | 14 | int index = 1 , row = n-1 , col = n-1; 15 | for (int x = 0, y = 0; x <= row && y <= col; x++, y++) 16 | { 17 | //为矩阵首行赋值 18 | for (int j = y; j <= col; ++j , index++) 19 | ret[x][j] = index; 20 | 21 | //为矩阵最右列赋值 22 | for (int i = x + 1; i <= row; ++i,index++) 23 | ret[i][col] = index; 24 | 25 | //为矩阵最底行赋值 26 | for (int j = col - 1; j >= y && x != row; --j, index++) 27 | ret[row][j] = index; 28 | 29 | //为矩阵最左列赋值 30 | for (int i = row - 1; i > x && y != col; --i, index++) 31 | ret[i][y] = index; 32 | 33 | //为内旋子矩阵赋值 34 | row--; 35 | col--; 36 | 37 | }//for 38 | return ret; 39 | } 40 | }; 41 | 42 | int main() 43 | { 44 | Solution s; 45 | int n = 5; 46 | vector > v = s.generateMatrix(n); 47 | 48 | for (int i = 0; i < n; i++) 49 | { 50 | for (int j = 0; j < n; j++) 51 | { 52 | cout << v[i][j] << "\t"; 53 | } 54 | cout << endl; 55 | }//for 56 | 57 | system("pause"); 58 | return 0; 59 | } -------------------------------------------------------------------------------- /LeetCode59/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | int lengthOfLastWord(string s) { 10 | int len = strlen(s.c_str()); 11 | 12 | //如果是空字符串或者是单字符,则直接返回长度 13 | if (len == 0) 14 | return len; 15 | 16 | 17 | int i = len-1 , j = 0; 18 | //从后向前找到非空字符 19 | while (i>=0 && s[i] == ' ') 20 | --i; 21 | 22 | for (j = i; j>=0 && s[j] != ' '; --j) 23 | ; 24 | 25 | return i - j; 26 | } 27 | }; 28 | 29 | int main() 30 | { 31 | Solution s; 32 | cout << s.lengthOfLastWord(" ") << endl; 33 | 34 | system("pause"); 35 | return 0; 36 | } -------------------------------------------------------------------------------- /LeetCode62/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | ////递归实现回溯,会超时 8 | //class Solution { 9 | //public: 10 | // int uniquePaths(int m, int n) { 11 | // if (m == 0 || n == 0) 12 | // return 0; 13 | // //如果矩阵为单行或者单列,则只有一条路径 14 | // else if (m == 1 || n == 1) 15 | // return 1; 16 | // 17 | // else 18 | // return uniquePaths(m, n - 1) + uniquePaths(m - 1, n); 19 | // } 20 | //}; 21 | 22 | //非递归实现回溯,会超时 23 | class Solution { 24 | public: 25 | int uniquePaths(int m, int n) { 26 | if (m == 0 || n == 0) 27 | return 0; 28 | vector > ret(m, vector(n, 1)); 29 | //如果矩阵为单行或者单列,则只有一条路径 30 | for (int i = 1; i < m; i++) 31 | for (int j = 1; j < n; j++) 32 | ret[i][j] = ret[i - 1][j] + ret[i][j - 1]; 33 | 34 | return ret[m-1][n-1]; 35 | } 36 | }; 37 | 38 | 39 | int main() 40 | { 41 | Solution s; 42 | cout << s.uniquePaths(23, 12) << endl; 43 | 44 | system("pause"); 45 | return 0; 46 | } -------------------------------------------------------------------------------- /LeetCode64/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | int minPathSum(vector>& grid) { 11 | if (grid.empty()) 12 | return 0; 13 | 14 | //求当前矩阵的行数、列数 15 | int m = grid.size(); 16 | int n = grid[0].size(); 17 | 18 | vector > sum(m, vector(n, 0)); 19 | 20 | //记录首元素和 21 | sum[0][0] = grid[0][0]; 22 | int minSum = sum[0][0]; 23 | 24 | for (int i = 1; i < m; i++) 25 | { 26 | sum[i][0] = sum[i - 1][0] + grid[i][0]; 27 | //此时路径和唯一,也是最小路径和 28 | }//for 29 | 30 | for (int j = 1; j < n; j++) 31 | { 32 | sum[0][j] = sum[0][j - 1] + grid[0][j]; 33 | //此时路径和唯一,也是最小路径和 34 | }//for 35 | 36 | for (int i = 1; i < m; i++) 37 | { 38 | for (int j = 1; j < n; j++) 39 | { 40 | sum[i][j] = min(sum[i - 1][j], sum[i][j - 1]) + grid[i][j]; 41 | }//for 42 | }//for 43 | 44 | return sum[m - 1][n - 1]; 45 | } 46 | }; 47 | 48 | int main() 49 | { 50 | Solution s; 51 | vector > v = { { 1, 2, 3 }, { 4, 5, 6 }, { 8, 7, 9 } }; 52 | //vector > v = { { 0 }, { 0 }, { 0 }, { 0 }, { 0 }, { 0 }, { 0 }, { 0 }, { 0 }, { 0 } }; 53 | cout << s.minPathSum(v)<< endl; 54 | 55 | system("pause"); 56 | 57 | return 0; 58 | 59 | } 60 | 61 | -------------------------------------------------------------------------------- /LeetCode66/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | vector plusOne(vector& digits) { 10 | int len = digits.size(); 11 | 12 | if (len == 0) 13 | return digits; 14 | 15 | int carry = 1; 16 | for (int i = len - 1; i >= 0; --i) 17 | { 18 | digits[i] += carry; 19 | if (digits[i] >= 10) 20 | { 21 | digits[i] -= 10; 22 | carry = 1; 23 | continue; 24 | } 25 | else{ 26 | carry = 0; 27 | break; 28 | } 29 | } 30 | 31 | if (carry == 0) 32 | return digits; 33 | else 34 | { 35 | vector v; 36 | v.push_back(1); 37 | for (int i = 0; i < len; i++) 38 | v.push_back(0); 39 | return v; 40 | } 41 | } 42 | }; 43 | 44 | int main() 45 | { 46 | Solution s; 47 | int arr[3] = { 9, 9, 9 }; 48 | 49 | vector v{ arr, arr + 3 }; 50 | 51 | vector r; 52 | r = s.plusOne(v); 53 | 54 | for (int i = 0; i < r.size(); ++i) 55 | cout << r[i]; 56 | cout << endl; 57 | 58 | system("pause"); 59 | return 0; 60 | } -------------------------------------------------------------------------------- /LeetCode70/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | int climbStairs(int n) { 10 | 11 | //如果0层,返回0 12 | if (n <= 0) 13 | return 0; 14 | //如果只有1层阶梯,则只有一种方式 15 | else if (n == 1) 16 | return 1; 17 | //若有两层阶梯,则有两种方式(每次走一层,一次走两层) 18 | else if (n == 2) 19 | return 2; 20 | 21 | int *r = new int[n]; 22 | //其余的情况方式总数 = 最终剩余1层的方式 + 最终剩余两层阶梯的方式 23 | r[0] = 1; 24 | r[1] = 2; 25 | 26 | for (int i = 2; i < n; i++) 27 | r[i] = r[i - 1] + r[i - 2]; 28 | 29 | int ret = r[n - 1]; 30 | delete []r; 31 | return ret; 32 | } 33 | }; 34 | 35 | int main() 36 | { 37 | Solution s; 38 | 39 | cout << s.climbStairs(8) << endl; 40 | 41 | system("pause"); 42 | 43 | return 0; 44 | 45 | } -------------------------------------------------------------------------------- /LeetCode88/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | void merge(vector& nums1, int m, vector& nums2, int n) { 11 | vector ret; 12 | int i = 0, j = 0; 13 | while (i < m && j < n) 14 | { 15 | if (nums1[i] <= nums2[j]) 16 | { 17 | ret.push_back(nums1[i]); 18 | i++; 19 | }else{ 20 | ret.push_back(nums2[j]); 21 | j++; 22 | }//elif 23 | }//while 24 | 25 | while (i < m) 26 | { 27 | ret.push_back(nums1[i]); 28 | i++; 29 | }//while 30 | 31 | while (j < n) 32 | { 33 | ret.push_back(nums2[j]); 34 | j++; 35 | }//while 36 | 37 | nums1 = ret; 38 | 39 | } 40 | 41 | }; 42 | 43 | int main() 44 | { 45 | int arr1[4] = { 1, 2, 2, 5 }; 46 | int arr2[6] = { 1, 2, 3, 4, 5, 6 }; 47 | 48 | vector v1(arr1, arr1 + 4); 49 | vector v2(arr2, arr2 + 6); 50 | 51 | Solution s; 52 | s.merge(v1, 4 , v2 , 6); 53 | 54 | vector::iterator iter = v1.begin(); 55 | while (iter != v1.end()) 56 | { 57 | cout << *iter << "\t"; 58 | iter++; 59 | } 60 | 61 | cout << endl; 62 | 63 | system("pause"); 64 | return 0; 65 | 66 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | --------------------------------------------------------------------------------