├── .gitignore ├── C++ ├── 001. Two Sum.cpp ├── 002. Add Two Numbers.cpp ├── 003. Longest Substring Without Repeating Characters.cpp ├── 005. Longest Palindromic Substring.cpp ├── 006. ZigZag Conversion.cpp ├── 007. Reverse Integer.cpp ├── 008. String to Integer (atoi).cpp ├── 009. Palindrome Number.cpp ├── 011. Container With Most Water.cpp ├── 012. Integer to Roman.cpp ├── 013. Roman to Integer.cpp ├── 014. Longest Common Prefix.cpp ├── 015. 3Sum.cpp ├── 016. 3Sum Closest.cpp ├── 017. Letter Combinations of a Phone Number.cpp ├── 018. 4Sum.cpp ├── 019. Remove Nth Node From End of List.cpp ├── 020. Valid Parentheses.cpp ├── 021. Merge Two Sorted Lists.cpp ├── 022. Generate Parentheses.cpp ├── 024. Swap Nodes in Pairs.cpp ├── 026. Remove Duplicates from Sorted Array.cpp ├── 027. Remove Element.cpp ├── 028. Implement strStr().cpp ├── 029. Divide Two Integers.cpp ├── 031. Next Permutation.cpp ├── 034. Search for a Range.cpp ├── 035. Search Insert Position.cpp ├── 036. Valid Sudoku.cpp ├── 038. Count and Say.cpp ├── 039. Combination Sum.cpp ├── 040. Combination Sum II.cpp ├── 046. Permutations.cpp ├── 047. Permutations II.cpp ├── 048. Rotate Image.cpp ├── 051. N-Queens.cpp ├── 052. N-Queens II.cpp ├── 053. Maximum Subarray.cpp ├── 054. Spiral Matrix.cpp ├── 055. Jump Game.cpp ├── 056. Merge Intervals.cpp ├── 058. Length of Last Word.cpp ├── 059. Spiral Matrix II.cpp ├── 060. Permutation Sequence.cpp ├── 061. Rotate List.cpp ├── 062. Unique Paths.cpp ├── 063. Unique Paths II.cpp ├── 064. Minimum Path Sum.cpp ├── 066. Plus One.cpp ├── 067. Add Binary.cpp ├── 069. Sqrt(x).cpp ├── 070. Climbing Stairs.cpp ├── 071. Simplify Path.cpp ├── 074. Search a 2D Matrix.cpp ├── 075. Sort Colors.cpp ├── 077. Combinations .cpp ├── 078. Subsets.cpp ├── 079. Word Search.cpp ├── 080. Remove Duplicates from Sorted Array II.cpp ├── 082. Remove Duplicates from Sorted List II .cpp ├── 083. Remove Duplicates from Sorted List.cpp ├── 088. Merge Sorted Array .cpp ├── 090. Subsets II.cpp ├── 091. Decode Ways.cpp ├── 093. Restore IP Addresses.cpp ├── 094. Binary Tree Inorder Traversal.cpp ├── 096. Unique Binary Search Trees.cpp ├── 098. Validate Binary Search Tree.cpp ├── 100. Same Tree .cpp ├── 101. Symmetric Tree.cpp ├── 102. Binary Tree Level Order Traversal.cpp ├── 103. Binary Tree Zigzag Level Order Traversal.cpp ├── 104. Maximum Depth of Binary Tree.cpp ├── 107. Binary Tree Level Order Traversal II.cpp ├── 108. Convert Sorted Array to Binary Search Tree.cpp ├── 109. Convert Sorted List to Binary Search Tre.cpp ├── 110. Balanced Binary Tree.cpp ├── 111. Minimum Depth of Binary Tree.cpp ├── 112. Path Sum .cpp ├── 113. Path Sum II.cpp ├── 118. Pascal's Triangle.cpp ├── 119. Pascal's Triangle II.cpp ├── 120. Triangle.cpp ├── 121. Best Time to Buy and Sell Stock.cpp ├── 122. Best Time to Buy and Sell Stock II.cpp ├── 125. Valid Palindrome.cpp ├── 127. Word Ladder.cpp ├── 129. Sum Root to Leaf Numbers.cpp ├── 130. Surrounded Regions.cpp ├── 134. Gas Station.cpp ├── 136. Single Number.cpp ├── 137. Single Number II.cpp ├── 141. Linked List Cycle.cpp ├── 142. Linked List Cycle II .cpp ├── 143. Reorder List.cpp ├── 144. Binary Tree Preorder Traversal.cpp ├── 145. Binary Tree Postorder Traversal.cpp ├── 151. Reverse Words in a String.cpp ├── 152. Maximum Product Subarray.cpp ├── 153. Find Minimum in Rotated Sorted Array.cpp ├── 155. Min Stack.cpp ├── 160. Intersection of Two Linked Lists.cpp ├── 162. Find Peak Element .cpp ├── 165. Compare Version Numbers.cpp ├── 166. Fraction to Recurring Decimal.cpp ├── 167. Two Sum II - Input array is sorted.cpp ├── 168. Excel Sheet Column Title.cpp ├── 169. Majority Element.cpp ├── 171. Excel Sheet Column Number.cpp ├── 172. Factorial Trailing Zeroes.cpp ├── 179. Largest Number.cpp ├── 189. Rotate Array.cpp ├── 190. Reverse Bits.cpp ├── 191. Number of 1 Bits .cpp ├── 198. House Robber.cpp ├── 199. Binary Tree Right Side View.cpp ├── 200. Number of Islands.cpp ├── 202. Happy Number.cpp ├── 203. Remove Linked List Elements.cpp ├── 204. Count Primes.cpp ├── 205. Isomorphic Strings.cpp ├── 206. Reverse Linked List.cpp ├── 209. Minimum Size Subarray Sum.cpp ├── 213. House Robber II.cpp ├── 215. Kth Largest Element in an Array.cpp ├── 216. Combination Sum III.cpp ├── 217. Contains Duplicate .cpp ├── 219. Contains Duplicate II.cpp ├── 220. Contains Duplicate III.cpp ├── 222. Count Complete Tree Nodes .cpp ├── 223. Rectangle Area.cpp ├── 225. Implement Stack using Queues.cpp ├── 226. Invert Binary Tree.cpp ├── 228. Summary Ranges.cpp ├── 229. Majority Element II.cpp ├── 230. Kth Smallest Element in a BST.cpp ├── 231. Power of Two.cpp ├── 232. Implement Queue using Stacks.cpp ├── 234. Palindrome Linked List.cpp ├── 235. Lowest Common Ancestor of a Binary Search Tree.cpp ├── 237. Delete Node in a Linked List.cpp ├── 238. Product of Array Except Self .cpp ├── 240. Search a 2D Matrix II.cpp ├── 242. Valid Anagram.cpp ├── 257. Binary Tree Paths .cpp ├── 257. Binary Tree Paths.cpp ├── 258. Add Digits.cpp ├── 260. Single Number III.cpp ├── 263. Ugly Number.cpp ├── 268. Missing Number.cpp ├── 278. First Bad Version.cpp ├── 279. Perfect Squares.cpp ├── 283. Move Zeroes.cpp ├── 290. Word Pattern.cpp ├── 292. Nim Game.cpp ├── 299. Bulls and Cows.cpp ├── 300. Longest Increasing Subsequence .cpp ├── 303. Range Sum Query - Immutable.cpp ├── 304. Range Sum Query 2D - Immutable.cpp ├── 307. Range Sum Query - Mutable .cpp ├── 318. Maximum Product of Word Lengths.cpp ├── 319. Bulb Switcher.cpp ├── 322. Coin Change.cpp ├── 324. Wiggle Sort II.cpp ├── 326. Power of Three.cpp ├── 328. Odd Even Linked List.cpp ├── 33. Search in Rotated Sorted Array.cpp ├── 330. Patching Array.cpp ├── 338. Counting Bits.cpp ├── 342. Power of Four.cpp ├── 343. Integer Break.cpp ├── 344. Reverse String.cpp ├── 345. Reverse Vowels of a String.cpp ├── 349. Intersection of Two Arrays.cpp ├── 350. Intersection of Two Arrays II.cpp ├── 357. Count Numbers with Unique Digits.cpp ├── 365. Water and Jug Problem.cpp ├── 367. Valid Perfect Square.cpp ├── 371. Sum of Two Integers.cpp ├── 374. Guess Number Higher or Lower.cpp ├── 377. Combination Sum IV.cpp ├── 378. Kth Smallest Element in a Sorted Matrix.cpp ├── 382. Linked List Random Node.cpp ├── 383. Ransom Note.cpp ├── 384. Shuffle an Array.cpp ├── 386. Lexicographical Numbers.cpp ├── 387. First Unique Character in a String .cpp ├── 389. Find the Difference.cpp ├── 392. Is Subsequence.cpp ├── 396. Rotate Function.cpp ├── 398. Random Pick Index.cpp ├── 400. Nth Digit.cpp ├── 401. Binary Watch.cpp ├── 402. Remove K Digits.cpp ├── 404. Sum of Left Leaves.cpp ├── 405. Convert a Number to Hexadecimal.cpp ├── 406. Queue Reconstruction by Height.cpp ├── 409. Longest Palindrome.cpp ├── 412. Fizz Buzz .cpp ├── 413. Arithmetic Slices.cpp ├── 414. Third Maximum Number.cpp ├── 415. Add Strings .cpp ├── 419. Battleships in a Board.cpp ├── 423. Reconstruct Original Digits from English.cpp ├── 43. Multiply Strings.cpp ├── 434. Number of Segments in a String.cpp ├── 437. Path Sum III.cpp ├── 438. Find All Anagrams in a String .cpp ├── 441. Arranging Coins .cpp ├── 442. Find All Duplicates in an Array.cpp ├── 443. String Compression.cpp ├── 445. Add Two Numbers II.cpp ├── 447. Number of Boomerangs .cpp ├── 448. Find All Numbers Disappeared in an Array.cpp ├── 451. Sort Characters By Frequency.cpp ├── 453. Minimum Moves to Equal Array Elements.cpp ├── 454. 4Sum II.cpp ├── 455. Assign Cookies.cpp ├── 459. Repeated Substring Pattern .cpp ├── 461. Hamming Distance.cpp ├── 462. Minimum Moves to Equal Array Elements II.cpp ├── 463. Island Perimeter .cpp ├── 464. Can I Win.cpp ├── 468. Validate IP Address.cpp ├── 475. Heaters .cpp ├── 476. Number Complement.cpp ├── 477. Total Hamming Distance.cpp ├── 479. Largest Palindrome Product.cpp ├── 481. Magical String.cpp ├── 482. License Key Formatting.cpp ├── 485. Max Consecutive Ones.cpp ├── 486. Predict the Winner.cpp ├── 49. Group Anagrams.cpp ├── 491. Increasing Subsequences.cpp ├── 492. Construct the Rectangle.cpp ├── 494. Target Sum.cpp ├── 495. Teemo Attacking.cpp ├── 496. Next Greater Element I.cpp ├── 498. Diagonal Traverse.cpp ├── 500. Keyboard Row.cpp ├── 501. Find Mode in Binary Search Tree.cpp ├── 503. Next Greater Element II.cpp ├── 504. Base 7.cpp ├── 506. Relative Ranks.cpp ├── 507. Perfect Number.cpp ├── 508. Most Frequent Subtree Sum.cpp ├── 513. Find Bottom Left Tree Value.cpp ├── 515. Find Largest Value in Each Tree Row.cpp ├── 516. Longest Palindromic Subsequence.cpp ├── 520. Detect Capital.cpp ├── 521. Longest Uncommon Subsequence I.cpp ├── 524. Longest Word in Dictionary through Deleting.cpp ├── 525. Contiguous Array.cpp ├── 526. Beautiful Arrangement.cpp ├── 530. Minimum Absolute Difference in BST.cpp ├── 532. K-diff Pairs in an Array.cpp ├── 537. Complex Number Multiplication.cpp ├── 538. Convert BST to Greater Tree.cpp ├── 541. Reverse String II.cpp ├── 543. Diameter of Binary Tree.cpp ├── 547. Friend Circles.cpp ├── 551. Student Attendance Record I.cpp ├── 553. Optimal Division.cpp ├── 557. Reverse Words in a String III.cpp ├── 561. Array Partition I.cpp ├── 563. Binary Tree Tilt.cpp ├── 566. Reshape the Matrix.cpp ├── 572. Subtree of Another Tree.cpp ├── 575. Distribute Candies.cpp ├── 581. Shortest Unsorted Continuous Subarray.cpp ├── 599. Minimum Index Sum of Two Lists.cpp ├── 628. Maximum Product of Three Numbers.cpp ├── 633. Sum of Square Numbers.cpp ├── 637. Average of Levels in Binary Tree.cpp ├── 643. Maximum Average Subarray I.cpp ├── 647. Palindromic Substrings.cpp ├── 650. 2 Keys Keyboard.cpp ├── 653. Two Sum IV - Input is a BST.cpp ├── 654. Maximum Binary Tree.cpp ├── 655. Print Binary Tree.cpp ├── 657. Judge Route Circle.cpp ├── 671. Second Minimum Node In a Binary Tree.cpp ├── 674. Longest Continuous Increasing Subsequence.cpp ├── 695. Max Area of Island.cpp ├── 717. 1-bit and 2-bit Characters.cpp ├── 724. Find Pivot Index.cpp ├── 728. Self Dividing Numbers.cpp ├── 733. Flood Fill.cpp ├── 739. Daily Temperatures.cpp ├── 740. Delete and Earn.cpp ├── 744. Find Smallest Letter Greater Than Target.cpp ├── 746. Min Cost Climbing Stairs.cpp ├── 747. Largest Number At Least Twice of Others.cpp ├── 760. Find Anagram Mappings.cpp ├── 762. Prime Number of Set Bits in Binary Representation.cpp ├── 763. Partition Labels.cpp ├── 766. Toeplitz Matrix.cpp ├── 768. Max Chunks To Make Sorted II.cpp ├── 769. Max Chunks To Make Sorted.cpp ├── 771. Jewels and Stones.cpp ├── 775. Global and Local Inversions.cpp └── 779. K-th Symbol in Grammar.cpp ├── README.md └── Swift ├── 100. Same Tree.swift ├── 101 Symmetric Tree.swift ├── 102. Binary Tree Level Order Traversal.swift ├── 104. Maximum Depth of Binary Tree.swift ├── 114. Flatten Binary Tree to Linked List.swift ├── 121. Best Time to Buy and Sell Stock.swift ├── 136. Single Number.swift ├── 148. Sort List.swift ├── 152. Maximum Product Subarray.swift ├── 169. Majority Element.swift ├── 198. House Robber.swift ├── 20. Valid Parentheses.swift ├── 206. Reverse Linked List.swift ├── 21. Merge Two Sorted Lists.swift ├── 215. Kth Largest Element in an Array.swift ├── 23. Merge k Sorted Lists.swift ├── 234. Palindrome Linked List.swift ├── 283. Move Zeroes.swift ├── 287. Find the Duplicate Number.swift ├── 338. Counting Bits.swift ├── 347. Top K Frequent Elements.swift ├── 35. Search Insert Position.swift ├── 394. Decode String.swift ├── 437. Path Sum III.swift ├── 438. Find All Anagrams in a String.swift ├── 448. Find All Numbers Disappeared in an Array.swift ├── 461. Hamming Distance.swift ├── 49. Group Anagrams.swift ├── 53. Maximum Subarray.swift ├── 538. Convert BST to Greater Tree.swift ├── 543. Diameter of Binary Tree.swift ├── 572. Subtree of Another Tree.swift ├── 581. Shortest Unsorted Continuous Subarray.swift ├── 617. Merge Two Binary Trees.swift ├── 62. Unique Paths.swift ├── 657. Judge Route Circle.swift ├── 695. Max Area of Island.swift ├── 70. Climbing Stairs.swift ├── 709. To Lower Case.swift ├── 75. Sort Colors.swift ├── 771. Jewels and Stones.swift ├── 804. Unique Morse Code Words.swift ├── 832. Flipping an Image.swift ├── 94. Binary Tree Inorder Traversal.swift ├── 96. Unique Binary Search Trees.swift └── 98. Validate Binary Search Tree.swift /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | .DS_Store 3 | -------------------------------------------------------------------------------- /C++/001. Two Sum.cpp: -------------------------------------------------------------------------------- 1 | 1. Two Sum 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 214750 Total Submissions: 948309 Difficulty: Easy 4 | Given an array of integers, return indices of the two numbers such that they add up to a specific target. 5 | 6 | You may assume that each input would have exactly one solution. 7 | 8 | Example: 9 | Given nums = [2, 7, 11, 15], target = 9, 10 | 11 | Because nums[0] + nums[1] = 2 + 7 = 9, 12 | return [0, 1]. 13 | UPDATE (2016/2/13): 14 | The return format had been changed to zero-based indices. Please read the above updated description carefully. 15 | 16 | Subscribe to see which companies asked this question 17 | 18 | 19 | 20 | 21 | class Solution { 22 | public: 23 | vector twoSum(vector& nums, int target) { 24 | vector v(2); 25 | for(int i = 0; i < nums.size(); i++) { 26 | for(int j = i + 1; j < nums.size(); j++) { 27 | if(nums[i] + nums[j] == target) { 28 | v[0] = i; 29 | v[1] = j; 30 | } 31 | } 32 | } 33 | return v; 34 | } 35 | }; -------------------------------------------------------------------------------- /C++/006. ZigZag Conversion.cpp: -------------------------------------------------------------------------------- 1 | 6. ZigZag Conversion 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 85965 Total Submissions: 358722 Difficulty: Easy 4 | The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) 5 | 6 | P A H N 7 | A P L S I I G 8 | Y I R 9 | And then read line by line: "PAHNAPLSIIGYIR" 10 | Write the code that will take a string and make this conversion given a number of rows: 11 | 12 | string convert(string text, int nRows); 13 | convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". 14 | Subscribe to see which companies asked this question 15 | 16 | 17 | class Solution { 18 | public: 19 | string convert(string s, int numRows) { 20 | string t[numRows]; 21 | string ans; 22 | int i = 0; 23 | while(i < s.length()) { 24 | for(int j = 0; j < numRows && i < s.length(); j++) 25 | t[j] += s[i++]; 26 | for(int k = numRows - 2; k > 0 && i < s.length(); k--) 27 | t[k] += s[i++]; 28 | } 29 | for(int j = 0; j < numRows; j++) { 30 | ans += t[j]; 31 | } 32 | return ans; 33 | } 34 | }; -------------------------------------------------------------------------------- /C++/009. Palindrome Number.cpp: -------------------------------------------------------------------------------- 1 | 9. Palindrome Number 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 117710 Total Submissions: 374088 Difficulty: Easy 4 | Determine whether an integer is a palindrome. Do this without extra space. 5 | 6 | click to show spoilers. 7 | 8 | Some hints: 9 | Could negative integers be palindromes? (ie, -1) 10 | 11 | If you are thinking of converting the integer to string, note the restriction of using extra space. 12 | 13 | You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case? 14 | 15 | There is a more generic way of solving this problem. 16 | 17 | 18 | Subscribe to see which companies asked this question 19 | 20 | 21 | class Solution { 22 | public: 23 | bool isPalindrome(int x) { 24 | if(x < 0) 25 | return false; 26 | int len = 1; 27 | while(x / len >= 10) { 28 | len = len * 10; 29 | } 30 | while(x) { 31 | int left = x / len; 32 | int right = x % 10; 33 | if(left != right) { 34 | return false; 35 | } 36 | x = x % len; 37 | x = x / 10; 38 | len = len / 100; 39 | } 40 | return true; 41 | } 42 | }; -------------------------------------------------------------------------------- /C++/011. Container With Most Water.cpp: -------------------------------------------------------------------------------- 1 | 11. Container With Most Water 2 | 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. 3 | 4 | Note: You may not slant the container and n is at least 2. 5 | 6 | 题目大意:给出一个数组height, height[i] = j表示横坐标为i处的高为j,以(i, j)与x轴作垂线段,计算两条垂线段和x轴组成的容器能装的最多的水的容量是多少~ 7 | 分析:容器两条边中取最短的那条边为影响容器容积的高,所以说,我们先假设left和right分别在最左边最右边,要想求得容器容积的最大值,需要考虑改变最短边的高度,如果左边短就让left++,如果右边短就让right--,直到直到一个area容积最大的值返回~ 8 | 9 | class Solution { 10 | public: 11 | int maxArea(vector& height) { 12 | int left = 0, right = height.size() - 1, area = 0; 13 | while(left < right) { 14 | area = max(area, min(height[left], height[right]) * (right - left)); 15 | if(height[left] < height[right]) 16 | left++; 17 | else 18 | right--; 19 | } 20 | return area; 21 | } 22 | }; -------------------------------------------------------------------------------- /C++/012. Integer to Roman.cpp: -------------------------------------------------------------------------------- 1 | 12. Integer to Roman 2 | Given an integer, convert it to a roman numeral. 3 | 4 | Input is guaranteed to be within the range from 1 to 3999. 5 | 6 | 题目大意:将一个整数转化为罗马数字表示法~ 7 | 分析:根据罗马数字的表示方法,我们直到罗马字符有"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"这几种,分别对应1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1。如果在这些数字之间的,比如3,那就重复3次写1:III。 8 | 所以只需要按照罗马数字表示的从大到小顺序,当num比a[i]大的时候,cnt = num / a[i],就将b[i]连接在result字符串后面cnt次。每一次循环将num取余a[i],直到num<=0为止~ 9 | 10 | class Solution { 11 | public: 12 | string intToRoman(int num) { 13 | string result = ""; 14 | int a[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; 15 | string b[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; 16 | int index = 0, cnt; 17 | while(num > 0) { 18 | cnt = num / a[index]; 19 | while(cnt--) 20 | result += b[index]; 21 | num = num % a[index]; 22 | index++; 23 | } 24 | return result; 25 | } 26 | }; -------------------------------------------------------------------------------- /C++/013. Roman to Integer.cpp: -------------------------------------------------------------------------------- 1 | 13. Roman to Integer 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 80246 Total Submissions: 205709 Difficulty: Easy 4 | Given a roman numeral, convert it to an integer. 5 | 6 | Input is guaranteed to be within the range from 1 to 3999. 7 | 8 | Subscribe to see which companies asked this question 9 | 10 | class Solution { 11 | public: 12 | int romanToInt(string s) { 13 | int ans = 0; 14 | map m; 15 | char c[] = {'I', 'V', 'X', 'L', 'C', 'D', 'M'}; 16 | int t[] = {1, 5, 10, 50, 100, 500, 1000}; 17 | for(int i = 0; i < 7; i++) { 18 | m.insert(pair (c[i], t[i])); 19 | } 20 | for(int i = 0; i < s.length() - 1; i++) { 21 | if(m[s[i]] >= m[s[i + 1]]) { 22 | ans = ans + m[s[i]]; 23 | } else { 24 | ans = ans - m[s[i]]; 25 | } 26 | } 27 | ans = ans + m[s[s.length() - 1]]; 28 | return ans; 29 | } 30 | }; -------------------------------------------------------------------------------- /C++/014. Longest Common Prefix.cpp: -------------------------------------------------------------------------------- 1 | 14. Longest Common Prefix 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 96364 Total Submissions: 343735 Difficulty: Easy 4 | Write a function to find the longest common prefix string amongst an array of strings. 5 | 6 | Subscribe to see which companies asked this question 7 | 8 | 9 | class Solution { 10 | public: 11 | string longestCommonPrefix(vector& strs) { 12 | if(strs.size() == 0) 13 | return ""; 14 | string s = strs[0]; 15 | for(int i = 1; i < strs.size(); i++) { 16 | for(int j = 0; j < s.length(); j++) { 17 | if(s[j] != strs[i][j]) { 18 | s = s.substr(0, j); 19 | break; 20 | } 21 | } 22 | } 23 | return s; 24 | } 25 | }; -------------------------------------------------------------------------------- /C++/020. Valid Parentheses.cpp: -------------------------------------------------------------------------------- 1 | 20. Valid Parentheses 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 103858 Total Submissions: 355021 Difficulty: Easy 4 | Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 5 | 6 | The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. 7 | 8 | Subscribe to see which companies asked this question 9 | 10 | 11 | class Solution { 12 | public: 13 | bool isValid(string s) { 14 | stack t; 15 | for(int i = 0; i < s.length(); i++) { 16 | if(s[i] == '(' || s[i] == '[' || s[i] == '{') { 17 | t.push(s[i]); 18 | } else if(s[i] == ')') { 19 | if(i == 0 || t.empty() || t.top() != '(') { 20 | return false; 21 | } 22 | t.pop(); 23 | } else if(s[i] == ']') { 24 | if(i == 0 || t.empty() || t.top() != '[') { 25 | return false; 26 | } 27 | t.pop(); 28 | } else if(s[i] == '}') { 29 | if(i == 0 || t.empty() || t.top() != '{') { 30 | return false; 31 | } 32 | t.pop(); 33 | } 34 | } 35 | return t.empty(); 36 | } 37 | }; -------------------------------------------------------------------------------- /C++/022. Generate Parentheses.cpp: -------------------------------------------------------------------------------- 1 | 22. Generate Parentheses 2 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 3 | 4 | For example, given n = 3, a solution set is: 5 | 6 | [ 7 | "((()))", 8 | "(()())", 9 | "(())()", 10 | "()(())", 11 | "()()()" 12 | ] 13 | 14 | 题目大意:给n对括号,写一个方法,生成所有格式正确的括号组合~ 15 | 分析:left表示还剩余的左括号个数,right表示目前需要的右括号数~一开始left = n,right = 0;当left还剩余左括号数大于0的时候,添加左括号,并将left - 1,right + 1;当right目前还需要的右括号数大于0的时候,添加右括号,并将right - 1~当left和right都等于0的时候,表示当前是一个符合格式条件的字符串,将该字符串cur放入result数组中,最后返回result~ 16 | 17 | class Solution { 18 | public: 19 | vector generateParenthesis(int n) { 20 | dfs("", n, 0); 21 | return result; 22 | } 23 | private: 24 | vector result; 25 | void dfs(string cur, int left, int right) { 26 | if (left == 0 && right == 0) { 27 | result.push_back(cur); 28 | return; 29 | } 30 | if (left > 0) dfs(cur + "(", left - 1, right + 1); 31 | if (right > 0) dfs(cur + ")", left, right - 1); 32 | } 33 | }; -------------------------------------------------------------------------------- /C++/026. Remove Duplicates from Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | 26. Remove Duplicates from Sorted Array 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 123663 Total Submissions: 371141 Difficulty: Easy 4 | Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. 5 | 6 | Do not allocate extra space for another array, you must do this in place with constant memory. 7 | 8 | For example, 9 | Given input array nums = [1,1,2], 10 | 11 | Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It does not matter what you leave beyond the new length. 12 | 13 | //才明白这类题目的意思是 返回的是 length 的值 但是会检验你是不是删除了相同的数字使得符合条件。。然后他检验的时候输出的只是0~length-1的值。。后面的是否符合不用管。。。 14 | class Solution { 15 | public: 16 | int removeDuplicates(vector& nums) { 17 | if(nums.size() == 0) { 18 | return 0; 19 | } 20 | int len = 1; 21 | for(int i = 1; i < nums.size(); i++) { 22 | if(nums[i] != nums[i - 1]) { 23 | nums[len++] = nums[i]; 24 | } 25 | } 26 | return len; 27 | } 28 | }; -------------------------------------------------------------------------------- /C++/027. Remove Element.cpp: -------------------------------------------------------------------------------- 1 | 27. Remove Element 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 111459 Total Submissions: 332345 Difficulty: Easy 4 | Given an array and a value, remove all instances of that value in place and return the new length. 5 | 6 | Do not allocate extra space for another array, you must do this in place with constant memory. 7 | 8 | The order of elements can be changed. It does not matter what you leave beyond the new length. 9 | 10 | Example: 11 | Given input array nums = [3,2,2,3], val = 3 12 | 13 | Your function should return length = 2, with the first two elements of nums being 2. 14 | 15 | 16 | 17 | class Solution { 18 | public: 19 | int removeElement(vector& nums, int val) { 20 | int len = 0; 21 | for(int i = 0; i < nums.size(); i++) { 22 | if(nums[i] != val) { 23 | nums[len++] = nums[i]; 24 | } 25 | } 26 | return len; 27 | } 28 | }; -------------------------------------------------------------------------------- /C++/028. Implement strStr().cpp: -------------------------------------------------------------------------------- 1 | 28. Implement strStr() 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 103132 Total Submissions: 415629 Difficulty: Easy 4 | Implement strStr(). 5 | 6 | Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 7 | 8 | Subscribe to see which companies asked this question 9 | 10 | 11 | class Solution { 12 | public: 13 | int strStr(string haystack, string needle) { 14 | int len1 = haystack.length(); 15 | int len2 = needle.length(); 16 | if(len2 == 0) 17 | return 0; 18 | for(int i = 0; i <= len1 - len2; i++) { 19 | for(int j = 0; j < len2 && needle[j] == haystack[i + j]; j++) { 20 | if(j == len2 - 1) 21 | return i; 22 | } 23 | } 24 | return -1; 25 | } 26 | }; -------------------------------------------------------------------------------- /C++/029. Divide Two Integers.cpp: -------------------------------------------------------------------------------- 1 | 29. Divide Two Integers 2 | Divide two integers without using multiplication, division and mod operator. 3 | 4 | If it is overflow, return MAX_INT. 5 | 6 | 题目大意:不用乘法、除法、取余操作,将两个数相除,如果它溢出了,返回MAX_INT~ 7 | 分析:我用了减法和log函数。。就是e的(loga-logb)次方等于e的log(a/b) = a/b。。。。这应该不算投机取巧吧?。。。~ 8 | 9 | class Solution { 10 | public: 11 | int divide(int dividend, int divisor) { 12 | if(divisor == 0 || dividend == INT_MIN && divisor == -1) return INT_MAX; 13 | int sign = ((dividend >> 31) ^ (divisor >> 31)) == 0 ? 1 : -1; 14 | long a = abs((long)dividend); 15 | long b = abs((long)divisor); 16 | double c = exp(log(a) - log(b)) + 0.0000000001; 17 | return (int)(sign * c); 18 | } 19 | }; -------------------------------------------------------------------------------- /C++/031. Next Permutation.cpp: -------------------------------------------------------------------------------- 1 | 31. Next Permutation 2 | Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. 3 | 4 | If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). 5 | 6 | The replacement must be in-place, do not allocate extra memory. 7 | 8 | Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. 9 | 1,2,3 → 1,3,2 10 | 3,2,1 → 1,2,3 11 | 1,1,5 → 1,5,1 12 | 13 | 题目大意:实现下一个排列,也就是按照字典序的下一个比它大的排列~ 14 | 分析:用C++库函数作个弊。。。 15 | 16 | class Solution { 17 | public: 18 | void nextPermutation(vector& nums) { 19 | next_permutation(nums.begin(), nums.end()); 20 | } 21 | }; -------------------------------------------------------------------------------- /C++/035. Search Insert Position.cpp: -------------------------------------------------------------------------------- 1 | 35. Search Insert Position 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 101847 Total Submissions: 273775 Difficulty: Medium 4 | Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. 5 | 6 | You may assume no duplicates in the array. 7 | 8 | Here are few examples. 9 | [1,3,5,6], 5 → 2 10 | [1,3,5,6], 2 → 1 11 | [1,3,5,6], 7 → 4 12 | [1,3,5,6], 0 → 0 13 | 14 | class Solution { 15 | public: 16 | int searchInsert(vector& nums, int target) { 17 | for(int i = 0; i < nums.size(); i++) { 18 | if(nums[i] >= target) { 19 | return i; 20 | } 21 | if(i == nums.size() - 1) { 22 | return nums.size(); 23 | } 24 | } 25 | } 26 | }; 27 | 28 | 29 | -------------------------------------------------------------------------------- /C++/046. Permutations.cpp: -------------------------------------------------------------------------------- 1 | 46. Permutations 2 | Given a collection of distinct numbers, return all possible permutations. 3 | 4 | For example, 5 | [1,2,3] have the following permutations: 6 | [ 7 | [1,2,3], 8 | [1,3,2], 9 | [2,1,3], 10 | [2,3,1], 11 | [3,1,2], 12 | [3,2,1] 13 | ] 14 | 15 | 题目大意:给一个不同数字的集合,返回它的所有可能的排列~ 16 | 分析:对nums进行排序,然后将所有全排列结果放入result数组中返回~ 17 | 18 | class Solution { 19 | public: 20 | vector> permute(vector& nums) { 21 | vector> result; 22 | sort(nums.begin(), nums.end()); 23 | do { 24 | result.push_back(nums); 25 | } while (next_permutation(nums.begin(), nums.end())); 26 | return result; 27 | } 28 | }; -------------------------------------------------------------------------------- /C++/047. Permutations II.cpp: -------------------------------------------------------------------------------- 1 | 47. Permutations II 2 | Given a collection of numbers that might contain duplicates, return all possible unique permutations. 3 | 4 | For example, 5 | [1,1,2] have the following unique permutations: 6 | [ 7 | [1,1,2], 8 | [1,2,1], 9 | [2,1,1] 10 | ] 11 | 12 | 题目大意:返回一个数字集合构成的数字(可能有重复数字)的所有可能的唯一的全排列~ 13 | 分析:先对nums排序,然后将所有全排列加入result中~ 14 | 15 | class Solution { 16 | public: 17 | vector> permuteUnique(vector& nums) { 18 | vector> result; 19 | sort(nums.begin(), nums.end()); 20 | do { 21 | result.push_back(nums); 22 | } while (next_permutation(nums.begin(), nums.end())); 23 | return result; 24 | } 25 | }; -------------------------------------------------------------------------------- /C++/048. Rotate Image.cpp: -------------------------------------------------------------------------------- 1 | 48. Rotate Image 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 65299 Total Submissions: 189246 Difficulty: Medium 4 | You are given an n x n 2D matrix representing an image. 5 | 6 | Rotate the image by 90 degrees (clockwise). 7 | 8 | Follow up: 9 | Could you do this in-place? 10 | 11 | Subscribe to see which companies asked this question 12 | 13 | 14 | //原地旋转90度。 15 | //1.沿主对角线所有元素交换 16 | //2.沿着垂直中轴线方向所有元素交换 17 | 18 | class Solution { 19 | public: 20 | void rotate(vector>& matrix) { 21 | for(int i = 0; i < matrix.size(); i++) 22 | for(int j = 0; j <= i; j++) 23 | swap(matrix[i][j], matrix[j][i]); 24 | 25 | for(int i = 0, j = matrix.size() - 1; i < j; i++, j--) 26 | for(int k = 0; k < matrix.size(); k++) 27 | swap(matrix[k][i], matrix[k][j]); 28 | } 29 | }; -------------------------------------------------------------------------------- /C++/052. N-Queens II.cpp: -------------------------------------------------------------------------------- 1 | 52. N-Queens II 2 | Follow up for N-Queens problem. 3 | Now, instead outputting board configurations, return the total number of distinct solutions. 4 | 分析:和LeetCode 51. N-Queens一样,只需改动几行代码即可~ 5 | 6 | class Solution { 7 | int cnt = 0; 8 | public: 9 | int totalNQueens(int n) { 10 | vector pos(n); 11 | dfs(pos, n, 0); 12 | return cnt; 13 | } 14 | private: 15 | void dfs(vector &pos, int n, int row) { 16 | if(row == n) { 17 | cnt++; 18 | return ; 19 | } 20 | for(pos[row] = 0; pos[row] < n; pos[row]++) { 21 | if(issafe(pos, n, row)) { 22 | dfs(pos, n, row + 1); 23 | } 24 | } 25 | } 26 | 27 | bool issafe(vector &pos, int n, int row) { 28 | for(int i = 0; i < row; i++) 29 | if(pos[i] == pos[row] || abs(i - row) == abs(pos[i] - pos[row])) 30 | return false; 31 | return true; 32 | } 33 | }; -------------------------------------------------------------------------------- /C++/054. Spiral Matrix.cpp: -------------------------------------------------------------------------------- 1 | 54. Spiral Matrix 2 | Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. 3 | 4 | For example, 5 | Given the following matrix: 6 | 7 | [ 8 | [ 1, 2, 3 ], 9 | [ 4, 5, 6 ], 10 | [ 7, 8, 9 ] 11 | ] 12 | You should return [1,2,3,6,9,8,7,4,5]. 13 | 题目大意:给一个m*n的矩阵,以顺时针旋转的方式返回所有的元素到一个数组中~ 14 | 分析:按照一个个矩阵的边框输出:x、m为行的上下界,y、n为列的上下界,每次输出这个围成的矩阵的第一行——最后一列——最后一行——第一列,然后将x和y自增1,m和n自减1~ 15 | 注意:为了避免重复输出,当x和m相等或者y和n相等的时候,就输出一次第一行和最后一列就可以,不用重复输出最后一行和第一列~ 16 | 17 | class Solution { 18 | public: 19 | vector spiralOrder(vector>& matrix) { 20 | vector result; 21 | if(matrix.empty()) return result; 22 | int m = matrix.size() - 1, n = matrix[0].size() - 1; 23 | for (int x = 0, y = 0; x <= m && y <= n; x++, y++, m--, n--) { 24 | for (int j = y; j <= n; j++) 25 | result.push_back(matrix[x][j]); 26 | for (int i = x + 1; i <= m - 1; i++) 27 | result.push_back(matrix[i][n]); 28 | for (int j = n; j >= y && x != m; j--) 29 | result.push_back(matrix[m][j]); 30 | for (int i = m - 1; i > x && y != n; i--) 31 | result.push_back(matrix[i][y]); 32 | } 33 | return result; 34 | } 35 | }; -------------------------------------------------------------------------------- /C++/055. Jump Game.cpp: -------------------------------------------------------------------------------- 1 | 55. Jump Game 2 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 3 | Each element in the array represents your maximum jump length at that position. 4 | Determine if you are able to reach the last index. 5 | For example: 6 | A = [2,3,1,1,4], return true. 7 | A = [3,2,1,0,4], return false. 8 | 题目解释: 9 | 从下标为0的地方开始,A[i]表示当前i处能够跳跃的最大长度。(也就是也就是i处最远能跳到下标i + nums[i]处。)判断能不能跳啊跳到最后一个下标的地方。 10 | 分析:设立distance为当处在i下标的时候,前面所能够达到的所有长度的最大值(因为是最大值,所以0~最大值的所有下标都可以遍历到),当i <= distance的所有下标都可以遍历,然后更新distance的值为distance = max(distance, i + nums[i]); 11 | 最后判断能够最远到达的distance是否够的到最后一个下标n-1,不能的话返回false,能的话返回true 12 | 13 | class Solution { 14 | public: 15 | bool canJump(vector& nums) { 16 | int distance = 0; 17 | for(int i = 0; i < nums.size() - 1 && i <= distance; i++) { 18 | distance = max(distance, i + nums[i]); 19 | } 20 | return distance >= (nums.size() - 1); 21 | } 22 | }; -------------------------------------------------------------------------------- /C++/056. Merge Intervals.cpp: -------------------------------------------------------------------------------- 1 | 56. Merge Intervals 2 | Given a collection of intervals, merge all overlapping intervals. 3 | 4 | For example, 5 | Given [1,3],[2,6],[8,10],[15,18], 6 | return [1,6],[8,10],[15,18]. 7 | 8 | 题目大意:给一组区间,合并他们所有的重叠区间 9 | 分析:先对所有区间按左区间从小到大排序,排序后将第一个区间放入ans结果数组中,遍历原数组,如果当前ans数组的最后一个区间的end小于intervals[i]的start,说明与其没有交集,那么就将这个intervals[i]放入结果数组中。否则说明有交集,就将当前ans数组的最后一个区间的end更新为ans.back().end和intervals[i].end()中较大的那一个,最后返回ans数组即为所求~注意如果intervals中不含元素要返回空集 10 | 11 | 12 | /** 13 | * Definition for an interval. 14 | * struct Interval { 15 | * int start; 16 | * int end; 17 | * Interval() : start(0), end(0) {} 18 | * Interval(int s, int e) : start(s), end(e) {} 19 | * }; 20 | */ 21 | class Solution { 22 | public: 23 | vector merge(vector& intervals) { 24 | vector ans; 25 | if (intervals.size() == 0) return ans; 26 | sort(intervals.begin(), intervals.end(), [](Interval a, Interval b){return a.start < b.start;}); 27 | ans.push_back(intervals[0]); 28 | for (int i = 1; i < intervals.size(); i++) { 29 | if(ans.back().end < intervals[i].start) 30 | ans.push_back(intervals[i]); 31 | else 32 | ans.back().end = max(ans.back().end, intervals[i].end); 33 | } 34 | return ans; 35 | } 36 | }; -------------------------------------------------------------------------------- /C++/058. Length of Last Word.cpp: -------------------------------------------------------------------------------- 1 | 58. Length of Last Word 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 90032 Total Submissions: 308380 Difficulty: Easy 4 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. 5 | 6 | If the last word does not exist, return 0. 7 | 8 | Note: A word is defined as a character sequence consists of non-space characters only. 9 | 10 | For example, 11 | Given s = "Hello World", 12 | return 5. 13 | 14 | Subscribe to see which companies asked this question 15 | 16 | 17 | 18 | class Solution { 19 | public: 20 | int lengthOfLastWord(string s) { 21 | int cnt = 0; 22 | int flag = 0; 23 | for(int i = s.length() - 1; i >= 0; i--) { 24 | if(flag == 0 && s[i] == ' ') { 25 | continue; 26 | } 27 | if(s[i] != ' ') { 28 | flag = 1; 29 | cnt++; 30 | } else { 31 | break; 32 | } 33 | } 34 | return cnt; 35 | } 36 | }; -------------------------------------------------------------------------------- /C++/059. Spiral Matrix II.cpp: -------------------------------------------------------------------------------- 1 | 59. Spiral Matrix II 2 | Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. 3 | 4 | For example, 5 | Given n = 3, 6 | 7 | You should return the following matrix: 8 | [ 9 | [ 1, 2, 3 ], 10 | [ 8, 9, 4 ], 11 | [ 7, 6, 5 ] 12 | ] 13 | 14 | 题目大意:给一个n,输出一个n*n的数组,并且按照螺旋的方式填充入数字1~n*n。 15 | 分析:按照一个个矩阵的边框输入:x为矩阵的上界,n为矩阵的上界,每次输出这个围成的矩阵的第一行——最后一列——最后一行——第一列,然后将x自增1,m自减1~ 16 | 注意:为了避免重复输出,当x和n相等的时候,就输入一次第一行和最后一列就可以,不用重复输入最后一行和第一列~ 17 | 18 | class Solution { 19 | public: 20 | vector> generateMatrix(int n) { 21 | vector> result(n, vector(n)); 22 | n = n - 1; 23 | int num = 1; 24 | for (int x = 0; x <= n; x++, n--) { 25 | for (int j = x; j <= n; j++) 26 | result[x][j] = num++; 27 | for (int i = x + 1; i <= n - 1; i++) 28 | result[i][n] = num++; 29 | for (int j = n; j >= x && x != n; j--) 30 | result[n][j] = num++; 31 | for (int i = n - 1; i >= x + 1 && x != n; i--) 32 | result[i][x] = num++; 33 | } 34 | return result; 35 | } 36 | }; -------------------------------------------------------------------------------- /C++/060. Permutation Sequence.cpp: -------------------------------------------------------------------------------- 1 | 60. Permutation Sequence 2 | The set [1,2,3,…,n] contains a total of n! unique permutations. 3 | By listing and labeling all of the permutations in order, 4 | We get the following sequence (ie, for n = 3): 5 | "123" 6 | "132" 7 | "213" 8 | "231" 9 | "312" 10 | "321" 11 | Given n and k, return the kth permutation sequence. 12 | 13 | 题目大意:返回1, 2, 3...n的第k个全排列~ 14 | 分析:result一开始为1 2 3 4 ... n,用C++库函数,当到第k个全排列的时候返回result~ 15 | 16 | class Solution { 17 | public: 18 | string getPermutation(int n, int k) { 19 | string result = ""; 20 | for (int i = 1; i <= n; i++) 21 | result += to_string(i); 22 | do { 23 | k--; 24 | } while (k > 0 && next_permutation(result.begin(), result.end())); 25 | return result; 26 | } 27 | }; -------------------------------------------------------------------------------- /C++/061. Rotate List.cpp: -------------------------------------------------------------------------------- 1 | 61. Rotate List 2 | Given a list, rotate the list to the right by k places, where k is non-negative. 3 | 4 | For example: 5 | Given 1->2->3->4->5->NULL and k = 2, 6 | return 4->5->1->2->3->NULL. 7 | 8 | 题目大意:将一个链表向右循环k次,返回这个链表~ 9 | 分析:计算出整个链表的长度len,如果要向右循环k次,则新的head指针应该在往右移动len - k % len处。(如果向右移动的距离moveDistance == len,那么直接返回head即可),newhead之前的一个指针的next应为NULL。并且尾部NULL前的tail指针处,tail的next应该为原来的head,最后返回newhead~ 10 | 11 | /** 12 | * Definition for singly-linked list. 13 | * struct ListNode { 14 | * int val; 15 | * ListNode *next; 16 | * ListNode(int x) : val(x), next(NULL) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | ListNode* rotateRight(ListNode* head, int k) { 22 | if (head == NULL) return head; 23 | int len = 0; 24 | ListNode *newhead = head, *tail = head, *p = head; 25 | while (p != NULL) { 26 | if (p->next == NULL) 27 | tail = p; 28 | len++; 29 | p = p->next; 30 | } 31 | int moveDistance = len - k % len; 32 | if (moveDistance == len) return head; 33 | for (int i = 0; i < moveDistance - 1; i++) { 34 | newhead = newhead->next; 35 | } 36 | ListNode *temp = newhead; 37 | newhead = newhead->next; 38 | temp->next = NULL; 39 | tail->next = head; 40 | return newhead; 41 | } 42 | }; -------------------------------------------------------------------------------- /C++/062. Unique Paths.cpp: -------------------------------------------------------------------------------- 1 | 62. Unique Paths 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 84185 Total Submissions: 233521 Difficulty: Medium 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 | 11 | Above is a 3 x 7 grid. How many possible unique paths are there? 12 | 13 | Note: m and n will be at most 100. 14 | 15 | Subscribe to see which companies asked this question 16 | 17 | 18 | class Solution { 19 | public: 20 | int uniquePaths(int m, int n) { 21 | int a[100][100]; 22 | for(int i = 0; i < m; i++) { 23 | for(int j = 0; j < n; j++) { 24 | if(i == 0 || j == 0) 25 | a[i][j] = 1; 26 | else 27 | a[i][j] = a[i - 1][j] + a[i][j - 1]; 28 | } 29 | } 30 | return a[m - 1][n - 1]; 31 | } 32 | }; -------------------------------------------------------------------------------- /C++/066. Plus One.cpp: -------------------------------------------------------------------------------- 1 | 66. Plus One 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 94851 Total Submissions: 284653 Difficulty: Easy 4 | Given a non-negative number represented as an array of digits, plus one to the number. 5 | 6 | The digits are stored such that the most significant digit is at the head of the list. 7 | 8 | Subscribe to see which companies asked this question 9 | 10 | 11 | 12 | class Solution { 13 | public: 14 | vector plusOne(vector& digits) { 15 | for(int i = digits.size() - 1; i >= 0; i--) { 16 | if(digits[i] != 9) { 17 | digits[i] = digits[i] + 1; 18 | return digits; 19 | } else { 20 | digits[i] = 0; 21 | } 22 | } 23 | digits.insert(digits.begin(), 1); 24 | 25 | return digits; 26 | 27 | } 28 | }; -------------------------------------------------------------------------------- /C++/069. Sqrt(x).cpp: -------------------------------------------------------------------------------- 1 | 69. Sqrt(x) 2 | Implement int sqrt(int x). 3 | Compute and return the square root of x. 4 | 5 | 题目大意:实现sqrt函数,返回x的sqrt结果(int型) 6 | 分析:二分法,令left = 0, right为int最大值,mid为left和right的中间值。始终保持要求的值在left和right之间。进入循环——如果mid的平方小于等于x并且mid+1的平方大于等于x则返回mid~否则:如果mid的平方小于x,说明答案在mid的右边,left = mid + 1,mid的平方大于x,说明答案在mid的左边,right = mid - 1~ 7 | 注意:令left、right、mid都是long型因为为了避免mid*mid的结果超出整型范围~ 8 | 9 | class Solution { 10 | public: 11 | int mySqrt(int x) { 12 | long left = 0, right = INT_MAX, mid = 0; 13 | while (true) { 14 | long mid = left + (right - left) / 2; 15 | if (mid * mid <= x && (mid + 1) * (mid + 1) > x) 16 | return (int)mid; 17 | if (mid * mid < x) 18 | left = mid + 1; 19 | else 20 | right = mid - 1; 21 | } 22 | } 23 | }; -------------------------------------------------------------------------------- /C++/070. Climbing Stairs.cpp: -------------------------------------------------------------------------------- 1 | 70. Climbing Stairs 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 103040 Total Submissions: 281923 Difficulty: Easy 4 | You are climbing a stair case. It takes n steps to reach to the top. 5 | 6 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 7 | 8 | Subscribe to see which companies asked this question 9 | 10 | class Solution { 11 | public: 12 | int climbStairs(int n) { 13 | int *a = new int [n + 1]; 14 | a[0] = 1; 15 | a[1] = 1; 16 | for(int i = 2; i <= n; i++) { 17 | a[i] = a[i - 1] + a[i - 2]; 18 | } 19 | return a[n]; 20 | } 21 | }; 22 | 23 | //一开始我写了个Fibonacci递归,在n = 44 时候超时了 24 | class Solution { 25 | public: 26 | int climbStairs(int n) { 27 | if(n == 1 || n == 2) 28 | return n; 29 | return climbStairs(n - 1) + climbStairs(n - 2); 30 | } 31 | }; 32 | 33 | //最最一开始我用的最原始的递归, 在 n=38的时候超时了 34 | class Solution { 35 | public: 36 | int ans = 0; 37 | int climbStairs(int n) { 38 | if(n == 0) { 39 | ans++; 40 | return ans; 41 | } 42 | if(n >= 1) { 43 | climbStairs(n - 1); 44 | } 45 | if(n >= 2) { 46 | climbStairs(n - 2); 47 | } 48 | } 49 | }; -------------------------------------------------------------------------------- /C++/074. Search a 2D Matrix.cpp: -------------------------------------------------------------------------------- 1 | 74. Search a 2D Matrix 2 | Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 3 | 4 | Integers in each row are sorted from left to right. 5 | The first integer of each row is greater than the last integer of the previous row. 6 | For example, 7 | 8 | Consider the following matrix: 9 | 10 | [ 11 | [1, 3, 5, 7], 12 | [10, 11, 16, 20], 13 | [23, 30, 34, 50] 14 | ] 15 | Given target = 3, return true. 16 | 17 | 题目大意:编写一个有效的算法,在m×n矩阵中搜索一个值。 该矩阵具有以下属性: 18 | 每行中的整数从左到右排序。每行的第一个整数大于前一行的最后一个整数。 19 | 分析:对每一行进行二分搜索,如果找到了就返回true否则返回false~ 20 | 21 | class Solution { 22 | public: 23 | bool searchMatrix(vector>& matrix, int target) { 24 | for(int i = 0; i < matrix.size(); i++) 25 | if (binary_search(matrix[i].begin(), matrix[i].end(), target)) return true; 26 | return false; 27 | } 28 | }; -------------------------------------------------------------------------------- /C++/075. Sort Colors.cpp: -------------------------------------------------------------------------------- 1 | 75. Sort Colors 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 94584 Total Submissions: 273580 Difficulty: Medium 4 | Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. 5 | 6 | Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. 7 | 8 | Note: 9 | You are not suppose to use the library’s sort function for this problem. 10 | 11 | click to show follow up. 12 | 13 | Subscribe to see which companies asked this question 14 | 15 | 16 | class Solution { 17 | public: 18 | void sortColors(vector& nums) { 19 | int cnt0 = 0, cnt1 = 0, cnt2 = 0; 20 | for(int i = 0; i < nums.size(); i++) { 21 | if(nums[i] == 0) { 22 | cnt0++; 23 | } else if (nums[i] == 1) { 24 | cnt1++; 25 | } else { 26 | cnt2++; 27 | } 28 | } 29 | for(int i = 0; i < cnt0; i++) { 30 | nums[i] = 0; 31 | } 32 | for(int i = cnt0; i < cnt0 + cnt1; i++) { 33 | nums[i] = 1; 34 | } 35 | for(int i = cnt1 + cnt0; i < nums.size(); i++) { 36 | nums[i] = 2; 37 | } 38 | } 39 | }; -------------------------------------------------------------------------------- /C++/077. Combinations .cpp: -------------------------------------------------------------------------------- 1 | 77. Combinations 2 | Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. 3 | 4 | For example, 5 | If n = 4 and k = 2, a solution is: 6 | 7 | [ 8 | [2,4], 9 | [3,4], 10 | [2,3], 11 | [1,2], 12 | [1,3], 13 | [1,4], 14 | ] 15 | 16 | 题目大意:给两个整数n和k,返回所有的k个数字组合,这些数字只能从1...n中选择~ 17 | 分析:从cur == 0,cnt == 0开始,每次将cur + 1 ~ n之间的数字放入row中,并将cnt + 1,然后继续深度优先搜索直到cnt == k为止将row放入result中作为结果之一,不要忘记dfs遍历后还要将当前元素pop_back()出来,最后返回result~ 18 | 19 | class Solution { 20 | public: 21 | vector> combine(int n, int k) { 22 | this->n = n, this->k = k; 23 | dfs(0, 0); 24 | return result; 25 | } 26 | private: 27 | int n, k; 28 | vector> result; 29 | vector row; 30 | void dfs(int cur, int cnt) { 31 | if (cnt == k) { 32 | result.push_back(row); 33 | return; 34 | } 35 | for (int i = cur + 1; i <= n; i++) { 36 | row.push_back(i); 37 | dfs(i, cnt + 1); 38 | row.pop_back(); 39 | } 40 | } 41 | }; -------------------------------------------------------------------------------- /C++/078. Subsets.cpp: -------------------------------------------------------------------------------- 1 | 78. Subsets 2 | Given a set of distinct integers, nums, return all possible subsets. 3 | 4 | Note: The solution set must not contain duplicate subsets. 5 | 6 | For example, 7 | If nums = [1,2,3], a solution is: 8 | 9 | [ 10 | [3], 11 | [1], 12 | [2], 13 | [1,2,3], 14 | [1,3], 15 | [2,3], 16 | [1,2], 17 | [] 18 | ] 19 | 20 | 题目大意:给一个集合nums,求nums的所有子集集合~ 21 | 分析:用位运算,j从0到maxn变化,每一次计算j移动i位后最后一位是否为1,如果为1就将nums[i]的值放入result[j]~ 22 | 23 | class Solution { 24 | public: 25 | vector> subsets(vector& nums) { 26 | int len = nums.size(); 27 | int maxn = pow(2, len); 28 | vector> result(maxn); 29 | for (int i = 0; i < len; i++) { 30 | for (int j = 0; j < maxn; j++) { 31 | if ((j >> i) & 1) 32 | result[j].push_back(nums[i]); 33 | } 34 | } 35 | return result; 36 | } 37 | }; -------------------------------------------------------------------------------- /C++/080. Remove Duplicates from Sorted Array II.cpp: -------------------------------------------------------------------------------- 1 | 80. Remove Duplicates from Sorted Array II 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 71707 Total Submissions: 220179 Difficulty: Medium 4 | Follow up for "Remove Duplicates": 5 | What if duplicates are allowed at most twice? 6 | 7 | For example, 8 | Given sorted array nums = [1,1,1,2,2,3], 9 | 10 | Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It does not matter what you leave beyond the new length. 11 | 12 | Subscribe to see which companies asked this question 13 | 14 | Show Tags 15 | 16 | 17 | 18 | class Solution { 19 | public: 20 | int removeDuplicates(vector& nums) { 21 | if(nums.empty()) 22 | return 0; 23 | int len = 1; 24 | vector v(nums.size()); 25 | int cnt = 1; 26 | v[0] = nums[0]; 27 | for(int i = 1; i < nums.size(); i++) { 28 | if(nums[i] == nums[i - 1]) { 29 | cnt++; 30 | } else { 31 | cnt = 1; 32 | } 33 | if(cnt <= 2) { 34 | v[len++] = nums[i]; 35 | } 36 | } 37 | for(int i = 0; i < len; i++) { 38 | nums[i] = v[i]; 39 | } 40 | return len; 41 | } 42 | }; -------------------------------------------------------------------------------- /C++/082. Remove Duplicates from Sorted List II .cpp: -------------------------------------------------------------------------------- 1 | 82. Remove Duplicates from Sorted List II 2 | Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. 3 | 4 | For example, 5 | Given 1->2->3->3->4->4->5, return 1->2->5. 6 | Given 1->1->1->2->3, return 2->3. 7 | 8 | 题目大意:给一个已经排序的链表,删除所有元素值出现过2次或者以上的结点,只保留元素值仅仅出现过一次的结点~ 9 | 分析:p为head的next,如果p的值和head的值不同,则将head->next置为deleteDuplicates(p),返回head,否则直到找到第一个p不等于head的地方,返回deleteDuplicates(p)~ 10 | 11 | class Solution { 12 | public: 13 | ListNode* deleteDuplicates(ListNode* head) { 14 | if (head == NULL || head->next == NULL) return head; 15 | ListNode* p = head->next; 16 | if (p->val != head->val) { 17 | head->next = deleteDuplicates(p); 18 | return head; 19 | } else { 20 | while (p != NULL && p->val == head->val) p = p->next; 21 | return deleteDuplicates(p); 22 | } 23 | } 24 | }; -------------------------------------------------------------------------------- /C++/083. Remove Duplicates from Sorted List.cpp: -------------------------------------------------------------------------------- 1 | 83. Remove Duplicates from Sorted List 2 | Total Accepted: 110507 Total Submissions: 302035 Difficulty: Easy 3 | Given a sorted linked list, delete all duplicates such that each element appear only once. 4 | 5 | For example, 6 | Given 1->1->2, return 1->2. 7 | Given 1->1->2->3->3, return 1->2->3. 8 | 9 | Subscribe to see which companies asked this question 10 | 11 | /** 12 | * Definition for singly-linked list. 13 | * struct ListNode { 14 | * int val; 15 | * ListNode *next; 16 | * ListNode(int x) : val(x), next(NULL) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | ListNode* deleteDuplicates(ListNode* head) { 22 | if(head == NULL || head->next == NULL) { 23 | return head; 24 | } 25 | ListNode *p = head; 26 | while(p != NULL && p->next != NULL) { 27 | while (p->next != NULL && p->next->val == p->val) { 28 | p->next = p->next->next; 29 | } 30 | p = p->next; 31 | } 32 | return head; 33 | } 34 | }; -------------------------------------------------------------------------------- /C++/088. Merge Sorted Array .cpp: -------------------------------------------------------------------------------- 1 | 88. Merge Sorted Array 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 96619 Total Submissions: 322174 Difficulty: Easy 4 | Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 5 | 6 | Note: 7 | You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively. 8 | 9 | Subscribe to see which companies asked this question 10 | 11 | 12 | class Solution { 13 | public: 14 | void merge(vector& nums1, int m, vector& nums2, int n) { 15 | int index = m + n - 1; 16 | int aindex = m - 1; 17 | int bindex = n - 1; 18 | while(aindex >= 0 && bindex >= 0) { 19 | if(nums1[aindex] > nums2[bindex]) { 20 | nums1[index--] = nums1[aindex--]; 21 | } else { 22 | nums1[index--] = nums2[bindex--]; 23 | } 24 | } 25 | while(bindex >= 0) { 26 | nums1[index--] = nums2[bindex--]; 27 | } 28 | } 29 | }; -------------------------------------------------------------------------------- /C++/090. Subsets II.cpp: -------------------------------------------------------------------------------- 1 | 90. Subsets II 2 | Given a collection of integers that might contain duplicates, nums, return all possible subsets. 3 | 4 | Note: The solution set must not contain duplicate subsets. 5 | 6 | For example, 7 | If nums = [1,2,2], a solution is: 8 | 9 | [ 10 | [2], 11 | [1], 12 | [1,2,2], 13 | [2,2], 14 | [1,2], 15 | [] 16 | ] 17 | 18 | 题目大意:给一个集合nums,nums中可能含有重复元素,求nums的所有子集集合~集合中的元素不能重复~ 19 | 分析:首先对nums进行排序,接着用位运算,j从0到maxn变化,每一次计算j移动i位后最后一位是否为1,如果为1就将nums[i]的值放入result[j]~为了保证不重复,将result的结果放入集合s中,然后将s中的结果再放入result数组中返回~ 20 | 21 | class Solution { 22 | public: 23 | vector> subsetsWithDup(vector& nums) { 24 | sort(nums.begin(), nums.end()); 25 | int len = nums.size(); 26 | int maxn = pow(2, len); 27 | vector> result(maxn); 28 | for (int i = 0; i < len; i++) { 29 | for (int j = 0; j < maxn; j++) { 30 | if ((j >> i) & 1) 31 | result[j].push_back(nums[i]); 32 | } 33 | } 34 | set> s; 35 | for (int i = 0; i < result.size(); i++) 36 | s.insert(result[i]); 37 | result.resize(0); 38 | for (auto it = s.begin(); it != s.end(); it++) 39 | result.push_back(*it); 40 | return result; 41 | } 42 | }; -------------------------------------------------------------------------------- /C++/093. Restore IP Addresses.cpp: -------------------------------------------------------------------------------- 1 | 93. Restore IP Addresses 2 | Given a string containing only digits, restore it by returning all possible valid IP address combinations. 3 | 4 | For example: 5 | Given "25525511135", 6 | 7 | return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) 8 | 9 | 题目大意:给一个只包含数字的字符串,返回它可能组成的所有合法IP地址~ 10 | 分析:i、j、k分别是点分隔的第一段、第二段、第三段的长度,从1到3,并且要给后面的段至少空一个数字的距离~这样就可以求出s1、s2、s3、s4,判断s1、s2、s3、s4是否满足条件,满足就将该结果放入result数组中~ 11 | 12 | class Solution { 13 | public: 14 | vector restoreIpAddresses(string s) { 15 | vector result; 16 | int len = s.length(); 17 | for (int i = 1; i <= 3 && i <= len - 3; i++) { 18 | for (int j = 1; j <= 3 && j <= len - i - 2; j++) { 19 | for (int k = 1; k <= 3 && k <= len - i - j - 1; k++) { 20 | string s1 = s.substr(0, i), s2 = s.substr(i, j), s3 = s.substr(i + j, k), s4 = s.substr(i + j + k, len); 21 | if (isValid(s1) && isValid(s2) && isValid(s3) && isValid(s4)) 22 | result.push_back(s1 + "." + s2 + "." + s3 + "." + s4); 23 | } 24 | } 25 | } 26 | return result; 27 | } 28 | bool isValid(string s) { 29 | return (s.length() >= 1 && s.length() <= 3 && (s[0] != '0' || s.length() == 1) && stoi(s) <= 255); 30 | } 31 | }; -------------------------------------------------------------------------------- /C++/094. Binary Tree Inorder Traversal.cpp: -------------------------------------------------------------------------------- 1 | 94. Binary Tree Inorder Traversal 2 | Given a binary tree, return the inorder traversal of its nodes' values. 3 | 4 | For example: 5 | Given binary tree [1,null,2,3], 6 | 1 7 | \ 8 | 2 9 | / 10 | 3 11 | return [1,3,2]. 12 | 13 | 分析:中序遍历,先遍历左子树,再输出中间,再遍历右子树~ 14 | 15 | /** 16 | * Definition for a binary tree node. 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 | vector result; 27 | vector inorderTraversal(TreeNode* root) { 28 | dfs(root); 29 | return result; 30 | } 31 | void dfs(TreeNode* root) { 32 | if(root == NULL) return ; 33 | dfs(root->left); 34 | result.push_back(root->val); 35 | dfs(root->right); 36 | } 37 | }; -------------------------------------------------------------------------------- /C++/096. Unique Binary Search Trees.cpp: -------------------------------------------------------------------------------- 1 | 96. Unique Binary Search Trees 2 | Given n, how many structurally unique BST's (binary search trees) that store values 1...n? 3 | 4 | For example, 5 | Given n = 3, there are a total of 5 unique BST's. 6 | 7 | 1 3 3 2 1 8 | \ / / / \ \ 9 | 3 2 1 1 3 2 10 | / / \ \ 11 | 2 1 2 3 12 | 13 | 二分查找树的定义是,左子树节点均小于root,右子树节点均大于root~~~ 14 | 所以可以用递推的方法,把v[i]表示i个数能够构成的二叉搜索树的个数~~ 15 | 初始化边界值是 v[0]=1,v[1]=1,v[2]=2~~~ 16 | 当i>=3的时候,若以j为root结点,v[j-1]等于root结点左边的j-1个结点能构成的BST个数~~ 17 | v[i-j]等于root结点右边i-j个结点能构成的BST个数~//j+1~i的种数和0~i-j的种数一样。。所以就是v[i-j]~ 18 | 所以v[j-1] * v[i-j]等于以j为root结点能构成的BST种数~~~ 19 | j可以取1~i中的任意一个值,把这些所有计算出来的总数相加就是v[i]的值~~~~ 20 | 所以 for(int j = 1; j <= i; j++) { 21 | v[i] += v[j-1] * v[i-j]; 22 | } 23 | 最后返回的值是v[n]的值,表示1~n能组成的BST的个数~~~~ 24 | 25 | 26 | class Solution { 27 | public: 28 | int numTrees(int n) { 29 | vector v(n+1); 30 | v[0] = 1; 31 | for(int i = 1; i <= n; i++) { 32 | v[i] = 0; 33 | if(i <= 2) { 34 | v[i] = i; 35 | } else { 36 | for(int j = 1; j <= i; j++) { 37 | v[i] += v[j-1] * v[i-j]; 38 | } 39 | } 40 | } 41 | return v[n]; 42 | } 43 | }; -------------------------------------------------------------------------------- /C++/098. Validate Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | 98. Validate Binary Search Tree 2 | Given a binary tree, determine if it is a valid binary search tree (BST). 3 | 4 | Assume a BST is defined as follows: 5 | 6 | The left subtree of a node contains only nodes with keys less than the node's key. 7 | The right subtree of a node contains only nodes with keys greater than the node's key. 8 | Both the left and right subtrees must also be binary search trees. 9 | Example 1: 10 | 2 11 | / \ 12 | 1 3 13 | Binary tree [2,1,3], return true. 14 | Example 2: 15 | 1 16 | / \ 17 | 2 3 18 | Binary tree [1,2,3], return false. 19 | 20 | 题目大意:给一个二叉树,判断这个二叉树是不是合法的二叉搜索树~ 21 | 分析:既然是二叉搜索树,那么按照左根右遍历后的结果一定是增序~所以只需要中序遍历一遍,判断遍历结果的数组是不是后面数一定大于前面数就可以了~ 22 | 23 | 24 | class Solution { 25 | private: 26 | vector v; 27 | public: 28 | bool isValidBST(TreeNode* root) { 29 | if(root == NULL ||(root->left == NULL && root->right == NULL)) return true; 30 | inorder(root); 31 | for(int i = 1; i < v.size(); i++) 32 | if(v[i] <= v[i-1]) return false; 33 | return true; 34 | } 35 | void inorder(TreeNode* root) { 36 | if(root == NULL) return; 37 | inorder(root->left); 38 | v.push_back(root->val); 39 | inorder(root->right); 40 | } 41 | }; -------------------------------------------------------------------------------- /C++/100. Same Tree .cpp: -------------------------------------------------------------------------------- 1 | 100. Same Tree 2 | Given two binary trees, write a function to check if they are equal or not. 3 | 4 | Two binary trees are considered equal if they are structurally identical and the nodes have the same value. 5 | 6 | Subscribe to see which companies asked this question 7 | 8 | 9 | 10 | /** 11 | * Definition for a binary tree node. 12 | * struct TreeNode { 13 | * int val; 14 | * TreeNode *left; 15 | * TreeNode *right; 16 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | bool isSameTree(TreeNode* p, TreeNode* q) { 22 | if(p != NULL && q != NULL) 23 | return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right); 24 | return p == NULL && q == NULL; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /C++/101. Symmetric Tree.cpp: -------------------------------------------------------------------------------- 1 | 101. Symmetric Tree 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 103156 Total Submissions: 305366 Difficulty: Easy 4 | Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). 5 | 6 | For example, this binary tree is symmetric: 7 | 8 | 1 9 | / \ 10 | 2 2 11 | / \ / \ 12 | 3 4 4 3 13 | But the following is not: 14 | 1 15 | / \ 16 | 2 2 17 | \ \ 18 | 3 3 19 | Note: 20 | Bonus points if you could solve it both recursively and iteratively. 21 | 22 | 23 | /** 24 | * Definition for a binary tree node. 25 | * struct TreeNode { 26 | * int val; 27 | * TreeNode *left; 28 | * TreeNode *right; 29 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 30 | * }; 31 | */ 32 | class Solution { 33 | public: 34 | bool func(TreeNode *left, TreeNode *right) { 35 | if(left == NULL && right == NULL) 36 | return true; 37 | if(left != NULL && right != NULL && left->val == right->val) { 38 | return func(left->left, right->right) && func(left->right, right->left); 39 | } 40 | return false; 41 | } 42 | bool isSymmetric(TreeNode* root) { 43 | if(root == NULL) 44 | return true; 45 | return func(root->left, root->right); 46 | } 47 | }; -------------------------------------------------------------------------------- /C++/104. Maximum Depth of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | 104. Maximum Depth of Binary Tree 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 135600 Total Submissions: 284617 Difficulty: Easy 4 | Given a binary tree, find its maximum depth. 5 | 6 | The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 7 | 8 | Subscribe to see which companies asked this question 9 | 10 | 11 | 12 | /** 13 | * Definition for a binary tree node. 14 | * struct TreeNode { 15 | * int val; 16 | * TreeNode *left; 17 | * TreeNode *right; 18 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 19 | * }; 20 | */ 21 | class Solution { 22 | public: 23 | int maxDepth(TreeNode* root) { 24 | if(root == NULL) 25 | return 0; 26 | if(root->left == NULL && root->right == NULL) 27 | return 1; 28 | if(root->left != NULL && root->right == NULL) 29 | return maxDepth(root->left) + 1; 30 | if(root->right != NULL && root->left == NULL) 31 | return maxDepth(root->right) + 1; 32 | if(root->right != NULL && root->left != NULL) { 33 | int leftdepth = maxDepth(root->left); 34 | int rightdepth = maxDepth(root->right); 35 | return leftdepth > rightdepth ? leftdepth + 1 : rightdepth + 1; 36 | } 37 | } 38 | }; -------------------------------------------------------------------------------- /C++/108. Convert Sorted Array to Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | 108. Convert Sorted Array to Binary Search Tree 2 | Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 3 | 4 | 题目大意:给一个升序数组,把它转化为一个高度平衡的二叉搜索树 5 | 分析:设立left和right,mid = (left + right) / 2,每次将数组的中点mid的值为根结点的值,中点左边为根结点的左子树,右边为根结点的右子树~递归求解~ 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 | class Solution { 17 | public: 18 | TreeNode* sortedArrayToBST(vector& nums) { 19 | return func(nums, 0, nums.size() - 1); 20 | } 21 | private: 22 | TreeNode* func(vector& nums, int left, int right) { 23 | if (left > right) return NULL; 24 | int mid = (left + right) / 2; 25 | TreeNode* root = new TreeNode(nums[mid]); 26 | root->left = func(nums, left, mid - 1); 27 | root->right = func(nums, mid + 1, right); 28 | return root; 29 | } 30 | }; -------------------------------------------------------------------------------- /C++/109. Convert Sorted List to Binary Search Tre.cpp: -------------------------------------------------------------------------------- 1 | 109. Convert Sorted List to Binary Search Tree 2 | Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 3 | 4 | 题目大意:给一个升序单链表,把它转换成一个高度平衡的二叉搜索树~ 5 | 分析:递归求解,找到中点,将中点的值赋值给根结点,中点之前的链表为根结点的左子树,中点之后的链表为根结点的右子树~ 6 | 中点以这种方式确定:设立两个指针fast和slow,它们分别从head开始,fast走两步slow走一步,当fast走到最后一个结点的时候slow正好走到中点~ 7 | 8 | class Solution { 9 | public: 10 | TreeNode* sortedListToBST(ListNode* head) { 11 | return func(head, NULL); 12 | } 13 | TreeNode* func(ListNode* head, ListNode* tail) { 14 | ListNode *fast = head, *slow = head; 15 | if (head == tail) return NULL; 16 | while (fast != tail && fast->next != tail) { 17 | fast = fast->next->next; 18 | slow = slow->next; 19 | } 20 | TreeNode* root = new TreeNode(slow->val); 21 | root->left = func(head, slow); 22 | root->right = func(slow->next, tail); 23 | return root; 24 | } 25 | }; -------------------------------------------------------------------------------- /C++/110. Balanced Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | 110. Balanced Binary Tree 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 105986 Total Submissions: 312957 Difficulty: Easy 4 | Given a binary tree, determine if it is height-balanced. 5 | 6 | For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 7 | 8 | Subscribe to see which companies asked this question 9 | 10 | Hide Tags 11 | 12 | /** 13 | * Definition for a binary tree node. 14 | * struct TreeNode { 15 | * int val; 16 | * TreeNode *left; 17 | * TreeNode *right; 18 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 19 | * }; 20 | */ 21 | class Solution { 22 | public: 23 | int flag = 1; 24 | int dfs(TreeNode* root) { 25 | if(root == NULL) 26 | return 1; 27 | int l, r; 28 | if(root->left == NULL) { 29 | l = 0; 30 | } else { 31 | l = dfs(root->left); 32 | } 33 | if(root->right == NULL) { 34 | r = 0; 35 | } else { 36 | r = dfs(root->right); 37 | } 38 | if(abs(l-r) >= 2) { 39 | flag = 0; 40 | } 41 | return (l > r ? l : r) + 1; 42 | } 43 | bool isBalanced(TreeNode* root) { 44 | dfs(root); 45 | return flag; 46 | } 47 | }; -------------------------------------------------------------------------------- /C++/111. Minimum Depth of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | 111. Minimum Depth of Binary Tree 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 101139 Total Submissions: 331361 Difficulty: Easy 4 | Given a binary tree, find its minimum depth. 5 | 6 | The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 7 | 8 | Subscribe to see which companies asked this question 9 | 10 | /** 11 | * Definition for a binary tree node. 12 | * struct TreeNode { 13 | * int val; 14 | * TreeNode *left; 15 | * TreeNode *right; 16 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | int minDepth(TreeNode* root) { 22 | if(root == NULL) 23 | return 0; 24 | if(root->left == NULL && root->right == NULL) 25 | return 1; 26 | if(root->left == NULL && root->right != NULL) 27 | return minDepth(root->right) + 1; 28 | if(root->right == NULL && root->left != NULL) 29 | return minDepth(root->left) + 1; 30 | if(root->left != NULL && root->right != NULL) { 31 | int leftdepth = minDepth(root->left); 32 | int rightdepth = minDepth(root->right); 33 | return leftdepth < rightdepth ? leftdepth + 1 : rightdepth + 1; 34 | } 35 | } 36 | }; -------------------------------------------------------------------------------- /C++/118. Pascal's Triangle.cpp: -------------------------------------------------------------------------------- 1 | 118. Pascal's Triangle 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 80029 Total Submissions: 241495 Difficulty: Easy 4 | Given numRows, generate the first numRows of Pascal's triangle. 5 | 6 | For example, given numRows = 5, 7 | Return 8 | 9 | [ 10 | [1], 11 | [1,1], 12 | [1,2,1], 13 | [1,3,3,1], 14 | [1,4,6,4,1] 15 | ] 16 | Subscribe to see which companies asked this question 17 | 18 | 19 | 20 | class Solution { 21 | public: 22 | vector> generate(int numRows) { 23 | vector> v(numRows); 24 | if(numRows == 0) 25 | return v; 26 | for(int i = 0; i < numRows; i++) { 27 | v[i].resize(i + 1); 28 | } 29 | v[0][0] = 1; 30 | if(numRows == 1) 31 | return v; 32 | v[1][0] = 1; 33 | v[1][1] = 1; 34 | for(int i = 2; i < numRows; i++) { 35 | v[i][0] = 1; 36 | v[i][i] = 1; 37 | } 38 | for(int i = 2; i < numRows; i++) { 39 | for(int j = 1; j < i; j++) { 40 | v[i][j] = v[i - 1][j - 1] + v[i - 1][j]; 41 | } 42 | } 43 | return v; 44 | } 45 | }; -------------------------------------------------------------------------------- /C++/119. Pascal's Triangle II.cpp: -------------------------------------------------------------------------------- 1 | 119. Pascal's Triangle II 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 72147 Total Submissions: 224801 Difficulty: Easy 4 | Given an index k, return the kth row of the Pascal's triangle. 5 | 6 | For example, given k = 3, 7 | Return [1,3,3,1]. 8 | 9 | Note: 10 | Could you optimize your algorithm to use only O(k) extra space? 11 | 12 | Subscribe to see which companies asked this question 13 | 14 | Show Tags 15 | Show Similar Problems 16 | 17 | 18 | class Solution { 19 | public: 20 | vector getRow(int rowIndex) { 21 | vector v(rowIndex+1); 22 | v[0] = 1; 23 | for(int i = 1; i <= rowIndex; i++) { 24 | v[i] = (long long int)v[i-1] *(long long int)(rowIndex-i+1) / i; 25 | } 26 | return v; 27 | } 28 | }; -------------------------------------------------------------------------------- /C++/120. Triangle.cpp: -------------------------------------------------------------------------------- 1 | 120. Triangle 2 | Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. 3 | 4 | For example, given the following triangle 5 | [ 6 | [2], 7 | [3,4], 8 | [6,5,7], 9 | [4,1,8,3] 10 | ] 11 | The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). 12 | 13 | Note: 14 | Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle. 15 | 16 | Subscribe to see which companies asked this question 17 | 18 | class Solution { 19 | public: 20 | int minimumTotal(vector>& triangle) { 21 | for(int i = triangle.size() - 2; i >= 0; i--) { 22 | for(int j = 0; j <= i; j++) { 23 | triangle[i][j] += min(triangle[i+1][j], triangle[i+1][j+1]); 24 | } 25 | } 26 | return triangle[0][0]; 27 | } 28 | }; -------------------------------------------------------------------------------- /C++/121. Best Time to Buy and Sell Stock.cpp: -------------------------------------------------------------------------------- 1 | 121. Best Time to Buy and Sell Stock 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 93802 Total Submissions: 261161 Difficulty: Medium 4 | Say you have an array for which the ith element is the price of a given stock on day i. 5 | 6 | If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. 7 | 8 | Subscribe to see which companies asked this question 9 | 10 | Show Tags 11 | Show Similar Problems 12 | 13 | class Solution { 14 | public: 15 | int maxProfit(vector& prices) { 16 | int minvalue = 99999999; 17 | int ans = 0; 18 | for(int i = 0; i < prices.size(); i++) { 19 | if(minvalue > prices[i]) { 20 | minvalue = prices[i]; 21 | } 22 | prices[i] = prices[i] - minvalue; 23 | if(ans < prices[i]) { 24 | ans = prices[i]; 25 | } 26 | } 27 | return ans; 28 | } 29 | }; -------------------------------------------------------------------------------- /C++/122. Best Time to Buy and Sell Stock II.cpp: -------------------------------------------------------------------------------- 1 | 122. Best Time to Buy and Sell Stock II 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 83388 Total Submissions: 198240 Difficulty: Medium 4 | Say you have an array for which the ith element is the price of a given stock on day i. 5 | 6 | Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 7 | 8 | Subscribe to see which companies asked this question 9 | 10 | 11 | 12 | class Solution { 13 | public: 14 | int maxProfit(vector& prices) { 15 | int ans = 0; 16 | for(int i = 1; i < prices.size(); i++) { 17 | if(prices[i] > prices[i - 1]) 18 | ans += prices[i] - prices[i - 1]; 19 | } 20 | return ans; 21 | } 22 | }; 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /C++/125. Valid Palindrome.cpp: -------------------------------------------------------------------------------- 1 | 125. Valid Palindrome 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 99300 Total Submissions: 417275 Difficulty: Easy 4 | Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 5 | 6 | For example, 7 | "A man, a plan, a canal: Panama" is a palindrome. 8 | "race a car" is not a palindrome. 9 | 10 | Note: 11 | Have you consider that the string might be empty? This is a good question to ask during an interview. 12 | 13 | For the purpose of this problem, we define empty string as valid palindrome. 14 | 15 | Subscribe to see which companies asked this question 16 | 17 | 18 | class Solution { 19 | public: 20 | bool isPalindrome(string s) { 21 | if(s.length() == 0) 22 | return true; 23 | int i = 0, j = s.length() - 1; 24 | while(i < j) { 25 | while(i < j && !isalnum(s[i])) { 26 | i++; 27 | } 28 | while(i < j && !isalnum(s[j])) { 29 | j--; 30 | } 31 | if(i < j && tolower(s[i]) != tolower(s[j])) { 32 | return false; 33 | } else { 34 | i++; 35 | j--; 36 | } 37 | } 38 | return true; 39 | } 40 | }; -------------------------------------------------------------------------------- /C++/136. Single Number.cpp: -------------------------------------------------------------------------------- 1 | 136. Single Number 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 123037 Total Submissions: 248977 Difficulty: Medium 4 | Given an array of integers, every element appears twice except for one. Find that single one. 5 | 6 | Note: 7 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 8 | 9 | 10 | 11 | Subscribe to see which companies asked this question 12 | 13 | update v2.0: 14 | class Solution { 15 | public: 16 | int singleNumber(vector& nums) { 17 | sort(nums.begin(), nums.end()); 18 | for(int i = 0; i < nums.size() - 1; i = i + 2) { 19 | if(nums[i] != nums[i + 1]) { 20 | return nums[i]; 21 | } 22 | } 23 | return nums[nums.size() - 1]; 24 | } 25 | }; 26 | 27 | 28 | 29 | class Solution { 30 | public: 31 | int singleNumber(vector& nums) { 32 | sort(nums.begin(), nums.end()); 33 | set s; 34 | int t = 0; 35 | for(int i = 0; i < nums.size() - 1; i++) { 36 | s.insert(nums[i]); 37 | if(i % 2 == 1 && s.size() != t) { 38 | return nums[i - 1]; 39 | } 40 | t = s.size(); 41 | } 42 | return nums[nums.size() - 1]; 43 | } 44 | }; 45 | 46 | -------------------------------------------------------------------------------- /C++/137. Single Number II.cpp: -------------------------------------------------------------------------------- 1 | 137. Single Number II 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 80394 Total Submissions: 214787 Difficulty: Medium 4 | Given an array of integers, every element appears three times except for one. Find that single one. 5 | 6 | Note: 7 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 8 | 9 | Subscribe to see which companies asked this question 10 | 11 | Show Tags 12 | Show Similar Problems 13 | 14 | 15 | class Solution { 16 | public: 17 | int singleNumber(vector& nums) { 18 | sort(nums.begin(), nums.end()); 19 | for(int i = 0; i <= nums.size() - 4; i = i + 3) { 20 | if(nums[i] != nums[i + 2]) { 21 | return nums[i]; 22 | } 23 | } 24 | return nums[nums.size() - 1]; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /C++/142. Linked List Cycle II .cpp: -------------------------------------------------------------------------------- 1 | 142. Linked List Cycle II 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 72017 Total Submissions: 228808 Difficulty: Medium 4 | Given a linked list, return the node where the cycle begins. If there is no cycle, return null. 5 | 6 | Note: Do not modify the linked list. 7 | 8 | Follow up: 9 | Can you solve it without using extra space? 10 | 11 | Subscribe to see which companies asked this question 12 | 13 | 14 | 15 | /** 16 | * Definition for singly-linked list. 17 | * struct ListNode { 18 | * int val; 19 | * ListNode *next; 20 | * ListNode(int x) : val(x), next(NULL) {} 21 | * }; 22 | */ 23 | class Solution { 24 | public: 25 | ListNode *detectCycle(ListNode *head) { 26 | if(head == NULL) { 27 | return NULL; 28 | } 29 | set s; 30 | ListNode *p = head; 31 | int cnt = 0; 32 | while(p->next != NULL) { 33 | s.insert(p); 34 | if(cnt == s.size()) { 35 | return p; 36 | } 37 | cnt = s.size(); 38 | p = p->next; 39 | } 40 | return NULL; 41 | } 42 | }; -------------------------------------------------------------------------------- /C++/145. Binary Tree Postorder Traversal.cpp: -------------------------------------------------------------------------------- 1 | 145. Binary Tree Postorder Traversal 2 | Given a binary tree, return the postorder traversal of its nodes' values. 3 | 4 | For example: 5 | Given binary tree {1,#,2,3}, 6 | 1 7 | \ 8 | 2 9 | / 10 | 3 11 | return [3,2,1]. 12 | 13 | Note: Recursive solution is trivial, could you do it iteratively? 14 | 15 | 分析:后序遍历,左右根~ 16 | 17 | /** 18 | * Definition for a binary tree node. 19 | * struct TreeNode { 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 | vector result; 29 | vector postorderTraversal(TreeNode* root) { 30 | dfs(root); 31 | return result; 32 | } 33 | void dfs(TreeNode* root) { 34 | if(root == NULL) return; 35 | dfs(root->left); 36 | dfs(root->right); 37 | result.push_back(root->val); 38 | } 39 | }; -------------------------------------------------------------------------------- /C++/151. Reverse Words in a String.cpp: -------------------------------------------------------------------------------- 1 | 151. Reverse Words in a String 2 | Given an input string, reverse the string word by word. 3 | 4 | For example, 5 | Given s = "the sky is blue", 6 | return "blue is sky the". 7 | 8 | 分析:我用的方法是把字符串中的所有单词放入栈里,然后将栈里的所有字符串弹栈到字符串s中~ 9 | 10 | class Solution { 11 | public: 12 | void reverseWords(string &s) { 13 | stack sstack; 14 | int flag = 0; 15 | string temp = ""; 16 | for(int i = 0; i < s.length(); i++) { 17 | if(s[i] != ' ' && flag == 0) { 18 | temp = ""; 19 | temp += s[i]; 20 | flag = 1; 21 | } else if(s[i] != ' ') { 22 | temp += s[i]; 23 | } else if(s[i] == ' ' && flag == 1){ 24 | sstack.push(temp); 25 | flag = 0; 26 | } 27 | if(i == s.length() - 1 && flag == 1) 28 | sstack.push(temp); 29 | } 30 | s = ""; 31 | while(!sstack.empty()) { 32 | string temp = sstack.top(); 33 | s += temp; 34 | sstack.pop(); 35 | if(!sstack.empty()) 36 | s += " "; 37 | } 38 | } 39 | }; -------------------------------------------------------------------------------- /C++/152. Maximum Product Subarray.cpp: -------------------------------------------------------------------------------- 1 | 152. Maximum Product Subarray 2 | Find the contiguous subarray within an array (containing at least one number) which has the largest product. 3 | 4 | For example, given the array [2,3,-2,4], 5 | the contiguous subarray [2,3] has the largest product = 6. 6 | 7 | 题目大意:给一个整型数组,求该数组中所有连续子数组的元素乘积的最大值~ 8 | 分析:需要保存临时最大值和最小值,因为最大值乘以一个正数可能构成新的最大值,而最小值乘以负数也可能构成新的最大值。 9 | result是要求的结果,maxValue为nums[i]之前的,和nums[i]相邻的乘积的最大值,minValue为nums[i]之前的,和nums[i]相邻的乘积的最小值。 10 | 首先令result、maxValue和minValue都为nums[0], i从nums[1]开始一直到结束,tempMax为考虑是否选择之前的maxValue与nums[i]相乘,如果相乘结果更大就保留,否则就选择nums[i]本身为最大。tempMin同理~ 11 | 然后maxValue和minValue比较tempMax/tempMin与minValue * nums[i]的大小关系,maxValue取较大值,minValue取较小值~ 12 | 而result是取所有maxValue中的最大值~最后返回result~ 13 | 14 | class Solution { 15 | public: 16 | int maxProduct(vector& nums) { 17 | if (nums.size() == 0) return 0; 18 | int result = nums[0], maxValue = nums[0], minValue = nums[0]; 19 | for (int i = 1; i < nums.size(); i++) { 20 | int tempMax = max(nums[i], maxValue * nums[i]); 21 | int tempMin = min(nums[i], maxValue * nums[i]); 22 | maxValue = max(tempMax, minValue * nums[i]); 23 | minValue = min(tempMin, minValue * nums[i]); 24 | result = max(maxValue, result); 25 | } 26 | return result; 27 | } 28 | }; -------------------------------------------------------------------------------- /C++/153. Find Minimum in Rotated Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | 153. Find Minimum in Rotated Sorted Array 2 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 3 | 4 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 5 | 6 | Find the minimum element. 7 | 8 | You may assume no duplicate exists in the array. 9 | 10 | 分析:二分搜索法,即使旋转过了也会一半的任何一个元素始终比另一半的任何一个元素大,所以如果nums[mid] < nums[high],说明最小元素一定在[left, mid]中,所以令high = mid;否则一定在[mid + 1, high]中,令low = mid + 1~~ 11 | 12 | class Solution { 13 | public: 14 | int findMin(vector& nums) { 15 | int low = 0, high = nums.size() - 1; 16 | while(low < high) { 17 | int mid = (low + high) / 2; 18 | if(nums[mid] < nums[high]) 19 | high = mid; 20 | else 21 | low = mid + 1; 22 | } 23 | return nums[low]; 24 | } 25 | }; -------------------------------------------------------------------------------- /C++/155. Min Stack.cpp: -------------------------------------------------------------------------------- 1 | 155. Min Stack 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 70109 Total Submissions: 318312 Difficulty: Easy 4 | Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. 5 | 6 | push(x) -- Push element x onto stack. 7 | pop() -- Removes the element on top of the stack. 8 | top() -- Get the top element. 9 | getMin() -- Retrieve the minimum element in the stack. 10 | Subscribe to see which companies asked this question 11 | 12 | 13 | class MinStack { 14 | public: 15 | stack s; 16 | stack min; 17 | 18 | void push(int x) { 19 | s.push(x); 20 | if(min.empty() || min.top() >= x) { 21 | min.push(x); 22 | } 23 | }//这里 if 语句里面是 >= 的原因是,假设有两个相同的最小值8, 24 | //如果只存一个(只填 > ),假设两个 stack 同时pop了一个8, 25 | //那么其实最小值还有8但是已经被 pop 掉了 26 | 27 | void pop() { 28 | if(s.top() == min.top()) { 29 | s.pop(); 30 | min.pop(); 31 | } else { 32 | s.pop(); 33 | } 34 | } 35 | 36 | int top() { 37 | return s.top(); 38 | } 39 | 40 | int getMin() { 41 | return min.top(); 42 | } 43 | }; -------------------------------------------------------------------------------- /C++/162. Find Peak Element .cpp: -------------------------------------------------------------------------------- 1 | 162. Find Peak Element 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 61829 Total Submissions: 187770 Difficulty: Medium 4 | A peak element is an element that is greater than its neighbors. 5 | 6 | Given an input array where num[i] ≠ num[i+1], find a peak element and return its index. 7 | 8 | The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. 9 | 10 | You may imagine that num[-1] = num[n] = -∞. 11 | 12 | For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2. 13 | 14 | click to show spoilers. 15 | 16 | Credits: 17 | Special thanks to @ts for adding this problem and creating all test cases. 18 | 19 | Subscribe to see which companies asked this question 20 | 21 | 22 | 23 | class Solution { 24 | public: 25 | int findPeakElement(vector& nums) { 26 | if(nums.size() == 1 || (nums[0] > nums[1])) 27 | return 0; 28 | if(nums[nums.size() - 1] > nums[nums.size() - 2]) { 29 | return nums.size() - 1; 30 | } 31 | for(int i = 1; i < nums.size() - 1; i++) { 32 | if(nums[i] > nums[i - 1] && nums[i] > nums[i + 1]) { 33 | return i; 34 | } 35 | } 36 | } 37 | }; -------------------------------------------------------------------------------- /C++/167. Two Sum II - Input array is sorted.cpp: -------------------------------------------------------------------------------- 1 | 167. Two Sum II - Input array is sorted 2 | Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. 3 | 4 | The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. 5 | 6 | You may assume that each input would have exactly one solution. 7 | 8 | Input: numbers={2, 7, 11, 15}, target=9 9 | Output: index1=1, index2=2 10 | 11 | 分析:每个数遍历找他的后面是否存在与它相加等于target的数,如果存在就放入result数组中。 12 | 13 | class Solution { 14 | public: 15 | vector twoSum(vector& numbers, int target) { 16 | vector result(2); 17 | for(int i = 0; i < numbers.size(); i++) { 18 | for(int j = i + 1; j < numbers.size(); j++) { 19 | if(numbers[i] + numbers[j] == target) { 20 | result[0] = i + 1; 21 | result[1] = j + 1; 22 | break; 23 | } else if(numbers[i] + numbers[j] > target) { 24 | break; 25 | } 26 | } 27 | if(result[0] != 0) 28 | break; 29 | } 30 | return result; 31 | } 32 | }; -------------------------------------------------------------------------------- /C++/168. Excel Sheet Column Title.cpp: -------------------------------------------------------------------------------- 1 | 168. Excel Sheet Column Title 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 59275 Total Submissions: 273414 Difficulty: Easy 4 | Given a positive integer, return its corresponding column title as appear in an Excel sheet. 5 | 6 | For example: 7 | 8 | 1 -> A 9 | 2 -> B 10 | 3 -> C 11 | ... 12 | 26 -> Z 13 | 27 -> AA 14 | 28 -> AB 15 | Credits: 16 | Special thanks to @ifanchu for adding this problem and creating all test cases. 17 | 18 | Subscribe to see which companies asked this question 19 | 20 | 21 | 把 A~Z 对应 0 ~ 25 22 | 满 26 进 1 23 | 只要看当前 n-1 的值是否 /26 != 0 24 | 如果是的 则 将 (n-1) % 26 + 'A' 存储在 s 之前 25 | 如果不是 则 退出 while 循环 26 | 27 | class Solution { 28 | public: 29 | string convertToTitle(int n) { 30 | string s; 31 | while(n) { 32 | s = (char)((n - 1) % 26 + 'A') + s; 33 | n = (n - 1) / 26; 34 | } 35 | return s; 36 | } 37 | }; -------------------------------------------------------------------------------- /C++/169. Majority Element.cpp: -------------------------------------------------------------------------------- 1 | 169. Majority Element 2 | Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. 3 | 4 | You may assume that the array is non-empty and the majority element always exist in the array. 5 | 6 | Credits: 7 | Special thanks to @ts for adding this problem and creating all test cases. 8 | 9 | Subscribe to see which companies asked this question 10 | 11 | Show Tags 12 | Show Similar Problems 13 | 14 | 15 | class Solution { 16 | public: 17 | int majorityElement(vector& nums) { 18 | sort(nums.begin(), nums.end()); 19 | int temp = 0, maxvalue = 0, ans = nums[0]; 20 | for(int i = 1; i < nums.size(); i++) { 21 | if(nums[i - 1] == nums[i]) { 22 | temp++; 23 | if(temp > maxvalue) { 24 | maxvalue = temp; 25 | ans = nums[i]; 26 | } 27 | } else { 28 | temp = 0; 29 | } 30 | } 31 | return ans; 32 | } 33 | }; -------------------------------------------------------------------------------- /C++/171. Excel Sheet Column Number.cpp: -------------------------------------------------------------------------------- 1 | 171. Excel Sheet Column Number 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 73689 Total Submissions: 178744 Difficulty: Easy 4 | Related to question Excel Sheet Column Title 5 | 6 | Given a column title as appear in an Excel sheet, return its corresponding column number. 7 | 8 | For example: 9 | 10 | A -> 1 11 | B -> 2 12 | C -> 3 13 | ... 14 | Z -> 26 15 | AA -> 27 16 | AB -> 28 17 | Credits: 18 | Special thanks to @ts for adding this problem and creating all test cases. 19 | 20 | Subscribe to see which companies asked this question 21 | 22 | Show Tags 23 | Show Similar Problems 24 | 25 | 26 | class Solution { 27 | public: 28 | int titleToNumber(string s) { 29 | int ans = 0; 30 | for(int i = 0; i < s.length(); i++) { 31 | ans = ans*26 + s[i] - 'A' + 1; 32 | } 33 | return ans; 34 | } 35 | }; -------------------------------------------------------------------------------- /C++/172. Factorial Trailing Zeroes.cpp: -------------------------------------------------------------------------------- 1 | 172. Factorial Trailing Zeroes 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 55895 Total Submissions: 171950 Difficulty: Easy 4 | Given an integer n, return the number of trailing zeroes in n!. 5 | 6 | Note: Your solution should be in logarithmic time complexity. 7 | 8 | Credits: 9 | Special thanks to @ts for adding this problem and creating all test cases. 10 | 11 | Subscribe to see which companies asked this question 12 | 在logn的时间内 找到n!末尾有几个零 13 | 14 | //5*2 = 10出现一个0,n*(n-1)*(n-2)...1当中能被5整除的数少于能被2整除的数 15 | //所以能被5整除的5的个数就是0的个数 16 | //比如25!,25 = 5 * 5有两个5,20,15,10,5各含一个5,这六个5分别和2结合相乘就能得到末尾6个0 17 | //所以只要count每个因子中5的个数就行 18 | 19 | class Solution { 20 | public: 21 | int trailingZeroes(int n) { 22 | int cnt = 0; 23 | while(n != 0) { 24 | cnt = cnt + n / 5; 25 | n = n / 5; 26 | } 27 | return cnt; 28 | } 29 | }; -------------------------------------------------------------------------------- /C++/179. Largest Number.cpp: -------------------------------------------------------------------------------- 1 | 179. Largest Number 2 | Given a list of non negative integers, arrange them such that they form the largest number. 3 | 4 | For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. 5 | 6 | Note: The result may be very large, so you need to return a string instead of an integer. 7 | 8 | Credits: 9 | Special thanks to @ts for adding this problem and creating all test cases. 10 | 题目大意:给一个非负整数数组,求怎样把他们连接起来构成的整数最大~ 11 | 分析:先把他们转换成字符串数组arr,然后对arr进行排序,排序规则是return (a + b) > (b + a);即a+b拼接起来的字符串应该比b+a拼接起来的字符串大~然后将排序后的arr数组从头到尾连接起来~ 12 | 13 | class Solution { 14 | public: 15 | string largestNumber(vector& nums) { 16 | string result = ""; 17 | vector arr(nums.size()); 18 | for(int i = 0; i < nums.size(); i++) 19 | arr[i] = to_string(nums[i]); 20 | auto cmp = [](string a, string b) { 21 | return (a + b) > (b + a); 22 | }; 23 | sort(arr.begin(), arr.end(), cmp); 24 | for(int i = 0; i < arr.size(); i++) 25 | result += arr[i]; 26 | return result[0] == '0' ? "0" : result; 27 | } 28 | }; -------------------------------------------------------------------------------- /C++/189. Rotate Array.cpp: -------------------------------------------------------------------------------- 1 | 189. Rotate Array 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 68454 Total Submissions: 325942 Difficulty: Easy 4 | Rotate an array of n elements to the right by k steps. 5 | 6 | For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. 7 | 8 | Note: 9 | Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. 10 | 11 | [show hint] 12 | 13 | Hint: 14 | Could you do it in-place with O(1) extra space? 15 | Related problem: Reverse Words in a String II 16 | 17 | Credits: 18 | Special thanks to @Freezen for adding this problem and creating all test cases. 19 | 20 | Subscribe to see which companies asked this question 21 | 22 | 23 | 24 | class Solution { 25 | public: 26 | void rotate(vector& nums, int k) { 27 | int n = nums.size(); 28 | k = k % n; 29 | for(int i = 0; i <= (n - 1 - k) / 2; i++) { 30 | swap(nums[i], nums[n - 1 - k - i]); 31 | } 32 | for(int i = n - k; i <= (n - 1 + n - k) / 2; i++) { 33 | swap(nums[i], nums[n - 1 + n - k - i]); 34 | } 35 | for(int i = 0; i <= (n - 1) / 2; i++) { 36 | swap(nums[i], nums[n - 1 - i]); 37 | } 38 | } 39 | }; -------------------------------------------------------------------------------- /C++/190. Reverse Bits.cpp: -------------------------------------------------------------------------------- 1 | 190. Reverse Bits 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 59782 Total Submissions: 204317 Difficulty: Easy 4 | Reverse bits of a given 32 bits unsigned integer. 5 | 6 | For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000). 7 | 8 | Follow up: 9 | If this function is called many times, how would you optimize it? 10 | 11 | Related problem: Reverse Integer 12 | 13 | Credits: 14 | Special thanks to @ts for adding this problem and creating all test cases. 15 | 16 | Subscribe to see which companies asked this question 17 | 18 | 19 | class Solution { 20 | public: 21 | uint32_t reverseBits(uint32_t n) { 22 | uint32_t ans = 0; 23 | for(int i = 0; i < 32; i++) { 24 | ans = ans * 2 + n % 2; 25 | n = n / 2; 26 | } 27 | return ans; 28 | } 29 | }; -------------------------------------------------------------------------------- /C++/191. Number of 1 Bits .cpp: -------------------------------------------------------------------------------- 1 | 191. Number of 1 Bits 2 | 3 | Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight). 4 | 5 | For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3. 6 | 7 | Credits: 8 | Special thanks to @ts for adding this problem and creating all test cases. 9 | 10 | Subscribe to see which companies asked this question 11 | 12 | class Solution { 13 | public: 14 | int hammingWeight(uint32_t n) { 15 | int ans = 0; 16 | while(n != 0) { 17 | ans = ans + n % 2; 18 | n = n / 2; 19 | } 20 | return ans; 21 | } 22 | }; -------------------------------------------------------------------------------- /C++/203. Remove Linked List Elements.cpp: -------------------------------------------------------------------------------- 1 | 203. Remove Linked List Elements 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 59711 Total Submissions: 209326 Difficulty: Easy 4 | Remove all elements from a linked list of integers that have value val. 5 | 6 | Example 7 | Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 8 | Return: 1 --> 2 --> 3 --> 4 --> 5 9 | 10 | Credits: 11 | Special thanks to @mithmatt for adding this problem and creating all test cases. 12 | 13 | Subscribe to see which companies asked this question 14 | 15 | 16 | /** 17 | * Definition for singly-linked list. 18 | * struct ListNode { 19 | * int val; 20 | * ListNode *next; 21 | * ListNode(int x) : val(x), next(NULL) {} 22 | * }; 23 | */ 24 | class Solution { 25 | public: 26 | ListNode* removeElements(ListNode* head, int val) { 27 | while(head != NULL && head->val == val) { 28 | head = head->next; 29 | } 30 | if(head == NULL) { 31 | return NULL; 32 | } 33 | ListNode *p = head; 34 | ListNode *q= p->next; 35 | while(p != NULL && p->next != NULL) { 36 | q = p->next; 37 | while(q != NULL && q->val == val) { 38 | q = q->next; 39 | } 40 | p->next = q; 41 | p = q; 42 | } 43 | return head; 44 | } 45 | }; -------------------------------------------------------------------------------- /C++/215. Kth Largest Element in an Array.cpp: -------------------------------------------------------------------------------- 1 | 215. Kth Largest Element in an Array 2 | Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. 3 | 4 | For example, 5 | Given [3,2,1,5,6,4] and k = 2, return 5. 6 | 7 | Note: 8 | You may assume k is always valid, 1 ≤ k ≤ array's length. 9 | 10 | Credits: 11 | Special thanks to @mithmatt for adding this problem and creating all test cases. 12 | 13 | 分析:一开始用set,后来发现是“not the kth distinct element”,所以说不能用set,set里面元素必须是不相同的,所以这里用multiset就能解决。 14 | 因为multiset会自动排序,所以每次将数字放入multiset,如果集合里面容量超过k个就把最小的那个移除~ 15 | 到最后输出*s.begin()即为第k大~ 16 | 17 | class Solution { 18 | public: 19 | int findKthLargest(vector& nums, int k) { 20 | multiset s; 21 | for(int i = 0; i < nums.size(); i++) { 22 | s.insert(nums[i]); 23 | if(s.size() > k) 24 | s.erase(s.begin()); 25 | } 26 | return *s.begin(); 27 | } 28 | }; -------------------------------------------------------------------------------- /C++/216. Combination Sum III.cpp: -------------------------------------------------------------------------------- 1 | 216. Combination Sum III 2 | Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers. 3 | 4 | 5 | Example 1: 6 | 7 | Input: k = 3, n = 7 8 | 9 | Output: 10 | 11 | [[1,2,4]] 12 | 13 | Example 2: 14 | 15 | Input: k = 3, n = 9 16 | 17 | Output: 18 | 19 | [[1,2,6], [1,3,5], [2,3,4]] 20 | 21 | 分析:一个dfs回溯解决,如果当前k == 0而且 n == 0说明一定达到了k个数,和为n,则将当前path压入result数组中;从start开始一直到9,分别压入path中深度优先搜索。深度优先搜索完了之后记得回溯path中pop出最后一个元素~ 22 | 因为题目要求结果集合必须是按照集合顺序,也就是从小到大而且没有重复元素,那么就要设立一个start变量,每次for循环的时候从start开始,一开始start为0,每次规定start为i+1,即只能从当前数字的下一个数字开始,这样就能保证结果是递增无重复数字的集合序列~~ 23 | 24 | class Solution { 25 | public: 26 | vector> result; 27 | vector path; 28 | vector> combinationSum3(int k, int n) { 29 | dfs(k, n, 1); 30 | return result; 31 | } 32 | 33 | void dfs(int k, int n, int start) { 34 | if(k == 0) { 35 | if(n == 0) 36 | result.push_back(path); 37 | return ; 38 | } 39 | for(int i = start; i <= 9; i++) { 40 | path.push_back(i); 41 | dfs(k - 1, n - i, i + 1); 42 | path.pop_back(); 43 | } 44 | } 45 | }; -------------------------------------------------------------------------------- /C++/217. Contains Duplicate .cpp: -------------------------------------------------------------------------------- 1 | 217. Contains Duplicate 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 81618 Total Submissions: 199467 Difficulty: Easy 4 | Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. 5 | 6 | class Solution { 7 | public: 8 | bool containsDuplicate(vector& nums) { 9 | set m; 10 | for(int i = 0; i < nums.size(); i++) { 11 | m.insert(nums[i]); 12 | } 13 | return nums.size() != m.size(); 14 | } 15 | }; -------------------------------------------------------------------------------- /C++/219. Contains Duplicate II.cpp: -------------------------------------------------------------------------------- 1 | 219. Contains Duplicate II 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 53942 Total Submissions: 181144 Difficulty: Easy 4 | Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k. 5 | 6 | Subscribe to see which companies asked this question 7 | 8 | class Solution { 9 | public: 10 | bool containsNearbyDuplicate(vector& nums, int k) { 11 | set s; 12 | int t = 0; 13 | for(int i = 0; i < nums.size(); i++) { 14 | s.insert(nums[i]); 15 | if(s.size() == t) { 16 | for(int j = i - 1; j >= 0 && j >= i - k; j--) { 17 | if(nums[i] == nums[j]) 18 | return true; 19 | } 20 | } 21 | t = s.size(); 22 | } 23 | return false; 24 | } 25 | }; -------------------------------------------------------------------------------- /C++/220. Contains Duplicate III.cpp: -------------------------------------------------------------------------------- 1 | 220. Contains Duplicate III 2 | Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k. 3 | 4 | 题目大意:给一个整数数组,找到是否存在两个不同的下标i和j,使得nums[i]和nums[j]的差的绝对值不超过t并且i和j的差的绝对值不超过k~ 5 | 分析:建立一个map,对应的是元素的值到元素的下标的映射。指针i将nums数组从头遍历到尾,j指针一开始指向0。i向右走的时候如果i和j之差大于k,且m中有nums[j],就将nums[j]从m中移除,且j向前走一步~这样就保证了m中所有的元素满足第一个条件:i和j的差的绝对值不超过k~ 6 | 接下来考虑nums[i]和nums[j]的差的绝对值不超过t,abs(num[i] - nums[j]) <= t 则 nums[j]的最小可能满足条件的值为>=nums[i] - t的,所以使用map中的lower_bound,寻找第一个大于等于nums[i] - t的地方,找到后标记为a,此时的a只是取到了可能满足的最小的a,但(a - nums[i])不一定满足,所以检验a是否存在于map中且是否abs(a->first - nums[i]) <= t。如果都满足说明可以return true~ 7 | 如果到最后都没有能够return true,则return false~ 8 | 9 | class Solution { 10 | public: 11 | bool containsNearbyAlmostDuplicate(vector& nums, int k, int t) { 12 | map m; 13 | int j = 0; 14 | for (int i = 0; i < nums.size(); ++i) { 15 | if (i - j > k && m[nums[j]] == j) m.erase(nums[j++]); 16 | auto a = m.lower_bound((long)nums[i] - t); 17 | if (a != m.end() && abs(a->first - nums[i]) <= t) return true; 18 | m[nums[i]] = i; 19 | } 20 | return false; 21 | } 22 | }; -------------------------------------------------------------------------------- /C++/222. Count Complete Tree Nodes .cpp: -------------------------------------------------------------------------------- 1 | 222. Count Complete Tree Nodes 2 | Given a complete binary tree, count the number of nodes. 3 | 4 | Definition of a complete binary tree from Wikipedia: 5 | In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. 6 | 7 | 题目大意:给一个完全二叉树,计算结点的个数~ 8 | 分析:完全二叉树满足当最左结点和最右结点等高(h)的时候,结点数为2的h次方-1;否则等于左子树的结点数 + 右子树的结点数 + 1。且完全二叉树的左子树和右子树也是一个完全二叉树~ 9 | 10 | class Solution { 11 | public: 12 | int countNodes(TreeNode* root) { 13 | if (root == NULL) return 0; 14 | TreeNode *l = root, *r = root; 15 | int cntLeft = 0, cntRight = 0; 16 | while (l != NULL) { 17 | l = l->left; 18 | cntLeft++; 19 | } 20 | while (r != NULL) { 21 | r = r->right; 22 | cntRight++; 23 | } 24 | if (cntLeft == cntRight) return pow(2, cntLeft) - 1; 25 | return countNodes(root->left) + countNodes(root->right) + 1; 26 | } 27 | }; -------------------------------------------------------------------------------- /C++/223. Rectangle Area.cpp: -------------------------------------------------------------------------------- 1 | 223. Rectangle Area 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 34834 Total Submissions: 117121 Difficulty: Easy 4 | Find the total area covered by two rectilinear rectangles in a 2D plane. 5 | 6 | Each rectangle is defined by its bottom left corner and top right corner as shown in the figure. 7 | 8 | Rectangle Area 9 | Assume that the total area is never beyond the maximum possible value of int. 10 | 11 | Credits: 12 | Special thanks to @mithmatt for adding this problem, creating the above image and all test cases. 13 | 14 | Subscribe to see which companies asked this question 15 | 16 | 17 | class Solution { 18 | public: 19 | int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { 20 | int maxae = A > E ? A : E; 21 | int mincg = C > G ? G : C; 22 | int maxfb = F > B ? F : B; 23 | int minhd = H > D ? D : H; 24 | int overlap; 25 | if(maxae >= mincg || maxfb >= minhd) 26 | overlap = 0; 27 | else 28 | overlap = (mincg - maxae) * (minhd - maxfb); 29 | return (C - A) * (D - B) + (G - E) * (H - F) - overlap; 30 | } 31 | }; -------------------------------------------------------------------------------- /C++/226. Invert Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | 226. Invert Binary Tree My Submissions QuestionEditorial Solution 2 | Total Accepted: 82224 Total Submissions: 182953 Difficulty: Easy 3 | Invert a binary tree. 4 | 5 | 4 6 | / \ 7 | 2 7 8 | / \ / \ 9 | 1 3 6 9 10 | to 11 | 4 12 | / \ 13 | 7 2 14 | / \ / \ 15 | 9 6 3 1 16 | Trivia: 17 | This problem was inspired by this original tweet by Max Howell: 18 | Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off. 19 | Subscribe to see which companies asked this question 20 | 21 | 22 | /** 23 | * Definition for a binary tree node. 24 | * struct TreeNode { 25 | * int val; 26 | * TreeNode *left; 27 | * TreeNode *right; 28 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 29 | * }; 30 | */ 31 | class Solution { 32 | public: 33 | TreeNode* invertTree(TreeNode* root) { 34 | TreeNode* p = root; 35 | if(root == NULL) { 36 | return NULL; 37 | } 38 | 39 | TreeNode* temp = root->left; 40 | root->left = root->right; 41 | root->right = temp; 42 | 43 | invertTree(root->left); 44 | invertTree(root->right); 45 | 46 | return p; 47 | } 48 | }; -------------------------------------------------------------------------------- /C++/228. Summary Ranges.cpp: -------------------------------------------------------------------------------- 1 | 228. Summary Ranges 2 | Given a sorted integer array without duplicates, return the summary of its ranges. 3 | 4 | For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"]. 5 | 6 | 分析:判断当前nums[i]与nums[i-1]是否是相连,如果是相连就令flag = 1,如果不相连了就将前面的结果放入result数组中。最后for循环之外还要记得把temp字符串再压入数组result中,因为当前最后一次的temp还未被处理。最后返回结果~ 7 | 8 | class Solution { 9 | public: 10 | vector summaryRanges(vector& nums) { 11 | vector result; 12 | if(nums.size() == 0) 13 | return result; 14 | string temp = ""; 15 | int flag = 0; 16 | temp += to_string(nums[0]); 17 | for(int i = 1; i < nums.size(); i++) { 18 | if(nums[i] != nums[i-1] + 1 && flag == 1) { 19 | flag = 0; 20 | temp += "->" + to_string(nums[i-1]); 21 | result.push_back(temp); 22 | temp = "" + to_string(nums[i]); 23 | } else if(nums[i] != nums[i-1] + 1) { 24 | result.push_back(temp); 25 | temp = "" + to_string(nums[i]); 26 | } else { 27 | flag = 1; 28 | } 29 | } 30 | if(flag == 1) { 31 | temp += "->" + to_string(nums[nums.size() - 1]); 32 | } 33 | result.push_back(temp); 34 | return result; 35 | } 36 | }; 37 | 38 | -------------------------------------------------------------------------------- /C++/229. Majority Element II.cpp: -------------------------------------------------------------------------------- 1 | 229. Majority Element II 2 | Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space. 3 | 4 | Hint: 5 | 6 | How many majority elements could it possibly have? 7 | 8 | 9 | 分析:用的常规做法,map计算每个数出现的次数,超过n/3的就放到集合里面,最后遍历集合放入数组中~ 10 | 11 | class Solution { 12 | public: 13 | vector majorityElement(vector& nums) { 14 | vector result; 15 | set s; 16 | map m; 17 | int n = nums.size(); 18 | for(int i = 0; i < n; i++) { 19 | m[nums[i]]++; 20 | if(m[nums[i]] > n / 3) 21 | s.insert(nums[i]); 22 | } 23 | for(auto it = s.begin(); it != s.end(); it++) 24 | result.push_back(*it); 25 | return result; 26 | } 27 | }; -------------------------------------------------------------------------------- /C++/230. Kth Smallest Element in a BST.cpp: -------------------------------------------------------------------------------- 1 | 230. Kth Smallest Element in a BST 2 | Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. 3 | 4 | Note: 5 | You may assume k is always valid, 1 ≤ k ≤ BST's total elements. 6 | 7 | Follow up: 8 | What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine? 9 | 10 | Hint: 11 | 12 | Try to utilize the property of a BST. 13 | What if you could modify the BST node's structure? 14 | The optimal runtime complexity is O(height of BST). 15 | 16 | 题目大意:给一个二叉搜索树,返回它的第k小的数~ 17 | 分析:二叉搜索树的中序遍历是从小到大排序的,将前k个遍历结果放入nums中,当nums.size() >= k的时候返回nums[k-1]~ 18 | 19 | /** 20 | * Definition for a binary tree node. 21 | * struct TreeNode { 22 | * int val; 23 | * TreeNode *left; 24 | * TreeNode *right; 25 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 26 | * }; 27 | */ 28 | class Solution { 29 | public: 30 | vector nums; 31 | int kthSmallest(TreeNode* root, int k) { 32 | if (root == NULL || nums.size() >= k) return nums[k - 1]; 33 | if (root->left != NULL) kthSmallest(root->left, k); 34 | nums.push_back(root->val); 35 | if (root->right != NULL) kthSmallest(root->right, k); 36 | return nums[k - 1]; 37 | } 38 | }; -------------------------------------------------------------------------------- /C++/231. Power of Two.cpp: -------------------------------------------------------------------------------- 1 | 231. Power of Two 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 66387 Total Submissions: 183626 Difficulty: Easy 4 | Given an integer, write a function to determine if it is a power of two. 5 | 6 | Credits: 7 | Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 8 | 9 | Subscribe to see which companies asked this question 10 | 11 | 12 | update v2.0: 13 | class Solution { 14 | public: 15 | bool isPowerOfTwo(int n) { 16 | if(n <= 0) 17 | return false; 18 | return pow(2, (round)(log(n) / log(2))) == n; 19 | } 20 | }; 21 | 22 | //如果没有考虑n <= 0就会超时。。 23 | class Solution { 24 | public: 25 | bool isPowerOfTwo(int n) { 26 | if(n <= 0) 27 | return false; 28 | while(n != 1) { 29 | if(n % 2 == 0) { 30 | n = n / 2; 31 | } else { 32 | return false; 33 | } 34 | } 35 | return true; 36 | } 37 | }; -------------------------------------------------------------------------------- /C++/237. Delete Node in a Linked List.cpp: -------------------------------------------------------------------------------- 1 | 237. Delete Node in a Linked List 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 73802 Total Submissions: 169182 Difficulty: Easy 4 | Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. 5 | 6 | Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function. 7 | 8 | 9 | /** 10 | * Definition for singly-linked list. 11 | * struct ListNode { 12 | * int val; 13 | * ListNode *next; 14 | * ListNode(int x) : val(x), next(NULL) {} 15 | * }; 16 | */ 17 | class Solution { 18 | public: 19 | void deleteNode(ListNode* node) { 20 | node->val = node->next->val; 21 | node->next = node->next->next; 22 | } 23 | }; -------------------------------------------------------------------------------- /C++/238. Product of Array Except Self .cpp: -------------------------------------------------------------------------------- 1 | 238. Product of Array Except Self 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 41121 Total Submissions: 96992 Difficulty: Medium 4 | Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. 5 | 6 | Solve it without division and in O(n). 7 | 8 | For example, given [1,2,3,4], return [24,12,8,6]. 9 | 10 | Follow up: 11 | Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.) 12 | 13 | Subscribe to see which companies asked this question 14 | 15 | 16 | 17 | class Solution { 18 | public: 19 | vector productExceptSelf(vector& nums) { 20 | vector v(nums.size()); 21 | int right = 1; 22 | v[0] = 1; 23 | //左边所有数字的乘积 24 | for(int i = 1; i < nums.size(); i++) { 25 | v[i] = nums[i - 1] * v[i - 1]; 26 | } 27 | for(int i = nums.size() - 2; i >= 0; i--) { 28 | right = right * nums[i + 1]; 29 | v[i] = v[i] * right; 30 | } 31 | return v; 32 | } 33 | }; -------------------------------------------------------------------------------- /C++/240. Search a 2D Matrix II.cpp: -------------------------------------------------------------------------------- 1 | 240. Search a 2D Matrix II 2 | Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 3 | 4 | Integers in each row are sorted in ascending from left to right. 5 | Integers in each column are sorted in ascending from top to bottom. 6 | For example, 7 | 8 | Consider the following matrix: 9 | 10 | [ 11 | [1, 4, 7, 11, 15], 12 | [2, 5, 8, 12, 19], 13 | [3, 6, 9, 16, 22], 14 | [10, 13, 14, 17, 24], 15 | [18, 21, 23, 26, 30] 16 | ] 17 | Given target = 5, return true. 18 | 19 | Given target = 20, return false. 20 | 21 | 题目大意:编写一个有效的算法,在m×n矩阵中搜索一个值。 该矩阵具有以下属性: 22 | 每行中的整数从左到右依次排列。每列中的整数按从上到下的顺序排列。 23 | 分析:对每一行进行binary_serch(),如果能够找到则return true,否则返回false 24 | 25 | class Solution { 26 | public: 27 | bool searchMatrix(vector>& matrix, int target) { 28 | for(int i = 0; i < matrix.size(); i++) 29 | if (binary_search(matrix[i].begin(), matrix[i].end(), target)) return true; 30 | return false; 31 | } 32 | }; -------------------------------------------------------------------------------- /C++/242. Valid Anagram.cpp: -------------------------------------------------------------------------------- 1 | 242. Valid Anagram 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 73035 Total Submissions: 175966 Difficulty: Easy 4 | Given two strings s and t, write a function to determine if t is an anagram of s. 5 | 6 | For example, 7 | s = "anagram", t = "nagaram", return true. 8 | s = "rat", t = "car", return false. 9 | 10 | Note: 11 | You may assume the string contains only lowercase alphabets. 12 | 13 | Follow up: 14 | What if the inputs contain unicode characters? How would you adapt your solution to such case? 15 | 16 | Subscribe to see which companies asked this question 17 | 18 | class Solution { 19 | public: 20 | bool isAnagram(string s, string t) { 21 | int a[26] = {0}; 22 | if(s.length() != t.length()) 23 | return 0; 24 | for(int i = 0; i < s.length(); i++) { 25 | a[s[i] - 'a']++; 26 | } 27 | for(int i = 0; i < t.length(); i++) { 28 | a[t[i] -'a']--; 29 | } 30 | for(int i = 0; i < 26; i++) { 31 | if(a[i] != 0) { 32 | return 0; 33 | } 34 | } 35 | return 1; 36 | } 37 | }; -------------------------------------------------------------------------------- /C++/257. Binary Tree Paths.cpp: -------------------------------------------------------------------------------- 1 | 257. Binary Tree Paths 2 | Given a binary tree, return all root-to-leaf paths. 3 | 4 | For example, given the following binary tree: 5 | 6 | 1 7 | / \ 8 | 2 3 9 | \ 10 | 5 11 | All root-to-leaf paths are: 12 | 13 | ["1->2->5", "1->3"] 14 | Credits: 15 | Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 16 | 17 | 18 | /** 19 | * Definition for a binary tree node. 20 | * struct TreeNode { 21 | * int val; 22 | * TreeNode *left; 23 | * TreeNode *right; 24 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 25 | * }; 26 | */ 27 | class Solution { 28 | public: 29 | void dfs(vector &v, TreeNode *node, string s) { 30 | if(node->left == NULL && node->right == NULL) { 31 | v.push_back(s); 32 | return ; 33 | } 34 | if(node->left != NULL) { 35 | dfs(v, node->left, s + "->" + to_string(node->left->val)); 36 | } 37 | if(node->right != NULL) { 38 | dfs(v, node->right, s + "->" + to_string(node->right->val)); 39 | } 40 | } 41 | 42 | vector binaryTreePaths(TreeNode* root) { 43 | vector v; 44 | if(root == NULL) { 45 | return v; 46 | } 47 | dfs(v, root, to_string(root->val)); 48 | return v; 49 | } 50 | }; -------------------------------------------------------------------------------- /C++/258. Add Digits.cpp: -------------------------------------------------------------------------------- 1 | 258. Add Digits 2 | Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 3 | 4 | For example: 5 | 6 | Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. 7 | 8 | Follow up: 9 | Could you do it without any loop/recursion in O(1) runtime? 10 | 11 | 12 | class Solution { 13 | public: 14 | int addDigits(int num) { 15 | return num - (num - 1) / 9 * 9; 16 | } 17 | }; -------------------------------------------------------------------------------- /C++/263. Ugly Number.cpp: -------------------------------------------------------------------------------- 1 | 263. Ugly Number 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 51161 Total Submissions: 140414 Difficulty: Easy 4 | Write a program to check whether a given number is an ugly number. 5 | 6 | Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. 7 | 8 | Note that 1 is typically treated as an ugly number. 9 | 10 | Credits: 11 | Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 12 | 13 | Subscribe to see which companies asked this question 14 | 15 | class Solution { 16 | public: 17 | bool isUgly(int num) { 18 | if(num <= 0) { 19 | return false; 20 | } 21 | int flag = 0; 22 | while(num != 1) { 23 | flag = 0; 24 | if(num % 2 == 0) { 25 | num = num / 2; 26 | flag = 1; 27 | } 28 | if(num % 3 == 0) { 29 | num = num / 3; 30 | flag = 1; 31 | } 32 | if(num % 5 == 0) { 33 | num = num / 5; 34 | flag = 1; 35 | } 36 | if(flag == 0) { 37 | return false; 38 | } 39 | } 40 | return true; 41 | } 42 | }; -------------------------------------------------------------------------------- /C++/268. Missing Number.cpp: -------------------------------------------------------------------------------- 1 | 268. Missing Number 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 46506 Total Submissions: 116644 Difficulty: Medium 4 | Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. 5 | 6 | For example, 7 | Given nums = [0, 1, 3] return 2. 8 | 9 | Note: 10 | Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity? 11 | 12 | Credits: 13 | Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 14 | 15 | Subscribe to see which companies asked this question 16 | 17 | 18 | 19 | class Solution { 20 | public: 21 | int missingNumber(vector& nums) { 22 | int *book = new int [nums.size() + 1]; 23 | for(int i = 0; i <= nums.size(); i++) { 24 | book[i] = 0; 25 | } 26 | for(int i = 0; i < nums.size(); i++) { 27 | book[nums[i]] = 1; 28 | } 29 | for(int i = 0; i <= nums.size(); i++) { 30 | if(book[i] == 0) { 31 | return i; 32 | } 33 | } 34 | } 35 | }; -------------------------------------------------------------------------------- /C++/279. Perfect Squares.cpp: -------------------------------------------------------------------------------- 1 | 279. Perfect Squares 2 | Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. 3 | For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9. 4 | 分析:建立一个n+1长度的数组dp,dp[i]表示i这个数构成平方和需要数字的最小个数。 5 | 当j*j dp(n+1); 14 | dp[1] = 1; 15 | for(int i = 2; i <= n; i++) { 16 | int temp = 99999999; 17 | for(int j = 1; j * j <= i; j++) { 18 | if(j * j == i) { 19 | temp = 1; 20 | break; 21 | } 22 | temp = min(temp, dp[i-j*j] + 1); 23 | } 24 | dp[i] = temp; 25 | } 26 | return dp[n]; 27 | } 28 | }; -------------------------------------------------------------------------------- /C++/283. Move Zeroes.cpp: -------------------------------------------------------------------------------- 1 | 283. Move Zeroes 2 | Difficulty: Easy 3 | Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements. 4 | 5 | For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. 6 | 7 | Note: 8 | You must do this in-place without making a copy of the array. 9 | Minimize the total number of operations. 10 | 11 | class Solution { 12 | public: 13 | void moveZeroes(vector& nums) { 14 | int len = nums.size(); 15 | for(int i = 0; i < len - 1; i++) { 16 | if(nums[i] == 0) { 17 | for(int j = i + 1; j < len; j++) { 18 | if(nums[j] != 0) { 19 | swap(nums[i], nums[j]); 20 | break; 21 | } 22 | } 23 | } 24 | } 25 | } 26 | }; -------------------------------------------------------------------------------- /C++/292. Nim Game.cpp: -------------------------------------------------------------------------------- 1 | 292. Nim Game 2 | Total Accepted: 59733 Total Submissions: 113879 Difficulty: Easy 3 | You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones. 4 | 5 | Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap. 6 | 7 | For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend. 8 | /* 9 | 设甲乙一人一次为一轮。进行了很多轮之后,让甲选的时候,如果是1,2,3那就可以通过。如果是4一定不能赢,所以如果是5,6,7可以想办法分别取1,2,3让乙来一定不能赢,所以5,6,7甲是可以赢的。 10 | 如果是8,则无论甲选任何个数,都能让乙来面临7,6,5这些必赢的选项所以甲一定输。 11 | 如果是9,10,11,则甲可以通过让乙来面临8来一定输。 12 | 如果是12,则甲无论选取任何个数,都能让乙面临9,10,11这样的一定可以赢的数字,所以12让甲必定输。 13 | 以此类推发现规律,在4或者4的倍数的时候,甲无论怎样一定输。 14 | 所以就简单一句:return n % 4; 15 | */ 16 | class Solution { 17 | public: 18 | bool canWinNim(int n) { 19 | return n % 4; 20 | } 21 | }; -------------------------------------------------------------------------------- /C++/303. Range Sum Query - Immutable.cpp: -------------------------------------------------------------------------------- 1 | 303. Range Sum Query - Immutable 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 27644 Total Submissions: 113304 Difficulty: Easy 4 | Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. 5 | 6 | Example: 7 | Given nums = [-2, 0, 3, -5, 2, -1] 8 | 9 | sumRange(0, 2) -> 1 10 | sumRange(2, 5) -> -1 11 | sumRange(0, 5) -> -3 12 | Note: 13 | You may assume that the array does not change. 14 | There are many calls to sumRange function. 15 | Subscribe to see which companies asked this question 16 | 17 | 18 | class NumArray { 19 | private: 20 | vector v; 21 | public: 22 | NumArray(vector &nums) { 23 | if(nums.size() == 0) 24 | return ; 25 | v.push_back(nums[0]); 26 | for(int i = 1; i < nums.size(); i++) { 27 | v.push_back(v[i - 1] + nums[i]); 28 | } 29 | } 30 | 31 | int sumRange(int i, int j) { 32 | if(i == 0) 33 | return v[j]; 34 | return v[j] - v[i - 1]; 35 | } 36 | }; 37 | 38 | 39 | // Your NumArray object will be instantiated and called as such: 40 | // NumArray numArray(nums); 41 | // numArray.sumRange(0, 1); 42 | // numArray.sumRange(1, 2); -------------------------------------------------------------------------------- /C++/319. Bulb Switcher.cpp: -------------------------------------------------------------------------------- 1 | 319. Bulb Switcher 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 17314 Total Submissions: 42815 Difficulty: Medium 4 | There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb. Find how many bulbs are on after n rounds. 5 | 6 | Example: 7 | 8 | Given n = 3. 9 | 10 | At first, the three bulbs are [off, off, off]. 11 | After first round, the three bulbs are [on, on, on]. 12 | After second round, the three bulbs are [on, off, on]. 13 | After third round, the three bulbs are [on, off, off]. 14 | 15 | So you should return 1, because there is only one bulb is on. 16 | Subscribe to see which companies asked this question 17 | 18 | 19 | 可知题意是想判断1~n中那些数的因子个数是奇数 20 | 一个数 a = b x c 当 b = c 的时候 a 的因子个数就是奇数 21 | 所以就是判断1~n当中有多少个是某数的平方 22 | 23 | class Solution { 24 | public: 25 | int bulbSwitch(int n) { 26 | int ans = 0; 27 | for(int i = 1; i * i <= n; i++) { 28 | ans++; 29 | } 30 | return ans; 31 | } 32 | }; -------------------------------------------------------------------------------- /C++/324. Wiggle Sort II.cpp: -------------------------------------------------------------------------------- 1 | 324. Wiggle Sort II 2 | Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... 3 | 4 | Example: 5 | (1) Given nums = [1, 5, 1, 1, 6, 4], one possible answer is [1, 4, 1, 5, 1, 6]. 6 | (2) Given nums = [1, 3, 2, 2, 3, 1], one possible answer is [2, 3, 1, 3, 1, 2]. 7 | 8 | Note: 9 | You may assume all input has valid answer. 10 | 11 | Follow Up: 12 | Can you do it in O(n) time and/or in-place with O(1) extra space? 13 | 14 | 题目大意:给一个数组,按照nums[0] < nums[1] > nums[2] < nums[3]...的顺序重排序数组~ 15 | 分析:先给数组排序,然后拷贝一份一样的数组arr。然后p指针从数组中间开始向前,q指针从数组最后一位开始向前,依次赋值给nums[i]和nums[j]——其中i是偶数下标,j是奇数下标~ 16 | 17 | class Solution { 18 | public: 19 | void wiggleSort(vector& nums) { 20 | sort(nums.begin(), nums.end()); 21 | vector arr = nums; 22 | int p = (nums.size() - 1) / 2, q = nums.size() - 1; 23 | for (int i = 0, j = 1; i < nums.size(); i += 2, j += 2) { 24 | nums[i] = arr[p--]; 25 | if (j < nums.size()) nums[j] = arr[q--]; 26 | } 27 | } 28 | }; -------------------------------------------------------------------------------- /C++/326. Power of Three.cpp: -------------------------------------------------------------------------------- 1 | 326. Power of Three 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 33438 Total Submissions: 92723 Difficulty: Easy 4 | Given an integer, write a function to determine if it is a power of three. 5 | 6 | Follow up: 7 | Could you do it without using any loop / recursion? 8 | 9 | Credits: 10 | Special thanks to @dietpepsi for adding this problem and creating all test cases. 11 | 12 | Subscribe to see which companies asked this question 13 | 14 | Show Tags 15 | Show Similar Problems 16 | 17 | class Solution { 18 | public: 19 | bool isPowerOfThree(int n) { 20 | if(n <= 0) 21 | return false; 22 | return pow(3, (round)(log(n) / log(3))) == n; 23 | } 24 | }; -------------------------------------------------------------------------------- /C++/328. Odd Even Linked List.cpp: -------------------------------------------------------------------------------- 1 | 328. Odd Even Linked List 2 | Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. 3 | 4 | You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity. 5 | 6 | Example: 7 | Given 1->2->3->4->5->NULL, 8 | return 1->3->5->2->4->NULL. 9 | 10 | Note: 11 | The relative order inside both the even and odd groups should remain as it was in the input. 12 | The first node is considered odd, the second node even and so on ... 13 | 14 | 题目大意:给一个单链表,将奇数结点放到一起,然后将偶数结点放到一起并放在奇数结点的后面返回~ 15 | 分析:设立odd、even和evenHead三个指针,odd负责将所有奇数结点连接在一起,even负责把所有偶数结点连接在一起,而evenHead指向head->next表示偶数结点的头结点。将所有的串联好后将odd->next = evenHead, 最后返回head~ 16 | 17 | 18 | class Solution { 19 | public: 20 | ListNode* oddEvenList(ListNode* head) { 21 | if (head == NULL) return head; 22 | ListNode *odd = head, *even = head->next, *evenHead = head->next; 23 | while (even != NULL && even->next != NULL) { 24 | odd->next = odd->next->next; 25 | even->next = even->next->next; 26 | odd = odd->next; 27 | even = even->next; 28 | } 29 | odd->next = evenHead; 30 | return head; 31 | } 32 | }; -------------------------------------------------------------------------------- /C++/342. Power of Four.cpp: -------------------------------------------------------------------------------- 1 | 342. Power of Four 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 2459 Total Submissions: 7074 Difficulty: Easy 4 | Given an integer (signed 32 bits), write a function to check whether it is a power of 4. 5 | 6 | Example: 7 | Given num = 16, return true. Given num = 5, return false. 8 | 9 | Follow up: Could you solve it without loops/recursion? 10 | 11 | Credits: 12 | Special thanks to @yukuairoy for adding this problem and creating all test cases. 13 | 14 | Subscribe to see which companies asked this question 15 | 16 | Show Tags 17 | Show Similar Problems 18 | 19 | 20 | class Solution { 21 | public: 22 | bool isPowerOfFour(int num) { 23 | return num <= 0 ? false : pow(4, (round)(log(num) / log(4))) == num; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /C++/344. Reverse String.cpp: -------------------------------------------------------------------------------- 1 | 344. Reverse String 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 6975 Total Submissions: 11764 Difficulty: Easy 4 | Write a function that takes a string as input and returns the string reversed. 5 | 6 | Example: 7 | Given s = "hello", return "olleh". 8 | 9 | Subscribe to see which companies asked this question 10 | 11 | //方法一:最简单的办法,直接调用 reverse 函数。。 12 | class Solution { 13 | public: 14 | string reverseString(string s) { 15 | reverse(s.begin(), s.end()); 16 | return s; 17 | } 18 | }; 19 | 20 | //方法二:比较常规的做法,左右两边第一个和倒数第一个调换,第二个和倒数第二个调换... 21 | class Solution { 22 | public: 23 | string reverseString(string s) { 24 | for(int i = 0; i < s.length() / 2; i++) { 25 | swap(s[i], s[s.length() - i - 1]); 26 | } 27 | return s; 28 | } 29 | }; 30 | 31 | -------------------------------------------------------------------------------- /C++/345. Reverse Vowels of a String.cpp: -------------------------------------------------------------------------------- 1 | 345. Reverse Vowels of a String 2 | My Submissions QuestionEditorial Solution 3 | Total Accepted: 3821 Total Submissions: 10524 Difficulty: Easy 4 | Write a function that takes a string as input and reverse only the vowels of a string. 5 | 6 | Example 1: 7 | Given s = "hello", return "holle". 8 | 9 | Example 2: 10 | Given s = "leetcode", return "leotcede". 11 | 12 | Subscribe to see which companies asked this question 13 | 14 | 15 | class Solution { 16 | public: 17 | string reverseVowels(string s) { 18 | int i = 0, j = s.length() - 1; 19 | while(i < j) { 20 | while(i < j && s[i] != 'a' && s[i] != 'e' && s[i] != 'i' && s[i] != 'o' && s[i] != 'u' 21 | && s[i] != 'A' && s[i] != 'E' && s[i] != 'I' && s[i] != 'O' && s[i] != 'U') { 22 | i++; 23 | } 24 | while(i < j && s[j] != 'a' && s[j] != 'e' && s[j] != 'i' && s[j] != 'o' && s[j] != 'u' 25 | && s[j] != 'A' && s[j] != 'E' && s[j] != 'I' && s[j] != 'O' && s[j] != 'U') { 26 | j--; 27 | } 28 | if(i < j) { 29 | swap(s[i], s[j]); 30 | } 31 | i++; 32 | j--; 33 | } 34 | return s; 35 | } 36 | }; -------------------------------------------------------------------------------- /C++/349. Intersection of Two Arrays.cpp: -------------------------------------------------------------------------------- 1 | 349. Intersection of Two Arrays 2 | Given two arrays, write a function to compute their intersection. 3 | 4 | Example: 5 | Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2]. 6 | 7 | Note: 8 | Each element in the result must be unique. 9 | The result can be in any order. 10 | 11 | class Solution { 12 | public: 13 | vector intersection(vector& nums1, vector& nums2) { 14 | set s1; 15 | set s2; 16 | for(int i = 0; i < nums1.size(); i++) { 17 | s1.insert(nums1[i]); 18 | } 19 | for(int i = 0; i < nums2.size(); i++) { 20 | if(s1.find(nums2[i]) != s1.end()) { 21 | s2.insert(nums2[i]); 22 | } 23 | } 24 | vector v; 25 | for(set::iterator it = s2.begin(); it != s2.end(); it++) { 26 | v.push_back(*it); 27 | } 28 | return v; 29 | } 30 | }; -------------------------------------------------------------------------------- /C++/350. Intersection of Two Arrays II.cpp: -------------------------------------------------------------------------------- 1 | 350. Intersection of Two Arrays II 2 | Given two arrays, write a function to compute their intersection. 3 | 4 | Example: 5 | Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2]. 6 | 7 | Note: 8 | Each element in the result should appear as many times as it shows in both arrays. 9 | The result can be in any order. 10 | 11 | 分析:将nums1的每一个数字以及对应数字的个数存储在map里面,遍历nums2中的所有元素,如果当前元素在map中存在,就把它放入result数组中,并将其数量-1。最终返回result即为所求交集~ 12 | 13 | class Solution { 14 | public: 15 | vector intersect(vector& nums1, vector& nums2) { 16 | vector result; 17 | map m; 18 | for(int i = 0; i < nums1.size(); i++) 19 | m[nums1[i]]++; 20 | for(int i = 0; i < nums2.size(); i++) { 21 | if(m[nums2[i]] != 0) { 22 | m[nums2[i]]--; 23 | result.push_back(nums2[i]); 24 | } 25 | } 26 | return result; 27 | } 28 | }; -------------------------------------------------------------------------------- /C++/365. Water and Jug Problem.cpp: -------------------------------------------------------------------------------- 1 | 365. Water and Jug Problem 2 | You are given two jugs with capacities x and y litres. There is an infinite amount of water supply available. You need to determine whether it is possible to measure exactly z litres using these two jugs. 3 | 4 | If z liters of water is measurable, you must have z liters of water contained within one or both buckets by the end. 5 | 6 | Operations allowed: 7 | 8 | Fill any of the jugs completely with water. 9 | Empty any of the jugs. 10 | Pour water from one jug into another till the other jug is completely full or the first jug itself is empty. 11 | Example 1: (From the famous "Die Hard" example) 12 | 13 | Input: x = 3, y = 5, z = 4 14 | Output: True 15 | Example 2: 16 | 17 | Input: x = 2, y = 6, z = 5 18 | Output: False 19 | 20 | 题目大意:给两个容量为x和y升的容器,和无限多的水。你需要确定是否可能用x和y量出z升的水,z升的水必须用一个或者两个容器盛装。 21 | 分析:首先x和y的总容量一定要大于z。其次如果z == 0则直接return true; 最后需要满足z必须是x和y的最大公约数的倍数~最大公约数采用辗转相除法求得~ 22 | 23 | class Solution { 24 | public: 25 | bool canMeasureWater(int x, int y, int z) { 26 | return z == 0 || (x + y >= z && z % gcd(x, y) == 0); 27 | } 28 | private: 29 | int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } 30 | }; -------------------------------------------------------------------------------- /C++/367. Valid Perfect Square.cpp: -------------------------------------------------------------------------------- 1 | 367. Valid Perfect Square 2 | Given a positive integer num, write a function which returns True if num is a perfect square else False. 3 | 4 | Note: Do not use any built-in library function such as sqrt. 5 | 6 | Example 1: 7 | 8 | Input: 16 9 | Returns: True 10 | Example 2: 11 | 12 | Input: 14 13 | Returns: False 14 | 15 | 题目大意:判断所给的数是否正好是某数的平方~ 16 | 分析:二分查找法,假设它是某数的平方,将该数的结果控制在left和right之间,不断循环,每次令mid为left和right的中间值,如果mid的平方等于num说明返回true;如果mid的平方小于num并且mid+1的平方大于num,说明num不是任何数的平方,夹在mid和mid+1之间~如果mid的平方小于num说明结果在mid的右边,令left = mid + 1;否则某数就是在mid的左边,right = mid - 1~~ 17 | 18 | class Solution { 19 | public: 20 | bool isPerfectSquare(int num) { 21 | long left = 0, right = INT_MAX, mid = 0; 22 | while (true) { 23 | mid = left + (right - left) / 2; 24 | if (mid * mid == num) 25 | return true; 26 | if (mid * mid < num && (mid + 1) * (mid + 1) > num) 27 | return false; 28 | if (mid * mid < num) 29 | left = mid + 1; 30 | else 31 | right = mid - 1; 32 | } 33 | } 34 | }; -------------------------------------------------------------------------------- /C++/371. Sum of Two Integers.cpp: -------------------------------------------------------------------------------- 1 | LeetCode 371. Sum of Two Integers 2 | 3 | Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. 4 | 5 | Example: 6 | Given a = 1 and b = 2, return 3. 7 | 8 | 分析:位运算~ 9 | 首先,已知异或(就是这个“^”符号)可以得到: 10 | 0^0 = 0 11 | 0^1 = 1 12 | 1^1 = 0 13 | 正是位相加时该位的结果~(只不过还有个进位没加罢了~) 14 | 所以对于还没有加进位的result,result可以暂时等于a^b 15 | 16 | 其次,已知与运算(就是这个“&”符号)可以得到: 17 | 0&0 = 0 18 | 0&1 = 0 19 | 1&1 = 1 20 | 正是位相加时候有进位的那一位标注为了1~ 21 | 但是进位是往前一个位相加上去的呀~ 22 | 所以carry = (a & b) << 1 23 | 24 | 现在处理要把result加上进位的事情~ 25 | 如果进位carry等于0,那么不用加~直接等于result的值就好了~ 26 | 如果进位不等于0,那么就要把result和carry的值按位相加~ 27 | 按位相加的结果也可能导致进位~所以先用个临时变量temp把carry的值保存,然后令carry = (result & temp) << 1(也就是result和原来carry按位相加后进位的结果~),然后result = result ^ temp(也就是result和原来carry按位相加的结果~),不断循环往复,直到有一次carry等于0,不再需要进位了~~~~ 28 | 29 | class Solution { 30 | public: 31 | int getSum(int a, int b) { 32 | int carry = (a & b) << 1; 33 | int result = (a ^ b); 34 | while(carry != 0) { 35 | int temp = carry; 36 | carry = (result & temp) << 1; 37 | result = result ^ temp; 38 | }; 39 | return result; 40 | } 41 | }; -------------------------------------------------------------------------------- /C++/374. Guess Number Higher or Lower.cpp: -------------------------------------------------------------------------------- 1 | 374. Guess Number Higher or Lower 2 | We are playing the Guess Game. The game is as follows: 3 | 4 | I pick a number from 1 to n. You have to guess which number I picked. 5 | 6 | Every time you guess wrong, I'll tell you whether the number is higher or lower. 7 | 8 | You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0): 9 | 10 | -1 : My number is lower 11 | 1 : My number is higher 12 | 0 : Congrats! You got it! 13 | Example: 14 | n = 10, I pick 6. 15 | 16 | Return 6. 17 | 18 | 分析:二分查找法解决,不过要注意mid = low + (high - low) / 2 不要写成 mid = (low + high) / 2 ,后者超过了Int类型的最大值,相加变成负数,会导致超时 19 | 20 | // Forward declaration of guess API. 21 | // @param num, your guess 22 | // @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 23 | int guess(int num); 24 | 25 | class Solution { 26 | public: 27 | int guessNumber(int n) { 28 | int low = 1, high = n; 29 | while(low <= high) { 30 | int mid = low + (high - low) / 2; 31 | int temp = guess(mid); 32 | if(temp == 1) 33 | low = mid + 1; 34 | else if(temp == -1) 35 | high = mid - 1; 36 | else 37 | return mid; 38 | } 39 | } 40 | }; -------------------------------------------------------------------------------- /C++/378. Kth Smallest Element in a Sorted Matrix.cpp: -------------------------------------------------------------------------------- 1 | 378. Kth Smallest Element in a Sorted Matrix 2 | Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix. 3 | 4 | Note that it is the kth smallest element in the sorted order, not the kth distinct element. 5 | 6 | Example: 7 | 8 | matrix = [ 9 | [ 1, 5, 9], 10 | [10, 11, 13], 11 | [12, 13, 15] 12 | ], 13 | k = 8, 14 | 15 | return 13. 16 | Note: 17 | You may assume k is always valid, 1 ≤ k ≤ n2. 18 | 19 | 分析:使用multiset,因为是求第k小的,而且允许相同的元素,所以使用可以存储相同元素的multiset。当multiset里面的元素大于k个的时候,删除集合中最大的那个(即最后一个元素,也就是s.end()的前一个),最后输出最后一个元素即可~即 *s.rbegin()~~~ 20 | 21 | class Solution { 22 | public: 23 | int kthSmallest(vector>& matrix, int k) { 24 | multiset s; 25 | for(int i = 0; i < matrix.size(); i++) { 26 | for(int j = 0; j < matrix[i].size(); j++) { 27 | s.insert(matrix[i][j]); 28 | if(s.size() > k) 29 | s.erase(--s.end()); 30 | } 31 | } 32 | return *s.rbegin(); 33 | } 34 | }; -------------------------------------------------------------------------------- /C++/383. Ransom Note.cpp: -------------------------------------------------------------------------------- 1 | 383. Ransom Note 2 | 
Given
 an
arbitrary
 ransom
 note
 string
and
another
string
containing
letters from
 all
the
magazines,
 write
a
function
that
will
return
true
if
the
ransom
 note
can
be
constructed
from
the
magazines ;
otherwise,
it
will
return
false.

 3 | 4 | Each
letter
 in
 the
 magazine
string
can
 only
be
 used
once
 in
 your
ransom
 note. 5 | 6 | Note: 7 | You may assume that both strings contain only lowercase letters. 8 | 9 | canConstruct("a", "b") -> false 10 | canConstruct("aa", "ab") -> false 11 | canConstruct("aa", "aab") -> true 12 | 13 | 题目大意:给两个string,判断第一个string能否由第二个string里面所含有的字母组成,第二个string里面的所有字母只能使用一次~ 14 | 分析:建立一个hash数组,对第二个string遍历并记录每个字符出现的次数,然后遍历第一个string,如果有出现hash里面不存在的字符,那么return false~~~~ 15 | 16 | class Solution { 17 | public: 18 | bool canConstruct(string ransomNote, string magazine) { 19 | vector hash(256); 20 | for(int i = 0; i < magazine.size(); i++) 21 | hash[magazine[i]]++; 22 | for(int i = 0; i < ransomNote.size(); i++) 23 | if(hash[ransomNote[i]]) 24 | hash[ransomNote[i]]--; 25 | else 26 | return false; 27 | return true; 28 | } 29 | }; -------------------------------------------------------------------------------- /C++/386. Lexicographical Numbers.cpp: -------------------------------------------------------------------------------- 1 | 386. Lexicographical Numbers 2 | Given an integer n, return 1 - n in lexicographical order. 3 | 4 | For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9]. 5 | 6 | Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000. 7 | 8 | 题目大意:给一个整数n,将1-n所有数按照字典序排序~ 9 | 分析:从1~9分别深度优先遍历,对于每一次遍历,继续深度优先它的10 * cur + i(i从1~9),只要符合范围的就将该数字cur放入result数组中~最后返回result即可~ 10 | 11 | class Solution { 12 | public: 13 | vector lexicalOrder(int n) { 14 | this->n = n; 15 | for (int i = 1; i <= 9; i++) 16 | dfs(i); 17 | return result; 18 | } 19 | private: 20 | vector result; 21 | int n; 22 | void dfs(int cur) { 23 | if (cur > n) return; 24 | result.push_back(cur); 25 | for (int i = 0; i <= 9; i++) 26 | dfs(10 * cur + i); 27 | } 28 | }; -------------------------------------------------------------------------------- /C++/387. First Unique Character in a String .cpp: -------------------------------------------------------------------------------- 1 | 387. First Unique Character in a String 2 | Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. 3 | 4 | Examples: 5 | 6 | s = "leetcode" 7 | return 0. 8 | 9 | s = "loveleetcode", 10 | return 2. 11 | Note: You may assume the string contain only lowercase letters. 12 | 13 | Subscribe to see which companies asked this question 14 | 15 | 分析:map存储每个字符的出现次数,从头遍历数组return第一个m[s[i]] == 1的下标。如果没有就return -1。 16 | class Solution { 17 | public: 18 | int firstUniqChar(string s) { 19 | map m; 20 | for(int i = 0; i < s.length(); i++) 21 | m[s[i]]++; 22 | for(int i = 0; i < s.length(); i++) { 23 | if(m[s[i]] == 1) 24 | return i; 25 | } 26 | return -1; 27 | } 28 | }; -------------------------------------------------------------------------------- /C++/389. Find the Difference.cpp: -------------------------------------------------------------------------------- 1 | 389. Find the Difference 2 | Given two strings s and t which consist of only lowercase letters. 3 | 4 | String t is generated by random shuffling string s and then add one more letter at a random position. 5 | 6 | Find the letter that was added in t. 7 | 8 | Example: 9 | 10 | Input: 11 | s = "abcd" 12 | t = "abcde" 13 | 14 | Output: 15 | e 16 | 17 | Explanation: 18 | 'e' is the letter that was added. 19 | 20 | 分析:将字符串s和字符串t的字符个数标记在hash1和hash2数组中,然后比较hash1和hash2,值不同的那个字符即为所求~ 21 | 22 | class Solution { 23 | public: 24 | char findTheDifference(string s, string t) { 25 | int hash1[256] = {0}, hash2[256] = {0}; 26 | for(int i = 0; i < s.length(); i++) 27 | hash1[s[i]]++; 28 | for(int i = 0; i < t.length(); i++) 29 | hash2[t[i]]++; 30 | for(int i = 0; i < 256; i++) 31 | if(hash1[i] != hash2[i]) 32 | return (char)i; 33 | return '0'; 34 | } 35 | }; -------------------------------------------------------------------------------- /C++/400. Nth Digit.cpp: -------------------------------------------------------------------------------- 1 | 400. Nth Digit 2 | Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... 3 | 4 | Note: 5 | n is positive and will fit within the range of a 32-bit signed integer (n < 231). 6 | 7 | Example 1: 8 | 9 | Input: 10 | 3 11 | 12 | Output: 13 | 3 14 | Example 2: 15 | 16 | Input: 17 | 11 18 | 19 | Output: 20 | 0 21 | 22 | Explanation: 23 | The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10. 24 | 25 | 分析:个位数:1-9,一共9个,共计9个数字;2位数:10-99,一共90个,共计180个数字; 3位数:100-999,一共900个,共计270个数字……以此类推,所以先算出它在几位数的区间,然后算出它是在这个区间内的第几个数,最后算出在这个数的第几位~ 26 | 27 | class Solution { 28 | public: 29 | int findNthDigit(int n) { 30 | long digit = 1, sum = 9; 31 | while(n > digit * sum) { 32 | n = n - digit * sum; 33 | sum = sum * 10; 34 | digit++; 35 | } 36 | int index = n % digit; 37 | if(index == 0) 38 | index = digit; 39 | long num = pow(10, digit - 1); 40 | num += (index == digit) ? (n / digit - 1) : (n / digit); 41 | for(int i = index; i < digit; i++) 42 | num = num / 10; 43 | return num % 10; 44 | } 45 | }; -------------------------------------------------------------------------------- /C++/401. Binary Watch.cpp: -------------------------------------------------------------------------------- 1 | 401. Binary Watch 2 | A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59). 3 | 4 | Each LED represents a zero or one, with the least significant bit on the right. 5 | 6 | For example, the above binary watch reads "3:25". 7 | 8 | Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent. 9 | 10 | Example: 11 | 12 | Input: n = 1 13 | Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"] 14 | 15 | 分析:小时数h从0~11,分钟数m从0~59,把他们每一个转换为一个二进制整体,初始化为bitset,看bitset中1的个数是否为num,如果是就将h和m构成一个字符串加入到result字符串数组中,最后返回result~~ 16 | 17 | class Solution { 18 | public: 19 | vector readBinaryWatch(int num) { 20 | vector result; 21 | for(int h = 0; h < 12; h++) { 22 | for(int m = 0; m < 60; m++) { 23 | bitset<10> b(h << 6 | m); 24 | if(b.count() == num) { 25 | string temp = to_string(h) + ":"; 26 | if(m < 10) 27 | temp += "0"; 28 | temp += to_string(m); 29 | result.push_back(temp); 30 | } 31 | } 32 | } 33 | return result; 34 | } 35 | }; -------------------------------------------------------------------------------- /C++/404. Sum of Left Leaves.cpp: -------------------------------------------------------------------------------- 1 | 404. Sum of Left Leaves 2 | Find the sum of all left leaves in a given binary tree. 3 | 4 | Example: 5 | 6 | 3 7 | / \ 8 | 9 20 9 | / \ 10 | 15 7 11 | 12 | There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24. 13 | 14 | 分析:深度优先遍历,将所有结点从根结点开始遍历一遍,设立isLeft的值,当当前结点是叶子节点并且也是左边,那就result加上它的值~ 15 | 16 | /** 17 | * Definition for a binary tree node. 18 | * struct TreeNode { 19 | * int val; 20 | * TreeNode *left; 21 | * TreeNode *right; 22 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 23 | * }; 24 | */ 25 | class Solution { 26 | public: 27 | int result = 0; 28 | int sumOfLeftLeaves(TreeNode* root) { 29 | if(root == NULL) 30 | return 0; 31 | dfs(root, false); 32 | return result; 33 | } 34 | void dfs(TreeNode* root, bool isLeft) { 35 | if(root->left == NULL && root->right == NULL) { 36 | if(isLeft == true) 37 | result += root->val; 38 | return ; 39 | } 40 | if(root->left != NULL) 41 | dfs(root->left, true); 42 | if(root->right != NULL) 43 | dfs(root->right, false); 44 | } 45 | }; -------------------------------------------------------------------------------- /C++/409. Longest Palindrome.cpp: -------------------------------------------------------------------------------- 1 | 409. Longest Palindrome 2 | Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters. 3 | 4 | This is case sensitive, for example "Aa" is not considered a palindrome here. 5 | 6 | Note: 7 | Assume the length of given string will not exceed 1,010. 8 | 9 | Example: 10 | 11 | Input: 12 | "abccccdd" 13 | 14 | Output: 15 | 7 16 | 17 | Explanation: 18 | One longest palindrome that can be built is "dccaccd", whose length is 7. 19 | 20 | 分析:统计每个字母出现的字数,如果是偶数就能放到回文串里;如果是奇数就只能hash[i] - 1个放到回文串里面,而且如果存在是奇数个数的字母,则最后可以加1,也就是把落单的字母中的任意一个放到回文串的最中间使长度加1~ 21 | 22 | class Solution { 23 | public: 24 | int longestPalindrome(string s) { 25 | int hash[256] = {0}, len = 0, flag = 0; 26 | for(int i = 0; i < s.length(); i++) 27 | hash[s[i]]++; 28 | for(int i = 0; i < 256; i++) { 29 | if(hash[i] % 2 == 0) { 30 | len += hash[i]; 31 | } else { 32 | len += (hash[i] - 1); 33 | flag = 1; 34 | } 35 | } 36 | return len + flag; 37 | } 38 | }; -------------------------------------------------------------------------------- /C++/412. Fizz Buzz .cpp: -------------------------------------------------------------------------------- 1 | 412. Fizz Buzz 2 | Write a program that outputs the string representation of numbers from 1 to n. 3 | 4 | But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”. 5 | 6 | Example: 7 | 8 | n = 15, 9 | 10 | Return: 11 | [ 12 | "1", 13 | "2", 14 | "Fizz", 15 | "4", 16 | "Buzz", 17 | "Fizz", 18 | "7", 19 | "8", 20 | "Fizz", 21 | "Buzz", 22 | "11", 23 | "Fizz", 24 | "13", 25 | "14", 26 | "FizzBuzz" 27 | ] 28 | 29 | 分析:几个if else 语句分别对是否能被15整除、5整除、3整除进行赋值~ 30 | 31 | class Solution { 32 | public: 33 | vector fizzBuzz(int n) { 34 | vector result(n); 35 | for(int i = 0; i < n; i++) { 36 | if((i + 1) % 15 == 0) 37 | result[i] = "FizzBuzz"; 38 | else if((i + 1) % 5 == 0) 39 | result[i] = "Buzz"; 40 | else if((i + 1) % 3 == 0) 41 | result[i] = "Fizz"; 42 | else 43 | result[i] = to_string(i + 1); 44 | } 45 | return result; 46 | } 47 | }; -------------------------------------------------------------------------------- /C++/414. Third Maximum Number.cpp: -------------------------------------------------------------------------------- 1 | 414. Third Maximum Number 2 | Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n). 3 | 4 | Example 1: 5 | Input: [3, 2, 1] 6 | 7 | Output: 1 8 | 9 | Explanation: The third maximum is 1. 10 | Example 2: 11 | Input: [1, 2] 12 | 13 | Output: 2 14 | 15 | Explanation: The third maximum does not exist, so the maximum (2) is returned instead. 16 | Example 3: 17 | Input: [2, 2, 3, 1] 18 | 19 | Output: 1 20 | 21 | Explanation: Note that the third maximum here means the third maximum distinct number. 22 | Both numbers with value 2 are both considered as second maximum. 23 | 24 | 分析:因为set会自动排序,所以每次将数字放入set,如果set里面容量超过三个就把最小的那个移除~ 25 | 到最后如果set的大小不是3个,那就输出最大值,也就是*s.rbegin(), 如果set的大小是3个就输出*s.begin()即为第三大~ 26 | 27 | class Solution { 28 | public: 29 | int thirdMax(vector& nums) { 30 | set s; 31 | for(int i = 0; i < nums.size(); i++) { 32 | s.insert(nums[i]); 33 | if(s.size() > 3) 34 | s.erase(s.begin()); 35 | } 36 | return s.size() == 3 ? *s.begin() : * s.rbegin(); 37 | } 38 | }; -------------------------------------------------------------------------------- /C++/434. Number of Segments in a String.cpp: -------------------------------------------------------------------------------- 1 | 434. Number of Segments in a String 2 | Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters. 3 | 4 | Please note that the string does not contain any non-printable characters. 5 | 6 | Example: 7 | 8 | Input: "Hello, my name is John" 9 | Output: 5 10 | 11 | 分析:一旦出现不是空格的s[i]并且他前一个不和他连续,那么就cnt++; 如果遇到是空格,重新将flag标记为0表示当前s[i]和下一个s[i]不连续~ 12 | 13 | class Solution { 14 | public: 15 | int countSegments(string s) { 16 | int cnt = 0, flag = 0; 17 | for(int i = 0; i < s.length(); i++) { 18 | if(s[i] != ' ' && flag == 0) { 19 | cnt++; 20 | flag = 1; 21 | } else if(s[i] == ' ') { 22 | flag = 0; 23 | } 24 | } 25 | return cnt; 26 | } 27 | }; -------------------------------------------------------------------------------- /C++/441. Arranging Coins .cpp: -------------------------------------------------------------------------------- 1 | 441. Arranging Coins 2 | You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins. 3 | 4 | Given n, find the total number of full staircase rows that can be formed. 5 | 6 | n is a non-negative integer and fits within the range of a 32-bit signed integer. 7 | 8 | Example 1: 9 | n = 5 10 | The coins can form the following rows: 11 | ¤ 12 | ¤ ¤ 13 | ¤ ¤ 14 | Because the 3rd row is incomplete, we return 2. 15 | Example 2: 16 | n = 8 17 | The coins can form the following rows: 18 | ¤ 19 | ¤ ¤ 20 | ¤ ¤ ¤ 21 | ¤ ¤ 22 | Because the 4th row is incomplete, we return 3. 23 | 24 | 分析:直接用公式一行代码就能解决 25 | 26 | class Solution { 27 | public: 28 | int arrangeCoins(int n) { 29 | return (int)((sqrt(8 * (long)n + 1) - 1)/ 2); 30 | } 31 | }; -------------------------------------------------------------------------------- /C++/442. Find All Duplicates in an Array.cpp: -------------------------------------------------------------------------------- 1 | 442. Find All Duplicates in an Array 2 | Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. 3 | 4 | Find all the elements that appear twice in this array. 5 | 6 | Could you do it without extra space and in O(n) runtime? 7 | 8 | Example: 9 | Input: 10 | [4,3,2,7,8,2,3,1] 11 | 12 | Output: 13 | [2,3] 14 | 15 | 分析:题目说不能用额外的空间,就想办法直接利用nums数组标记,考虑到nums数组中的所有数都为正数,那么比如i出现过,把num[i]的值标记为负数,那么每次去看num[i]是正是负就能知道i以前有没有出现过~因为所有数都是1~n的,而下标只能0~n-1,可以把i-1标记成负数来符合这个条件~ 16 | 所以说可以令当前nums[i]的绝对值是num,如果nums[num-1]这个值是负数,说明以前遇到过num,那么就把num这个数字放入result数组中;如果不是负数,说明以前没有出现过这个数,就把这个数变成自己本身的负数~即:nums[num - 1] = 0 - nums[num - 1]; 17 | 18 | class Solution { 19 | public: 20 | vector findDuplicates(vector& nums) { 21 | vector result; 22 | for(int i = 0; i < nums.size(); i++) { 23 | int num = abs(nums[i]); 24 | if(nums[num - 1] < 0) 25 | result.push_back(num); 26 | else 27 | nums[num - 1] = 0 - nums[num - 1]; 28 | } 29 | return result; 30 | } 31 | }; -------------------------------------------------------------------------------- /C++/448. Find All Numbers Disappeared in an Array.cpp: -------------------------------------------------------------------------------- 1 | 448. Find All Numbers Disappeared in an Array 2 | Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. 3 | 4 | Find all the elements of [1, n] inclusive that do not appear in this array. 5 | 6 | Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. 7 | 8 | Example: 9 | 10 | Input: 11 | [4,3,2,7,8,2,3,1] 12 | 13 | Output: 14 | [5,6] 15 | 16 | 分析:hash[i]用来标记i是否在nums数组中出现过。然后将没有出现过的放入result数组中,返回result数组~~~ 17 | 18 | class Solution { 19 | public: 20 | vector findDisappearedNumbers(vector& nums) { 21 | vector result; 22 | vector hash(nums.size() + 1, false); 23 | for(int i = 0; i < nums.size(); i++) { 24 | hash[nums[i]] = true; 25 | } 26 | for(int i = 1; i < hash.size(); i++) { 27 | if(hash[i] == false) 28 | result.push_back(i); 29 | } 30 | return result; 31 | } 32 | }; -------------------------------------------------------------------------------- /C++/451. Sort Characters By Frequency.cpp: -------------------------------------------------------------------------------- 1 | 451. Sort Characters By Frequency 2 | Given a string, sort it in decreasing order based on the frequency of characters. 3 | 4 | Example 1: 5 | 6 | Input: 7 | "tree" 8 | 9 | Output: 10 | "eert" 11 | 12 | Explanation: 13 | 'e' appears twice while 'r' and 't' both appear once. 14 | So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. 15 | Example 2: 16 | 17 | Input: 18 | "cccaaa" 19 | 20 | Output: 21 | "cccaaa" 22 | 23 | Explanation: 24 | Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer. 25 | Note that "cacaca" is incorrect, as the same characters must be together. 26 | Example 3: 27 | 28 | Input: 29 | "Aabb" 30 | 31 | Output: 32 | "bbAa" 33 | 34 | Explanation: 35 | "bbaA" is also a valid answer, but "Aabb" is incorrect. 36 | Note that 'A' and 'a' are treated as two different characters. 37 | 38 | 分析:在cnt数组中保存每个字母出现的次数,然后按照出现次数的顺序对字符串进行排序~ 39 | 40 | class Solution { 41 | public: 42 | string frequencySort(string s) { 43 | int cnt[256] = {0}; 44 | for(int i = 0; i < s.length(); i++) 45 | cnt[s[i]]++; 46 | sort(s.begin(), s.end(), [&](char a, char b) { 47 | return cnt[a] > cnt[b] || (cnt[a] == cnt[b] && a < b); 48 | }); 49 | return s; 50 | }; 51 | }; -------------------------------------------------------------------------------- /C++/453. Minimum Moves to Equal Array Elements.cpp: -------------------------------------------------------------------------------- 1 | 453. Minimum Moves to Equal Array Elements 2 | Contributors: amehrotra2610 3 | Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1. 4 | 5 | Example: 6 | 7 | Input: 8 | [1,2,3] 9 | 10 | Output: 11 | 3 12 | 13 | Explanation: 14 | Only three moves are needed (remember each move increments two elements): 15 | 16 | [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4] 17 | 18 | 分析:每次n-1个数都+1,最后所有数都相等,其实等价于每次将其中一个数-1,最后所有数都相等。 19 | 因为每次只能减一个数,那肯定是将除了最小数minn之外的其他所有数一次次减,直到他们等于都最小数minn。所以cnt就等于所有数与最小数之间的差距的和(因为每次只能减去一个数,且只能减去1,所以差为多少就要减去多少次~) 20 | 先求出数组的最小值minn,然后累加的所有数和minn之间的差即为所求~ 21 | 22 | class Solution { 23 | public: 24 | int minMoves(vector& nums) { 25 | int minn = INT_MAX; 26 | for(int i = 0; i < nums.size(); i++) 27 | minn = min(minn, nums[i]); 28 | int cnt = 0; 29 | for(int i = 0; i < nums.size(); i++) 30 | cnt += nums[i] - minn; 31 | return cnt; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /C++/461. Hamming Distance.cpp: -------------------------------------------------------------------------------- 1 | 461. Hamming Distance 2 | The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 3 | 4 | Given two integers x and y, calculate the Hamming distance. 5 | 6 | Note: 7 | 0 ≤ x, y < 2^31. 8 | 9 | Example: 10 | 11 | Input: x = 1, y = 4 12 | 13 | Output: 2 14 | 15 | Explanation: 16 | 1 (0 0 0 1) 17 | 4 (0 1 0 0) 18 | ↑ ↑ 19 | 20 | The above arrows point to positions where the corresponding bits are different. 21 | 22 | 分析:将x和y不断右移一位,然后比较他们的最后一位。对于右移一位,采用x / 2和 y / 2的方式,对于比较最后一位,即比较x % 2 和 y % 2,统计不相同的次数cnt,直到x和y都等于0为止 23 | 24 | class Solution { 25 | public: 26 | int hammingDistance(int x, int y) { 27 | int cnt = 0; 28 | while(x != 0 || y != 0) { 29 | if(x % 2 != y % 2) 30 | cnt++; 31 | x /= 2; 32 | y /= 2; 33 | } 34 | return cnt; 35 | } 36 | }; -------------------------------------------------------------------------------- /C++/462. Minimum Moves to Equal Array Elements II.cpp: -------------------------------------------------------------------------------- 1 | 462. Minimum Moves to Equal Array Elements II 2 | Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1. 3 | 4 | You may assume the array's length is at most 10,000. 5 | 6 | Example: 7 | 8 | Input: 9 | [1,2,3] 10 | 11 | Output: 12 | 2 13 | 14 | Explanation: 15 | Only two moves are needed (remember each move increments or decrements one element): 16 | 17 | [1,2,3] => [2,2,3] => [2,2,2] 18 | 19 | 题目大意:给一个非空整数数组,每次可以将数组中一个元素+1或者-1,求最少需要多少次这样的操作,才能使数组中所有的数都想等~ 20 | 分析:让所有数都等于那个第n/2大的数字~首先用nth_element(nums.begin(), nums.begin() + n / 2, nums.end());将第n/2大的数字放到最中间,然后取得它的值为mid,最后遍历数组,累加所有元素与mid的差的绝对值即为所求~ 21 | 22 | class Solution { 23 | public: 24 | int minMoves2(vector& nums) { 25 | int result = 0, n = nums.size(); 26 | nth_element(nums.begin(), nums.begin() + n / 2, nums.end()); 27 | int mid = *(nums.begin() + n / 2); 28 | for(int i = 0; i < n; i++) 29 | result += abs(nums[i] - mid); 30 | return result; 31 | } 32 | }; -------------------------------------------------------------------------------- /C++/476. Number Complement.cpp: -------------------------------------------------------------------------------- 1 | 476. Number Complement 2 | Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation. 3 | 4 | Note: 5 | The given integer is guaranteed to fit within the range of a 32-bit signed integer. 6 | You could assume no leading zero bit in the integer’s binary representation. 7 | Example 1: 8 | Input: 5 9 | Output: 2 10 | Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. 11 | Example 2: 12 | Input: 1 13 | Output: 0 14 | Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. 15 | 16 | 分析:mask - 1为和num二进制位等长的所有位数为1的数,与num取^可以得到和num相反的数字。 17 | 18 | class Solution { 19 | public: 20 | int findComplement(int num) { 21 | int temp = num, mask = 1; 22 | while(temp != 0) { 23 | temp = temp >> 1; 24 | mask = mask << 1; 25 | } 26 | return num ^ (mask - 1); 27 | } 28 | }; -------------------------------------------------------------------------------- /C++/477. Total Hamming Distance.cpp: -------------------------------------------------------------------------------- 1 | 477. Total Hamming Distance 2 | The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 3 | 4 | Now your job is to find the total Hamming distance between all pairs of the given numbers. 5 | 6 | Example: 7 | Input: 4, 14, 2 8 | 9 | Output: 6 10 | 11 | Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just 12 | showing the four bits relevant in this case). So the answer will be: 13 | HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. 14 | Note: 15 | Elements of the given array are in the range of 0 to 10^9 16 | Length of the array will not exceed 10^4. 17 | 18 | 题目大意:两个数字的二进制表示中,相应的位不相同的个数即为这两个数的Hamming距离。给出一组数,计算他们每两对构成的Hamming距离的总和~ 19 | 分析:遍历数组中所有数的相同某位,如果有cnt个1,n-cnt个0,则这一位能够构成的Hamming距离为cnt * (n - cnt)~所以从第0位开始一直计算到第32位,将所有位贡献的Hamming距离总和相加即可得到总的Hamming距离~ 20 | 21 | class Solution { 22 | public: 23 | int totalHammingDistance(vector& nums) { 24 | int result = 0, n = nums.size(); 25 | for(int i = 0; i < 32; i++) { 26 | int cnt = 0; 27 | for(int j = 0; j < n; j++) { 28 | if(nums[j] >> i & 1 == 1) 29 | cnt++; 30 | } 31 | result += cnt * (n - cnt); 32 | } 33 | return result; 34 | } 35 | }; -------------------------------------------------------------------------------- /C++/479. Largest Palindrome Product.cpp: -------------------------------------------------------------------------------- 1 | 479. Largest Palindrome Product 2 | Find the largest palindrome made from the product of two n-digit numbers. 3 | Since the result could be very large, you should return the largest palindrome mod 1337. 4 | Example: 5 | Input: 2 6 | Output: 987 7 | Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 8 | Note: 9 | The range of n is [1,8]. 10 | 11 | 题目大意:找到由两个n位数字乘积得到的最大回文。由于结果可能非常大,返回最大回文的%1337后的结果。 12 | 分析:l是两位数的最小值,r是两位数的最大值,从r到1能够组成的回文是r的字符串+r倒置后的字符串组成的字符串,将这个回文字串转为long型的ans,j从r到根号ans中,判断是否有j可以满足能被ans整除的j,并且这个除以的结果是小于r的,如果找到了返回ans%1337的结果,因为如果n == 1的时候比较特殊,组成的回文串是9,所以如果for循环后依然没有返回,说明遇到了n=1,那么最后就单独返回9~ 13 | 14 | class Solution { 15 | public: 16 | int largestPalindrome(int n) { 17 | int l = pow(10, n-1), r = pow(10, n) - 1; 18 | for (int i = r; i >= 1; i--) { 19 | string s = to_string(i); 20 | string t = s; 21 | reverse(t.begin(), t.end()); 22 | long ans = stol(s + t); 23 | for (long j = r; j * j >= ans; j--) 24 | if (ans % j == 0 && ans / j <= r) return ans % 1337; 25 | } 26 | return 9; 27 | } 28 | }; -------------------------------------------------------------------------------- /C++/485. Max Consecutive Ones.cpp: -------------------------------------------------------------------------------- 1 | 485. Max Consecutive Ones 2 | Given a binary array, find the maximum number of consecutive 1s in this array. 3 | 4 | Example 1: 5 | Input: [1,1,0,1,1,1] 6 | Output: 3 7 | Explanation: The first two digits or the last three digits are consecutive 1s. 8 | The maximum number of consecutive 1s is 3. 9 | Note: 10 | 11 | The input array will only contain 0 and 1. 12 | The length of input array is a positive integer and will not exceed 10,000 13 | 14 | 分析:设立cnt数组,表示在nums[i]处当前连续的1的值,maxn取其最大的值,在遇到nums[i] == 0的时候更新maxn的值。最后还要更新一下防止最后一个是1. 15 | 16 | class Solution { 17 | public: 18 | int findMaxConsecutiveOnes(vector& nums) { 19 | vector cnt(nums.size()); 20 | int maxn = 0; 21 | cnt[0] = nums[0]; 22 | for(int i = 1; i < nums.size(); i++) { 23 | if(nums[i] == 0) { 24 | cnt[i] = 0; 25 | maxn = max(maxn, cnt[i-1]); 26 | } else { 27 | cnt[i] = cnt[i-1] + 1; 28 | } 29 | } 30 | maxn = max(maxn, cnt[nums.size() - 1]); 31 | return maxn; 32 | } 33 | }; -------------------------------------------------------------------------------- /C++/49. Group Anagrams.cpp: -------------------------------------------------------------------------------- 1 | 49. Group Anagrams 2 | Given an array of strings, group anagrams together. 3 | 4 | For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], 5 | Return: 6 | 7 | [ 8 | ["ate", "eat","tea"], 9 | ["nat","tan"], 10 | ["bat"] 11 | ] 12 | Note: All inputs will be in lower-case. 13 | 14 | 题目大意:给一组字符串,将这些字符串分组,按照同字母异序词为一组 15 | 分析:每一个s排序后的字符串为t,将s保存在以t为键的map中,这样同字母异序词即为一组。遍历map中的每一个vector,将其保存在ans中,ans即为结果~ 16 | 17 | class Solution { 18 | public: 19 | vector> groupAnagrams(vector& strs) { 20 | vector> ans; 21 | map> mp; 22 | for (auto s : strs) { 23 | string t = s; 24 | sort(t.begin(), t.end()); 25 | mp[t].push_back(s); 26 | } 27 | for (auto m : mp) { 28 | vector temp(m.second.begin(), m.second.end()); 29 | ans.push_back(temp); 30 | } 31 | return ans; 32 | } 33 | }; -------------------------------------------------------------------------------- /C++/504. Base 7.cpp: -------------------------------------------------------------------------------- 1 | 504. Base 7 2 | Given an integer, return its base 7 string representation. 3 | 4 | Example 1: 5 | Input: 100 6 | Output: "202" 7 | Example 2: 8 | Input: -7 9 | Output: "-10" 10 | Note: The input will be in range of [-1e7, 1e7]. 11 | 12 | 题目大意:给一个整数,以字符串形式返回它的7进制~ 13 | 分析:如果num等于0则直接return 0,如果num小于0则变为相反数,且标记sign为-,每次将对num 取余 7的结果插入result字符串的最前面,并将num / 7,最后返回sign + result的字符串结果~ 14 | 15 | class Solution { 16 | public: 17 | string convertToBase7(int num) { 18 | if (num == 0) return "0"; 19 | string sign = ""; 20 | if (num < 0) { 21 | num = 0 - num; 22 | sign = "-"; 23 | } 24 | string result = ""; 25 | while (num != 0) { 26 | result = to_string(num % 7) + result; 27 | num = num / 7; 28 | } 29 | return sign + result; 30 | } 31 | }; -------------------------------------------------------------------------------- /C++/507. Perfect Number.cpp: -------------------------------------------------------------------------------- 1 | 507. Perfect Number 2 | We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself. 3 | 4 | Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not. 5 | Example: 6 | Input: 28 7 | Output: True 8 | Explanation: 28 = 1 + 2 + 4 + 7 + 14 9 | Note: The input number n will not exceed 100,000,000. (1e8) 10 | 11 | 题目大意:完美数字是指它的所有可以整除的正数中除了它本身,其他数字之和等于这个数字的数。给一个正整数n,写一个函数,当它是一个完美数字的时候返回true否则false。 12 | 分析:从2~sqrt(num),累加所有i和num/i【因为如果从1~num一个个试是否可以整除的话会超时,而且也没必要,因为知道了除数a必然就知道了num/a这个数字也是它的除数】因为最后还有一个1没有加,所以sum一开始为1,然后返回num == sum,注意如果num本身为1,则要return false,因为1的唯一一个除数1是它本身不能累加,所以1不满足条件。 13 | 14 | class Solution { 15 | public: 16 | bool checkPerfectNumber(int num) { 17 | if (num == 1) return false; 18 | int sum = 1; 19 | for (int i = 2; i <= sqrt(num); i++) 20 | if (num % i == 0) sum = sum + (num / i) + i; 21 | return num == sum; 22 | } 23 | }; -------------------------------------------------------------------------------- /C++/513. Find Bottom Left Tree Value.cpp: -------------------------------------------------------------------------------- 1 | 513. Find Bottom Left Tree Value 2 | Given a binary tree, find the leftmost value in the last row of the tree. 3 | Example 1: 4 | Input: 5 | 2 6 | / \ 7 | 1 3 8 | Output: 9 | 1 10 | Example 2: 11 | Input: 12 | 1 13 | / \ 14 | 2 3 15 | / / \ 16 | 4 5 6 17 | / 18 | 7 19 | Output: 20 | 7 21 | 22 | 题目大意:给一个二叉树,找它的最后一行的最左边的结点的值~ 23 | 分析:广度优先搜索,对每一层进行遍历,result每次保存每一层的第一个值,最后层序遍历完成之后的result即为最后一行的第一个结点的值~ 24 | 25 | class Solution { 26 | public: 27 | int findBottomLeftValue(TreeNode* root) { 28 | int result = root->val; 29 | queue q; 30 | q.push(root); 31 | TreeNode* temp; 32 | while (!q.empty()) { 33 | int size = q.size(); 34 | result = q.front()->val; 35 | while (size--) { 36 | temp = q.front(); 37 | q.pop(); 38 | if (temp->left != NULL) q.push(temp->left); 39 | if (temp->right != NULL) q.push(temp->right); 40 | } 41 | } 42 | return result; 43 | } 44 | }; -------------------------------------------------------------------------------- /C++/515. Find Largest Value in Each Tree Row.cpp: -------------------------------------------------------------------------------- 1 | 515. Find Largest Value in Each Tree Row 2 | 3 | You need to find the largest value in each row of a binary tree. 4 | 5 | Example: 6 | Input: 7 | 8 | 1 9 | / \ 10 | 3 2 11 | / \ \ 12 | 5 3 9 13 | 14 | Output: [1, 3, 9] 15 | 16 | 题目大意:找二叉树每一层最大的数~然后返回一个数组表示每一层的最大的数~ 17 | 分析:先用广度优先搜索对二叉树进行层序遍历,每一层设立maxn保存每一层的最大值,然后在每一层遍历完毕之后将maxn的值放入result数组中~ 18 | 19 | class Solution { 20 | public: 21 | vector largestValues(TreeNode* root) { 22 | vector result; 23 | queue q; 24 | if (root == NULL) return result; 25 | q.push(root); 26 | TreeNode *temp; 27 | while (!q.empty()) { 28 | int size = q.size(); 29 | int maxn = INT_MIN; 30 | while (size--) { 31 | temp = q.front(); 32 | q.pop(); 33 | maxn = max(maxn, temp->val); 34 | if (temp->left != NULL) q.push(temp->left); 35 | if (temp->right != NULL) q.push(temp->right); 36 | } 37 | result.push_back(maxn); 38 | } 39 | return result; 40 | } 41 | }; -------------------------------------------------------------------------------- /C++/516. Longest Palindromic Subsequence.cpp: -------------------------------------------------------------------------------- 1 | 516. Longest Palindromic Subsequence 2 | Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000. 3 | 4 | Example 1: 5 | Input: 6 | 7 | "bbbab" 8 | Output: 9 | 4 10 | One possible longest palindromic subsequence is "bbbb". 11 | Example 2: 12 | Input: 13 | 14 | "cbbd" 15 | Output: 16 | 2 17 | One possible longest palindromic subsequence is "bb". 18 | 19 | 题目大意:给一个字符串s,找最长回文子串~返回这个最长回文子串的长度~ 20 | 分析:使用动态规划解决~设立一个len行len列的dp数组~dp[i][j]表示字符串i~j下标所构成的子串中最长回文子串的长度~最后我们需要返回的是dp[0][len-1]的值~ 21 | dp数组这样更新:首先i指针从尾到头遍历,j指针从i指针后面一个元素开始一直遍历到尾部~一开始dp[i][i]的值都为1,如果当前i和j所指元素相等,说明能够加到i~j的回文子串的长度中,所以更新dp[i][j] = dp[i+1][j-1] + 2; 如果当前元素不相等,那么说明这两个i、j所指元素对回文串无贡献,则dp[i][j]就是从dp[i+1][j]和dp[i][j-1]中选取较大的一个值即可~ 22 | 23 | class Solution { 24 | public: 25 | int longestPalindromeSubseq(string s) { 26 | int len = s.length(); 27 | vector> dp(len, vector(len)); 28 | for (int i = len - 1; i >= 0; i--) { 29 | dp[i][i] = 1; 30 | for (int j = i + 1; j < len; j++) { 31 | if (s[i] == s[j]) 32 | dp[i][j] = dp[i+1][j-1] + 2; 33 | else 34 | dp[i][j] = max(dp[i+1][j], dp[i][j-1]); 35 | } 36 | } 37 | return dp[0][len-1]; 38 | } 39 | 40 | }; -------------------------------------------------------------------------------- /C++/520. Detect Capital.cpp: -------------------------------------------------------------------------------- 1 | 520. Detect Capital 2 | Given a word, you need to judge whether the usage of capitals in it is right or not. 3 | 4 | We define the usage of capitals in a word to be right when one of the following cases holds: 5 | 6 | All letters in this word are capitals, like "USA". 7 | All letters in this word are not capitals, like "leetcode". 8 | Only the first letter in this word is capital if it has more than one letter, like "Google". 9 | Otherwise, we define that this word doesn't use capitals in a right way. 10 | Example 1: 11 | Input: "USA" 12 | Output: True 13 | Example 2: 14 | Input: "FlaG" 15 | Output: False 16 | 17 | 题目大意:判断一个字母是否大小写正确:要么全是大写,要么全是小写,或者首字母大写其他小写,否则不满足题意~ 18 | 分析:判断word[0]和word[1]的大小写,如果word[0]是小写,那后面必须是小写,如果word[0]是大写word[1]是小写,那后面也必须是小写,如果word[0]是大写word[1]也是大写那么后面必须都是大写~ 19 | 20 | class Solution { 21 | public: 22 | bool detectCapitalUse(string word) { 23 | if (word.length() <= 1) return true; 24 | if (islower(word[0]) || (isupper(word[0]) && islower(word[1]))) { 25 | for (int i = 1; i < word.length(); i++) 26 | if (isupper(word[i])) return false; 27 | } else { 28 | for (int i = 1; i < word.length(); i++) 29 | if (islower(word[i])) return false; 30 | } 31 | return true; 32 | } 33 | }; -------------------------------------------------------------------------------- /C++/525. Contiguous Array.cpp: -------------------------------------------------------------------------------- 1 | 525. Contiguous Array 2 | Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. 3 | 4 | Example 1: 5 | Input: [0,1] 6 | Output: 2 7 | Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1. 8 | Example 2: 9 | Input: [0,1,0] 10 | Output: 2 11 | Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. 12 | Note: The length of the given binary array will not exceed 50,000. 13 | 14 | 题目大意:给一个二进制数组,找最长的连续子数组,要求子数组里面的0和1的个数相等~ 15 | 分析:0和1数组,可以考虑把0换成-1,变成-1和0数组,那么本质上就是找是否有下标从i~j的总和为0的子数组~ 16 | 令map保存sum和sum对应的下标的值,遍历数组每次计算数组当前的sum,如果当前sum之前已经出现过,比如说之前有过一个sum = 2,现在又sum = 2了,说明在第一次sum等于2的时候,它前面所有元素加起来总和是2,那么在它前面去掉2个元素1就能满足0,同理当前的sum = 2也可以通过去掉最前面的2个元素1使sum = 0,所以看看i - m[sum]是否比之前的最大值大,如果比之前最大值大就更新最大值~ 17 | 18 | class Solution { 19 | public: 20 | int findMaxLength(vector& nums) { 21 | int result = 0, sum = 0; 22 | for (int i = 0; i < nums.size(); i++) 23 | if (nums[i] == 0) nums[i] = -1; 24 | map m; 25 | m[0] = -1; 26 | for (int i = 0; i < nums.size(); i++) { 27 | sum += nums[i]; 28 | if (m.find(sum) != m.end()) 29 | result = max(result, i - m[sum]); 30 | else 31 | m[sum] = i; 32 | } 33 | return result; 34 | } 35 | }; -------------------------------------------------------------------------------- /C++/530. Minimum Absolute Difference in BST.cpp: -------------------------------------------------------------------------------- 1 | 530. Minimum Absolute Difference in BST 2 | Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes. 3 | 4 | Example: 5 | 6 | Input: 7 | 8 | 1 9 | \ 10 | 3 11 | / 12 | 2 13 | 14 | Output: 15 | 1 16 | 17 | Explanation: 18 | The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3). 19 | Note: There are at least two nodes in this BST. 20 | 21 | 题目大意:给一棵二叉搜索树,结点的值都为非负,找到两个元素值之差的绝对值的最小值~ 22 | 分析:二叉搜索树,用中序遍历后得到的结果是从小到大的元素,遍历这个中序遍历后的结果数组,就可以得到两个元素值之差的绝对值的最小值~ 23 | 24 | class Solution { 25 | public: 26 | int getMinimumDifference(TreeNode* root) { 27 | inOrder(root); 28 | int result = INT_MAX; 29 | for (int i = 1; i < tree.size(); i++) 30 | result = min(result, tree[i] - tree[i-1]); 31 | return result; 32 | } 33 | private: 34 | vector tree; 35 | void inOrder(TreeNode* root) { 36 | if (root->left != NULL) inOrder(root->left); 37 | tree.push_back(root->val); 38 | if (root->right != NULL) inOrder(root->right); 39 | } 40 | }; -------------------------------------------------------------------------------- /C++/537. Complex Number Multiplication.cpp: -------------------------------------------------------------------------------- 1 | 537. Complex Number Multiplication 2 | Given two strings representing two complex numbers. 3 | 4 | You need to return a string representing their multiplication. Note i2 = -1 according to the definition. 5 | 6 | Example 1: 7 | Input: "1+1i", "1+1i" 8 | Output: "0+2i" 9 | Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i. 10 | Example 2: 11 | Input: "1+-1i", "1+-1i" 12 | Output: "0+-2i" 13 | Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i. 14 | Note: 15 | 16 | The input strings will not have extra blank. 17 | The input strings will be given in the form of a+bi, where the integer a and b will both belong to the range of [-100, 100]. And the output should be also in this form. 18 | 19 | 题目大意:给两个复数,求两个数的乘积 20 | 分析:使用sscanf和ssprinf,(m+ni)*(p+qi)=(m*p-n*q)*(n*p+m*q)i 21 | 22 | class Solution { 23 | public: 24 | string complexNumberMultiply(string a, string b) { 25 | char t[200]; 26 | int m, n, p, q; 27 | sscanf(a.c_str(), "%d+%di", &m, &n); 28 | sscanf(b.c_str(), "%d+%di", &p, &q); 29 | sprintf(t, "%d+%di", (m*p-n*q), (n*p+m*q)); 30 | string ans = t; 31 | return ans; 32 | } 33 | }; -------------------------------------------------------------------------------- /C++/538. Convert BST to Greater Tree.cpp: -------------------------------------------------------------------------------- 1 | 538. Convert BST to Greater Tree 2 | Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST. 3 | 4 | Example: 5 | 6 | Input: The root of a Binary Search Tree like this: 7 | 5 8 | / \ 9 | 2 13 10 | 11 | Output: The root of a Greater Tree like this: 12 | 18 13 | / \ 14 | 20 13 15 | 题目大意:给定一个二叉搜索树(BST),将其转换为一个Greater Tree,使得原始BST的每个结点的键值被改变为原始键加上所有比BST中的原始键大的键的总和。 16 | 分析:因为BST的中序遍历是从小到大排列,那么BST的右根左遍历方式得到的就是从大到小的排列,遍历过程中对当前结点累计到sum中,并将sum的值赋值给当前结点,最后返回这棵树即可~ 17 | 18 | 19 | /** 20 | * Definition for a binary tree node. 21 | * struct TreeNode { 22 | * int val; 23 | * TreeNode *left; 24 | * TreeNode *right; 25 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 26 | * }; 27 | */ 28 | class Solution { 29 | public: 30 | TreeNode* convertBST(TreeNode* root) { 31 | dfs(root); 32 | return root; 33 | } 34 | private: 35 | int sum = 0; 36 | void dfs(TreeNode* root) { 37 | if (root == NULL) return; 38 | if (root->right != NULL) dfs(root->right); 39 | sum += root->val; 40 | root->val = sum; 41 | if (root->left != NULL) dfs(root->left); 42 | } 43 | }; -------------------------------------------------------------------------------- /C++/541. Reverse String II.cpp: -------------------------------------------------------------------------------- 1 | 541. Reverse String II 2 | Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original. 3 | Example: 4 | Input: s = "abcdefg", k = 2 5 | Output: "bacdfeg" 6 | Restrictions: 7 | The string consists of lower English letters only. 8 | Length of the given string and k will in the range [1, 10000] 9 | 10 | 题目大意:给一个字符串s和一个整数k,每2k长度倒置前k个字符串,如果最后剩余的长度小于k则全都倒置,否则如果剩余的长度大于k小于2k,倒置前k个,返回倒置后的字符串~ 11 | 分析:遍历字符串,步长为2k,每次倒置s.begin() + i~s.begin() + i + k的字符串,如果i + k > s.length()就倒置s.begin() + i~s.begin() + s.length()即可~O(∩_∩)O~ 12 | 13 | class Solution { 14 | public: 15 | string reverseStr(string s, int k) { 16 | for (int i = 0; i < s.length(); i+=2*k) { 17 | int t = min((i + k), (int)s.length()); 18 | reverse(s.begin() + i, s.begin() + t); 19 | } 20 | return s; 21 | } 22 | }; -------------------------------------------------------------------------------- /C++/543. Diameter of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | 543. Diameter of Binary Tree 2 | Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. 3 | 4 | Example: 5 | Given a binary tree 6 | 1 7 | / \ 8 | 2 3 9 | / \ 10 | 4 5 11 | Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3]. 12 | 13 | Note: The length of path between two nodes is represented by the number of edges between them. 14 | 15 | 题目大意:给一个二叉树,计算出任意两个节点中最长的长度并返回结果~ 16 | 分析:计算每个节点的深度,并在dfs过程中将每个节点左边深度+右边深度的值的最大的值保存在ans中返回~ 17 | 18 | class Solution { 19 | public: 20 | int diameterOfBinaryTree(TreeNode* root) { 21 | dfs(root); 22 | return ans; 23 | } 24 | private: 25 | int ans = 0; 26 | int dfs(TreeNode* root) { 27 | if (root == NULL) return 0; 28 | int l = dfs(root->left), r = dfs(root->right); 29 | ans = max(ans, l + r); 30 | return max(l, r) + 1; 31 | } 32 | }; -------------------------------------------------------------------------------- /C++/551. Student Attendance Record I.cpp: -------------------------------------------------------------------------------- 1 | 551. Student Attendance Record I 2 | You are given a string representing an attendance record for a student. The record only contains the following three characters: 3 | 'A' : Absent. 4 | 'L' : Late. 5 | 'P' : Present. 6 | A student could be rewarded if his attendance record doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late). 7 | 8 | You need to return whether the student could be rewarded according to his attendance record. 9 | 10 | Example 1: 11 | Input: "PPALLP" 12 | Output: True 13 | Example 2: 14 | Input: "PPALLL" 15 | Output: False 16 | 17 | 分析:正则表达式匹配,如果出现三次连续的LLL或者两次AA则返回false 18 | 19 | class Solution { 20 | public: 21 | bool checkRecord(string s) { 22 | return !regex_match(s, regex(".*LLL.*|.*A.*A.*")); 23 | } 24 | }; -------------------------------------------------------------------------------- /C++/557. Reverse Words in a String III.cpp: -------------------------------------------------------------------------------- 1 | 557. Reverse Words in a String III 2 | Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. 3 | 4 | Example 1: 5 | Input: "Let's take LeetCode contest" 6 | Output: "s'teL ekat edoCteeL tsetnoc" 7 | Note: In the string, each word is separated by single space and there will not be any extra space in the string. 8 | 9 | 题目大意:将一个字符串的每个单词反转~ 10 | 分析:将每个单词放入栈中,当遇到空格或者最后一个字符的时候,说明当前栈内为一个完整的单词,那么就将栈内的单词按字符一个个出栈加入result字符串中,根据flag的值判断是否是第一个单词,如果不是第一个单词就要在result的后面加一个空格~ 11 | 12 | class Solution { 13 | public: 14 | string reverseWords(string s) { 15 | string result = ""; 16 | stack word; 17 | int flag = 0; 18 | for (int i = 0; i < s.length(); i++) { 19 | if (s[i] != ' ') 20 | word.push(s[i]); 21 | if (s[i] == ' ' || i == s.length() - 1) { 22 | if (flag == 1) result += " "; 23 | while (!word.empty()) { 24 | result += word.top(); 25 | word.pop(); 26 | flag = 1; 27 | } 28 | } 29 | } 30 | return result; 31 | } 32 | }; -------------------------------------------------------------------------------- /C++/561. Array Partition I.cpp: -------------------------------------------------------------------------------- 1 | 561. Array Partition I 2 | Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible. 3 | 4 | Example 1: 5 | Input: [1,4,3,2] 6 | 7 | Output: 4 8 | Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4). 9 | Note: 10 | n is a positive integer, which is in the range of [1, 10000]. 11 | All the integers in the array will be in the range of [-10000, 10000]. 12 | 13 | 题目大意:给2n个数,请把数字分为2个一组,问所有组(取每组数的较小的那一数字)累加的和最大为多少~ 14 | 分析:把数组从小到大排列,第1个、第3个、...第2n-1个数字之和即为所求~ 15 | 16 | class Solution { 17 | public: 18 | int arrayPairSum(vector& nums) { 19 | sort(nums.begin(), nums.end()); 20 | int ans = 0; 21 | for (int i = 0; i < nums.size(); i+=2) 22 | ans += nums[i]; 23 | return ans; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /C++/581. Shortest Unsorted Continuous Subarray.cpp: -------------------------------------------------------------------------------- 1 | 581. Shortest Unsorted Continuous Subarray 2 | Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too. 3 | 4 | You need to find the shortest such subarray and output its length. 5 | 6 | Example 1: 7 | Input: [2, 6, 4, 8, 10, 9, 15] 8 | Output: 5 9 | Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order. 10 | Note: 11 | Then length of the input array is in range [1, 10,000]. 12 | The input array may contain duplicates, so ascending order here means <=. 13 | 14 | 题目大意:给定一个整数数组,你需要找到一个连续的子数组,如果你按升序对这个子数组排序,那么整个数组将也是升序。你需要找到最短的这样的子数组并输出它的长度。 15 | 分析:对v排序,i找到第一个和排序后的数组v不相等的元素,j找到最后一个和排序后的数组v不相等的元素,如果i<=j说明存在这样一个长度,长度为j-i+1,否则不存在这样一个长度,则返回0 16 | 17 | class Solution { 18 | public: 19 | int findUnsortedSubarray(vector& nums) { 20 | vector v(nums); 21 | sort(v.begin(), v.end()); 22 | int i = 0, j = nums.size() - 1; 23 | while (i < nums.size() && nums[i] == v[i]) i++; 24 | while (j >= 0 && nums[j] == v[j]) j--; 25 | return i <= j ? j - i + 1 : 0; 26 | } 27 | }; -------------------------------------------------------------------------------- /C++/628. Maximum Product of Three Numbers.cpp: -------------------------------------------------------------------------------- 1 | 628. Maximum Product of Three Numbers 2 | Given an integer array, find three numbers whose product is maximum and output the maximum product. 3 | 4 | Example 1: 5 | Input: [1,2,3] 6 | Output: 6 7 | Example 2: 8 | Input: [1,2,3,4] 9 | Output: 24 10 | Note: 11 | The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000]. 12 | Multiplication of any three numbers in the input won’t exceed the range of 32-bit signed integer. 13 | 14 | 题目大意:给一个数组,找三个数字,使这三个数乘积最大,返回乘积的最大值 15 | 分析:先对数组排序,要么是最后三个数字乘积,要么可能会有负数,则是前两个数的乘积*最后一个数字的乘积,取这个两个乘积结果的最大值即可~ 16 | 17 | class Solution { 18 | public: 19 | int maximumProduct(vector& nums) { 20 | sort(nums.begin(), nums.end()); 21 | int n = nums.size(); 22 | return max(nums[0] * nums[1] * nums[n-1], nums[n-3] * nums[n-2] * nums[n-1]); 23 | } 24 | }; -------------------------------------------------------------------------------- /C++/633. Sum of Square Numbers.cpp: -------------------------------------------------------------------------------- 1 | 633. Sum of Square Numbers 2 | Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a2 + b2 = c. 3 | 4 | Example 1: 5 | Input: 5 6 | Output: True 7 | Explanation: 1 * 1 + 2 * 2 = 5 8 | Example 2: 9 | Input: 3 10 | Output: False 11 | 12 | 题目大意:给一个数c,判断是否存在两个数字a b满足a*a+b*b=c,存在就返回true,否则返回false 13 | 分析:i和j分别从根号c开始到0,如果找到了i * i + j * j == c就return true,如果i * i + j * j < c就break第二层for循环,最后如果都没有找到就返回false~ 14 | 15 | class Solution { 16 | public: 17 | bool judgeSquareSum(int c) { 18 | int t = sqrt(c); 19 | for (int i = t; i >= 0; i--) { 20 | for (int j = t; j >= 0; j--) { 21 | if (i * i + j * j == c) return true; 22 | if (i * i + j * j < c) break; 23 | } 24 | } 25 | return false; 26 | } 27 | }; -------------------------------------------------------------------------------- /C++/637. Average of Levels in Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | 637. Average of Levels in Binary Tree 2 | Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array. 3 | Example 1: 4 | Input: 5 | 3 6 | / \ 7 | 9 20 8 | / \ 9 | 15 7 10 | Output: [3, 14.5, 11] 11 | Explanation: 12 | The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11]. 13 | Note: 14 | The range of node’s value is in the range of 32-bit signed integer. 15 | 16 | 题目大意:计算一棵树的每一层结点的值的平均值 17 | 分析:用广度优先搜索,当!q.empty()时,每次将当前队列q中的元素个数保存在n中,表示当前层有n个元素,对这n个元素遍历取出每一个,然后将他们的孩子节点放入队列q中,并累加这一层元素的值保存在sum中,最后将sum/n的值放入ans数组中,返回ans数组即可~ 18 | 19 | class Solution { 20 | public: 21 | vector averageOfLevels(TreeNode* root) { 22 | vector ans; 23 | if (root == NULL) return ans; 24 | queue q; 25 | q.push(root); 26 | while(!q.empty()) { 27 | int n = q.size(); 28 | long long sum = 0; 29 | for (int i = 0; i < n; i++) { 30 | TreeNode* t = q.front(); 31 | q.pop(); 32 | if (t->left) q.push(t->left); 33 | if (t->right) q.push(t->right); 34 | sum += t->val; 35 | } 36 | ans.push_back(sum * 1.0 / n); 37 | } 38 | return ans; 39 | } 40 | }; -------------------------------------------------------------------------------- /C++/643. Maximum Average Subarray I.cpp: -------------------------------------------------------------------------------- 1 | 643. Maximum Average Subarray I 2 | Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value. 3 | 4 | Example 1: 5 | Input: [1,12,-5,-6,50,3], k = 4 6 | Output: 12.75 7 | Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75 8 | Note: 9 | 1 <= k <= n <= 30,000. 10 | Elements of the given array will be in the range [-10,000, 10,000]. 11 | 12 | 13 | 题目大意:给定一个由n个整数组成的数组,找到具有最大平均值的给定长度k的连续子数组。你需要输出最大的平均值~ 14 | 分析:sum[i]保存0~i个数字的和,每次将(sum[i]-sum[i-k])的最大值保存在ans中,然后返回ans*1.0/k 15 | 16 | class Solution { 17 | public: 18 | double findMaxAverage(vector& nums, int k) { 19 | if (nums.size() == 0) return 0.0; 20 | vector sum(nums.size()); 21 | sum[0] = nums[0]; 22 | for (int i = 1; i < nums.size(); i++) { 23 | sum[i] = sum[i-1] + nums[i]; 24 | if (i >= k - 1) ans = max(ans, sum[i] - sum[i-k]); 25 | } 26 | return ans * 1.0 / k; 27 | } 28 | }; -------------------------------------------------------------------------------- /C++/647. Palindromic Substrings.cpp: -------------------------------------------------------------------------------- 1 | 647. Palindromic Substrings 2 | Given a string, your task is to count how many palindromic substrings in this string. 3 | 4 | The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters. 5 | 6 | Example 1: 7 | Input: "abc" 8 | Output: 3 9 | Explanation: Three palindromic strings: "a", "b", "c". 10 | Example 2: 11 | Input: "aaa" 12 | Output: 6 13 | Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". 14 | Note: 15 | The input string length won’t exceed 1000. 16 | 17 | 题目大意:给定一个字符串,计算这个字符串中有多少回文子串。(具有不同start下标或end下标的子字符串即使包含相同的字符也会被计为不同的子字符串。) 18 | 分析:对于s[i]来说,检测s[i-j]==s[i+j]是否成立,每一次相等就ans++、检测s[i-j-1]==s[i+j]是否成立,每次成立就ans++,最后返回ans的值~ 19 | 20 | class Solution { 21 | public: 22 | int countSubstrings(string s) { 23 | int ans = 0, n = s.length(); 24 | for (int i = 0; i < n; i++) { 25 | for (int j = 0; i + j < n && i - j >= 0 && s[i-j] == s[i+j]; j++) ans++; 26 | for (int j = 0; i + j < n && i - j - 1 >=0 && s[i-j-1] == s[i+j]; j++) ans++; 27 | } 28 | return ans; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /C++/650. 2 Keys Keyboard.cpp: -------------------------------------------------------------------------------- 1 | 650. 2 Keys Keyboard 2 | Initially on a notepad only one character 'A' is present. You can perform two operations on this notepad for each step: 3 | 4 | Copy All: You can copy all the characters present on the notepad (partial copy is not allowed). 5 | Paste: You can paste the characters which are copied last time. 6 | Given a number n. You have to get exactly n 'A' on the notepad by performing the minimum number of steps permitted. Output the minimum number of steps to get n 'A'. 7 | 8 | Example 1: 9 | Input: 3 10 | Output: 3 11 | Explanation: 12 | Intitally, we have one character 'A'. 13 | In step 1, we use Copy All operation. 14 | In step 2, we use Paste operation to get 'AA'. 15 | In step 3, we use Paste operation to get 'AAA'. 16 | Note: 17 | The n will be in the range [1, 1000]. 18 | 19 | 题目大意:一开始给一个A,每次只能复制所有、或者粘贴上一次复制的内容。问要想最后变成n个A,至少得经过多少步~ 20 | 分析:可以用贪心算法解决,i从2到√n,尝试是否能被n整除,如果能被整除,说明可以通过复制1次粘贴i-1次得到,则计数器ans加上i次,然后将n除以i。再次判断是否能被i整除,直至不能整除为止。然后尝试下一个i……最终n如果等于1则直接返回ans,否则要加上n表示对A复制一次粘贴n-1次 21 | 22 | class Solution { 23 | public: 24 | int minSteps(int n) { 25 | int ans = 0; 26 | for (int i = 2; i <= sqrt(n); i++) { 27 | while (n % i == 0) { 28 | ans += i; 29 | n /= i; 30 | } 31 | } 32 | if (n != 1) ans += n; 33 | return ans; 34 | } 35 | }; -------------------------------------------------------------------------------- /C++/653. Two Sum IV - Input is a BST.cpp: -------------------------------------------------------------------------------- 1 | 653. Two Sum IV - Input is a BST 2 | Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target. 3 | 4 | Example 1: 5 | Input: 6 | 5 7 | / \ 8 | 3 6 9 | / \ \ 10 | 2 4 7 11 | 12 | Target = 9 13 | 14 | Output: True 15 | Example 2: 16 | Input: 17 | 5 18 | / \ 19 | 3 6 20 | / \ \ 21 | 2 4 7 22 | 23 | Target = 28 24 | 25 | Output: False 26 | 27 | 题目大意:给一棵二叉搜索树和一个目标数字,如果这棵树中存在两个元素,这两个元素的和等于目标数字,则返回true 28 | 分析:设立set,如果set里面存在k - 当前结点的值,则返回true;每次将当前结点的值放入set中,否则返回它左子树的结果 || 右子树的结果。相当于每次比较的是当前结点i之前的所有数字中是否有和i相加为k的数字,如果有就返回true,否则就继续遍历左子树和右子树,只要其中一个满足就返回true 29 | 30 | /** 31 | * Definition for a binary tree node. 32 | * struct TreeNode { 33 | * int val; 34 | * TreeNode *left; 35 | * TreeNode *right; 36 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 37 | * }; 38 | */ 39 | class Solution { 40 | public: 41 | set s; 42 | bool findTarget(TreeNode* root, int k) { 43 | if (root == NULL) return false; 44 | if (s.count(k - root->val)) return true; 45 | s.insert(root->val); 46 | return findTarget(root->left, k) || findTarget(root->right, k); 47 | } 48 | }; -------------------------------------------------------------------------------- /C++/657. Judge Route Circle.cpp: -------------------------------------------------------------------------------- 1 | 657. Judge Route Circle 2 | Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place. 3 | 4 | The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle. 5 | 6 | Example 1: 7 | Input: "UD" 8 | Output: true 9 | Example 2: 10 | Input: "LL" 11 | Output: false 12 | 13 | 题目大意:最初,位置(0,0)处有一个机器人。 给出它的一系列动作,判断这个机器人是否有一个圆圈,这意味着它回到原来的位置。移动顺序由一个字符串表示。 而每一个动作都是由一个人物来表现的。 有效的机器人移动R(右),L(左),U(上)和D(下)。 输出应该是真或假,表示机器人是否成圈。 14 | 分析:计算UDLR出现的次数保存在map中,如果U和D出现的次数相同且L和R出现的次数相同则为true~ 15 | 16 | class Solution { 17 | public: 18 | bool judgeCircle(string moves) { 19 | map m; 20 | for(int i = 0; i < moves.length(); i++) m[moves[i]]++; 21 | return (m['L'] == m['R'] && m['U'] == m['D']); 22 | } 23 | }; -------------------------------------------------------------------------------- /C++/674. Longest Continuous Increasing Subsequence.cpp: -------------------------------------------------------------------------------- 1 | 674. Longest Continuous Increasing Subsequence 2 | Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray). 3 | 4 | Example 1: 5 | Input: [1,3,5,4,7] 6 | Output: 3 7 | Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3. 8 | Even though [1,3,5,7] is also an increasing subsequence, it is not a continuous one where 5 and 7 are separated by 4. 9 | Example 2: 10 | Input: [2,2,2,2,2] 11 | Output: 1 12 | Explanation: The longest continuous increasing subsequence is [2], its length is 1. 13 | Note: Length of the array will not exceed 10,000. 14 | 15 | 题目大意:给一个乱序数组,返回这个数组中递增连续子序列中最长的长度~ 16 | 分析:遍历从i = 1到结尾,每次比较nums[i-1]和nums[i],如果是递增的就将temp++,否则temp=1,每次将temp最大值保存在ans中,最后返回ans的值~ 17 | 18 | class Solution { 19 | public: 20 | int findLengthOfLCIS(vector& nums) { 21 | int temp = 1, ans = 1; 22 | for (int i = 1; i < nums.size(); i++) { 23 | temp = (nums[i-1] < nums[i]) ? temp + 1 : 1; 24 | ans = max(ans, temp); 25 | } 26 | return nums.size() == 0 ? 0 : ans; 27 | } 28 | }; -------------------------------------------------------------------------------- /C++/717. 1-bit and 2-bit Characters.cpp: -------------------------------------------------------------------------------- 1 | 717. 1-bit and 2-bit Characters 2 | We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11). 3 | 4 | Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero. 5 | 6 | Example 1: 7 | Input: 8 | bits = [1, 0, 0] 9 | Output: True 10 | Explanation: 11 | The only way to decode it is two-bit character and one-bit character. So the last character is one-bit character. 12 | Example 2: 13 | Input: 14 | bits = [1, 1, 1, 0] 15 | Output: False 16 | Explanation: 17 | The only way to decode it is two-bit character and two-bit character. So the last character is NOT one-bit character. 18 | Note: 19 | 20 | 1 <= len(bits) <= 1000. 21 | bits[i] is always 0 or 1. 22 | 23 | 题目大意:我们有两个特殊字符。 第一个字符可以用1位表示。第二个字符可以用2位(10或11)表示。现在给出一个由几位表示的字符串。 返回最后一个字符是否是一位字符。 给定的字符串将始终以0结束。 24 | 分析:i从0开始遍历整个bits数组,当i遇到0时走一步,否则走2步,判断是否会走到最后一个元素~ 25 | 26 | class Solution { 27 | public: 28 | bool isOneBitCharacter(vector& bits) { 29 | int i = 0; 30 | while(i < bits.size()) { 31 | if (i == (bits.size() - 1)) return true; 32 | if (bits[i] == 0) i++; 33 | else i += 2; 34 | } 35 | return false; 36 | } 37 | }; -------------------------------------------------------------------------------- /C++/739. Daily Temperatures.cpp: -------------------------------------------------------------------------------- 1 | 739. Daily Temperatures 2 | Given a list of daily temperatures, produce a list that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. 3 | 4 | For example, given the list temperatures = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0]. 5 | 6 | Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100]. 7 | 8 | 分析:用栈解决,i从0~len-1,每次将栈顶元素小于temperatures[i]的出栈,因为对于出栈的元素来说它已经找到了第一个大于它的值,剩余在栈中的都是未找到大于它本身的值的元素,则继续等待下一个temperatures[i]。每次将temperatures[i]压入栈中,等待接下来遇到比它大的值时出栈~将i与栈顶元素下标的差值保存在栈顶元素的下标所对应的ans中,最后返回ans即可~ 9 | 10 | class Solution { 11 | public: 12 | vector dailyTemperatures(vector& temperatures) { 13 | stack> s; 14 | int len = temperatures.size(); 15 | vector ans(len); 16 | for (int i = 0; i < len; i++) { 17 | while(!s.empty() && temperatures[i] > s.top().first) { 18 | ans[s.top().second] = i - s.top().second; 19 | s.pop(); 20 | } 21 | s.push(pair(temperatures[i], i)); 22 | } 23 | return ans; 24 | } 25 | }; -------------------------------------------------------------------------------- /C++/746. Min Cost Climbing Stairs.cpp: -------------------------------------------------------------------------------- 1 | 746. Min Cost Climbing Stairs 2 | On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed). 3 | 4 | Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1. 5 | 6 | Example 1: 7 | Input: cost = [10, 15, 20] 8 | Output: 15 9 | Explanation: Cheapest is start on cost[1], pay that cost and go to the top. 10 | Example 2: 11 | Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] 12 | Output: 6 13 | Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3]. 14 | Note: 15 | cost will have a length in the range [2, 1000]. 16 | Every cost[i] will be an integer in the range [0, 999]. 17 | 18 | 题目大意:爬n阶的楼梯,每层都有一个cost值(0~n-1),每次可以爬1层或者2层,求爬完全程的最小花费cost(可以从第0层开始也可以从第1层开始) 19 | 分析:dp数组,每次dp[i] = cost[i] + min(dp[i-1], dp[i-2]),最终返回dp[n-1]和dp[n-2]中较小的那个~ 20 | 21 | class Solution { 22 | public: 23 | int minCostClimbingStairs(vector& cost) { 24 | int n = cost.size(); 25 | vector dp(n); 26 | dp[0] = cost[0], dp[1] = cost[1]; 27 | for (int i = 2; i < n; i++) 28 | dp[i] = cost[i] + min(dp[i-1], dp[i-2]); 29 | return min(dp[n-1], dp[n-2]); 30 | } 31 | }; -------------------------------------------------------------------------------- /C++/766. Toeplitz Matrix.cpp: -------------------------------------------------------------------------------- 1 | 766. Toeplitz Matrix 2 | A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element. 3 | 4 | Now given an M x N matrix, return True if and only if the matrix is Toeplitz. 5 | 6 | 7 | Example 1: 8 | 9 | Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]] 10 | Output: True 11 | Explanation: 12 | 1234 13 | 5123 14 | 9512 15 | 16 | In the above grid, the diagonals are "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]", and in each diagonal all elements are the same, so the answer is True. 17 | Example 2: 18 | 19 | Input: matrix = [[1,2],[2,2]] 20 | Output: False 21 | Explanation: 22 | The diagonal "[1, 2]" has different elements. 23 | Note: 24 | 25 | matrix will be a 2D array of integers. 26 | matrix will have a number of rows and columns in range [1, 20]. 27 | matrix[i][j] will be integers in range [0, 99]. 28 | 29 | 题目大意:如果从左上角到右下角的每个对角线具有相同的元素,则矩阵是Toeplitz。给一个矩阵判断它是否是Toeplitz矩阵 30 | 分析:对于每一个元素matrix[i][j],都判断它是否等于它的右上角元素matrix[i-1][j-1],如果不相等就返回false,否则循环结束后返回true 31 | 32 | class Solution { 33 | public: 34 | bool isToeplitzMatrix(vector>& matrix) { 35 | for (int i = 1; i < matrix.size(); i++) 36 | for (int j = 1; j < matrix[0].size(); j++) 37 | if (matrix[i][j] != matrix[i-1][j-1]) return false; 38 | return true; 39 | } 40 | }; -------------------------------------------------------------------------------- /C++/771. Jewels and Stones.cpp: -------------------------------------------------------------------------------- 1 | 771. Jewels and Stones 2 | You are given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels. 3 | 4 | The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A". 5 | 6 | Example 1: 7 | 8 | Input: J = "aA", S = "aAAbbbb" 9 | Output: 3 10 | Example 2: 11 | 12 | Input: J = "z", S = "ZZ" 13 | Output: 0 14 | Note: 15 | 16 | S and J will consist of letters and have length at most 50. 17 | The characters in J are distinct. 18 | 19 | 题目大意:J是珠宝,S是自己拥有的石头,判断自己拥有的石头中有多少个珠宝~ 20 | 分析:将J中的所有字符在hash数组中标记为1,再遍历S,统计hash == 1的个数即为所求~ 21 | 22 | class Solution { 23 | public: 24 | int numJewelsInStones(string J, string S) { 25 | int ans = 0, hash[256] = {0}; 26 | for (auto i : J) hash[i] = 1; 27 | for (auto i : S) if (hash[i]) ans++; 28 | return ans; 29 | } 30 | }; -------------------------------------------------------------------------------- /C++/779. K-th Symbol in Grammar.cpp: -------------------------------------------------------------------------------- 1 | 779. K-th Symbol in Grammar 2 | On the first row, we write a 0. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10. 3 | 4 | Given row N and index K, return the K-th indexed symbol in row N. (The values of K are 1-indexed.) (1 indexed). 5 | 6 | Examples: 7 | Input: N = 1, K = 1 8 | Output: 0 9 | 10 | Input: N = 2, K = 1 11 | Output: 0 12 | 13 | Input: N = 2, K = 2 14 | Output: 1 15 | 16 | Input: N = 4, K = 5 17 | Output: 1 18 | 19 | Explanation: 20 | row 1: 0 21 | row 2: 01 22 | row 3: 0110 23 | row 4: 01101001 24 | Note: 25 | 26 | N will be an integer in the range [1, 30]. 27 | K will be an integer in the range [1, 2^(N-1)]. 28 | 29 | 题目大意:在第一行,我们写一个0.现在在后面的每一行中,我们看前一行,用01代替0出现的每一个,每一次出现1代表10。现在问第N行第K数字是什么数字 30 | 分析:用递归,已知N == 1的时候返回0,为了知道第N行第K个数字的值,只要知道它在第N-1行的第(K+1)/2个数字对应的值即可,因为0对应01,1对应10,那么如果K是奇数只需和原数字相同即可,如果K是偶数只需对原对应数字取反即可~ 31 | 32 | class Solution { 33 | public: 34 | int kthGrammar(int N, int K) { 35 | if (N == 1) return 0; 36 | return (K % 2 == 0) ? !kthGrammar(N-1, (K+1)/2) : kthGrammar(N-1, (K+1)/2); 37 | } 38 | }; -------------------------------------------------------------------------------- /Swift/100. Same Tree.swift: -------------------------------------------------------------------------------- 1 | // 100. Same Tree 2 | // 8 ms 3 | if let p = p, let q = q { 4 | return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right) 5 | } else { 6 | return p == nil && q == nil 7 | } -------------------------------------------------------------------------------- /Swift/101 Symmetric Tree.swift: -------------------------------------------------------------------------------- 1 | // 101 Symmetric Tree 2 | // 16 ms 3 | func isSymmetricTree(_ p: TreeNode?, _ q: TreeNode?) -> Bool { 4 | if let p = p, let q = q { 5 | return p.val == q.val && isSymmetricTree(p.left, q.right) && isSymmetricTree(p.right, q.left) 6 | } else { 7 | return p == nil && q == nil 8 | } 9 | } 10 | 11 | func isSymmetric(_ root: TreeNode?) -> Bool { 12 | return isSymmetricTree(root?.left, root?.right) 13 | } 14 | 15 | -------------------------------------------------------------------------------- /Swift/102. Binary Tree Level Order Traversal.swift: -------------------------------------------------------------------------------- 1 | // 102. Binary Tree Level Order Traversal 2 | // 20 ms 3 | 4 | func levelOrder(_ root: TreeNode?) -> [[Int]] { 5 | guard let root = root else { return [] } 6 | 7 | var q = [TreeNode](), lists = [[Int]]() 8 | q.append(root) 9 | 10 | while !q.isEmpty { 11 | lists.append(q.map { $0.val }) 12 | 13 | q = q.reduce([]) { l, t in 14 | l + [t.left, t.right] 15 | }.compactMap({$0}) 16 | } 17 | 18 | return lists 19 | } -------------------------------------------------------------------------------- /Swift/104. Maximum Depth of Binary Tree.swift: -------------------------------------------------------------------------------- 1 | // 104. Maximum Depth of Binary Tree 2 | // 24 ms 3 | return root == nil ? 0 : 1 + max(maxDepth(root?.left), maxDepth(root?.right)) -------------------------------------------------------------------------------- /Swift/114. Flatten Binary Tree to Linked List.swift: -------------------------------------------------------------------------------- 1 | // 114. Flatten Binary Tree to Linked List 2 | // 20 ms, 100% 3 | func flatten(_ root: TreeNode?) { 4 | if let p = root { 5 | flatten(p.left) 6 | flatten(p.right) 7 | if let l = p.left { 8 | if let r = p.right { 9 | var lr = l 10 | while lr.right != nil { 11 | lr = lr.right! 12 | } 13 | lr.right = r 14 | } 15 | p.right = l 16 | p.left = nil 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /Swift/121. Best Time to Buy and Sell Stock.swift: -------------------------------------------------------------------------------- 1 | // 121. Best Time to Buy and Sell Stock 2 | // 16 ms, 90.40% 3 | func maxProfit(_ prices: [Int]) -> Int { 4 | if prices.count < 2 { return 0 } 5 | 6 | var p = prices[0], m = 0 7 | for i in 1.. ListNode? { 4 | var arr = Array(repeating: 0, count: 256*128) 5 | var i = 0, p = head 6 | while let q = p { 7 | arr[i] = q.val 8 | p = q.next; i += 1 9 | } 10 | arr = Array(arr[.. Int { 4 | if nums.isEmpty { return 0 } 5 | var gm = nums[0], lmax = nums[0], lmin = nums[0], i = 1 6 | while i < nums.count { 7 | let t = [lmax * nums[i], nums[i], lmin * nums[i]] 8 | lmin = t.min()! 9 | lmax = t.max()! 10 | gm = max(lmax, gm) 11 | i += 1 12 | } 13 | 14 | return gm 15 | } -------------------------------------------------------------------------------- /Swift/169. Majority Element.swift: -------------------------------------------------------------------------------- 1 | // 169. Majority Element 2 | // 60 ms 3 | var v = 0, res = 0 4 | var dict = [Int: Int]() 5 | nums.forEach { 6 | var t = 1 7 | if let n = dict[$0] { 8 | t = n + 1 9 | } 10 | 11 | if t > v { 12 | res = $0 13 | v = t 14 | } 15 | dict[$0] = t 16 | } 17 | 18 | return res -------------------------------------------------------------------------------- /Swift/198. House Robber.swift: -------------------------------------------------------------------------------- 1 | // 198. House Robber 2 | // 8 ms, 100% 3 | func rob(_ nums: [Int]) -> Int { 4 | if nums.count < 1 { return nums.first ?? 0 } 5 | var lm = 0, gm = 0 6 | for i in 0.. Bool { 4 | var stack = [Character](), b = true 5 | 6 | func compare(_ c: Character) -> Bool { 7 | guard let t = stack.popLast() else { return false } 8 | return (c == ")" && t == "(") || (c == "]" && t == "[" ) || (c == "}" && t == "{") 9 | } 10 | 11 | loop: for c in s { 12 | switch c { 13 | case "(", "[", "{": 14 | stack.append(c) 15 | default: 16 | b = compare(c) 17 | if !b { break loop } 18 | } 19 | } 20 | 21 | return b && stack.isEmpty 22 | } -------------------------------------------------------------------------------- /Swift/206. Reverse Linked List.swift: -------------------------------------------------------------------------------- 1 | // 206. Reverse Linked List 2 | // 20 ms, 63.85% 3 | func reverseList(_ head: ListNode?) -> ListNode? { 4 | var stack = [Int](), p = head 5 | while let t = p { 6 | stack.append(t.val) 7 | p = t.next 8 | } 9 | p = head 10 | while let t = p { 11 | t.val = stack.popLast()! 12 | p = t.next 13 | } 14 | return head 15 | } -------------------------------------------------------------------------------- /Swift/21. Merge Two Sorted Lists.swift: -------------------------------------------------------------------------------- 1 | // 21. Merge Two Sorted Lists 2 | // 24 ms, 60.98% 3 | func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { 4 | var arr = [Int](), p1 = l1, p2 = l2, r = l1 5 | 6 | while let q1 = p1, let q2 = p2 { 7 | if q1.val < q2.val { 8 | arr.append(q1.val) 9 | p1 = q1.next 10 | } else { 11 | arr.append(q2.val) 12 | p2 = q2.next 13 | } 14 | } 15 | while let q1 = p1 { 16 | arr.append(q1.val) 17 | p1 = q1.next 18 | if p1 == nil { 19 | q1.next = l2 20 | r = l1 21 | } 22 | } 23 | while let q2 = p2 { 24 | arr.append(q2.val) 25 | p2 = q2.next 26 | if p2 == nil { 27 | q2.next = l1 28 | r = l2 29 | } 30 | } 31 | 32 | p1 = r 33 | arr.forEach { 34 | p1?.val = $0 35 | p1 = p1?.next 36 | } 37 | 38 | return r 39 | } -------------------------------------------------------------------------------- /Swift/215. Kth Largest Element in an Array.swift: -------------------------------------------------------------------------------- 1 | // 215. Kth Largest Element in an Array 2 | // 20 ms, 97.33% 3 | func findKthLargest(_ nums: [Int], _ k: Int) -> Int { 4 | if nums.isEmpty { return 0 } 5 | let sn = nums.sorted(by: >) 6 | return (k <= sn.count && k > 0) ? sn[k-1] : sn[0] 7 | } -------------------------------------------------------------------------------- /Swift/23. Merge k Sorted Lists.swift: -------------------------------------------------------------------------------- 1 | // 23. Merge k Sorted Lists 2 | // 80 ms, 90.77% 3 | func mergeKLists(_ lists: [ListNode?]) -> ListNode? { 4 | var i = 0, j = 0, fl = lists.compactMap({$0}), n = fl.count, p: ListNode? 5 | if n < 1 { return nil } 6 | 7 | var arr = Array(repeating: 0, count: 256*256) 8 | while i < n { 9 | p = fl[i]; i += 1 10 | while let p1 = p { 11 | arr[j] = p1.val 12 | p = p1.next; j += 1 13 | if p == nil, i < n { 14 | p1.next = fl[i] 15 | } 16 | } 17 | } 18 | 19 | arr = Array(arr[.. Bool { 4 | var arr = Array(repeating: -1, count: 999999), p = head 5 | var i = 0, j = 0 6 | 7 | while let q = p { 8 | arr[i] = q.val 9 | p = q.next; i+=1 10 | } 11 | 12 | j = i-1; i = 0 13 | 14 | while i < j { 15 | if arr[i] != arr[j] { return false } 16 | i+=1; j -= 1 17 | } 18 | 19 | return true 20 | } -------------------------------------------------------------------------------- /Swift/283. Move Zeroes.swift: -------------------------------------------------------------------------------- 1 | // 283. Move Zeroes 2 | // 16 ms 3 | var j = 0 4 | for i in 0.. Int { 4 | let sn = nums.sorted() 5 | var i = 1 6 | while i < nums.count { 7 | if sn[i-1] == sn[i] { return sn[i] } 8 | i += 1 9 | } 10 | 11 | return -1 12 | } -------------------------------------------------------------------------------- /Swift/338. Counting Bits.swift: -------------------------------------------------------------------------------- 1 | // 338. Counting Bits 2 | // 28ms 3 | func countBits(_ num: Int) -> [Int] { 4 | var arr = Array(repeating: 0, count: num+1), i = 0 5 | while i <= num { 6 | arr[i] = i.nonzeroBitCount 7 | i += 1 8 | } 9 | 10 | return arr 11 | } -------------------------------------------------------------------------------- /Swift/347. Top K Frequent Elements.swift: -------------------------------------------------------------------------------- 1 | // 347. Top K Frequent Elements 2 | // 48 ms, 68% 3 | func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] { 4 | var dict = [Int:Int]() 5 | nums.forEach { 6 | dict[$0] = (dict[$0] == nil ? 0 : dict[$0]! ) + 1 7 | } 8 | 9 | return dict.sorted(by: { $0.value > $1.value } )[0.. String { 4 | var stack = [String]() 5 | s.forEach { 6 | switch $0 { 7 | case "]": 8 | var s = "", i = "" 9 | while let c = stack.popLast(), c != "[" { 10 | s = "\(c)\(s)" 11 | } 12 | while let sl = stack.last, nil != Int("\(sl)"), let c = stack.popLast() { 13 | i = "\(c)\(i)" 14 | } 15 | stack.append(String(repeating: s, count: Int(i)!)) 16 | default: 17 | stack.append(String($0)) 18 | } 19 | } 20 | 21 | return stack.joined() 22 | } 23 | 24 | -------------------------------------------------------------------------------- /Swift/437. Path Sum III.swift: -------------------------------------------------------------------------------- 1 | // 437. Path Sum III 2 | // 472 ms 34.38% 3 | func pathSum(_ root: TreeNode?, _ sum: Int) -> Int { 4 | return pathSumNote(root, sum).0 5 | } 6 | 7 | private func pathSumNote(_ root: TreeNode?, _ sum: Int) -> (Int, [Int]) { 8 | guard let p = root else { return (0, []) } 9 | 10 | let ls = pathSumNote(p.left, sum) 11 | let rs = pathSumNote(p.right, sum) 12 | let arr = (ls.1 + rs.1).map({$0 + p.val}) + [p.val] 13 | 14 | let sum = ls.0 + rs.0 + arr.filter({$0 == sum}).count 15 | return (sum, arr) 16 | } 17 | 18 | -------------------------------------------------------------------------------- /Swift/448. Find All Numbers Disappeared in an Array.swift: -------------------------------------------------------------------------------- 1 | // 448. Find All Numbers Disappeared in an Array 2 | // 264 ms 3 | return nums.count > 1 ? Array(Set(1...nums.count).subtracting(nums)) : [] -------------------------------------------------------------------------------- /Swift/461. Hamming Distance.swift: -------------------------------------------------------------------------------- 1 | // 461. Hamming Distance 2 | // 12 ms 3 | return (x ^ y).nonzeroBitCount -------------------------------------------------------------------------------- /Swift/49. Group Anagrams.swift: -------------------------------------------------------------------------------- 1 | // 49. Group Anagrams 2 | // 164 ms, 58.49% 3 | func groupAnagrams(_ strs: [String]) -> [[String]] { 4 | var dict = [String: [String]]() 5 | strs.forEach { 6 | let s = String($0.sorted()) 7 | dict[s] = (dict[s] == nil) ? [$0] : dict[s]! + [$0] 8 | } 9 | return dict.map({$0.value}) 10 | } -------------------------------------------------------------------------------- /Swift/53. Maximum Subarray.swift: -------------------------------------------------------------------------------- 1 | // 53. Maximum Subarray 2 | // 12 ms, 100% 3 | func maxSubArray(_ nums: [Int]) -> Int { 4 | if nums.isEmpty { return 0 } 5 | 6 | var gMax = nums[0], lMax = nums[0] 7 | for i in 1.. TreeNode? { 5 | if let root = root { 6 | convertBST(root.right) 7 | sum += root.val 8 | root.val = sum 9 | convertBST(root.left) 10 | } 11 | 12 | return root 13 | } -------------------------------------------------------------------------------- /Swift/543. Diameter of Binary Tree.swift: -------------------------------------------------------------------------------- 1 | // 543. Diameter of Binary Tree 2 | // 32 ms 3 | private var diameter = 0 4 | private func diameterOfNode(_ root: TreeNode?) -> Int { 5 | var lv = 0, rv = 0 6 | 7 | if let l = root?.left { 8 | lv = 1 + diameterOfNode(l) 9 | } 10 | if let r = root?.right { 11 | rv = 1 + diameterOfNode(r) 12 | } 13 | diameter = max(diameter, lv + rv) 14 | return max(lv, rv) 15 | } 16 | 17 | func diameterOfBinaryTree(_ root: TreeNode?) -> Int { 18 | diameterOfNode(root) 19 | return diameter 20 | } -------------------------------------------------------------------------------- /Swift/572. Subtree of Another Tree.swift: -------------------------------------------------------------------------------- 1 | // 572. Subtree of Another Tree 2 | // 368 ms 3 | 4 | func isSubtree(_ s: TreeNode?, _ t: TreeNode?) -> Bool { 5 | return ( maxDepth(s) >= maxDepth(t) ) 6 | && ( isSameTree(s, t) 7 | || (s?.left != nil && isSubtree(s?.left, t)) 8 | || (s?.right != nil && isSubtree(s?.right, t)) ) 9 | } 10 | 11 | private func isSameTree(_ p: TreeNode?, _ q: TreeNode?) -> Bool { 12 | if let p = p, let q = q { 13 | return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right) 14 | } else { 15 | return p == nil && q == nil 16 | } 17 | } 18 | 19 | private func maxDepth(_ root: TreeNode?) -> Int { 20 | return root == nil ? 0 : 1 + max(maxDepth(root?.left), maxDepth(root?.right)) 21 | } -------------------------------------------------------------------------------- /Swift/581. Shortest Unsorted Continuous Subarray.swift: -------------------------------------------------------------------------------- 1 | // 581. Shortest Unsorted Continuous Subarray 2 | // 216 ms, 0% 3 | 4 | func findUnsortedSubarray(_ nums: [Int]) -> Int { 5 | if nums.count < 2 { return 0 } 6 | let sn = nums.sorted() 7 | var p = -1, q = -1 8 | for (i, v) in zip(sn, nums).enumerated() { 9 | if v.0 != v.1 { 10 | p == -1 ? (p = i) : (q = i + 1) 11 | } 12 | } 13 | return q - p 14 | } 15 | -------------------------------------------------------------------------------- /Swift/617. Merge Two Binary Trees.swift: -------------------------------------------------------------------------------- 1 | // 617. Merge Two Binary Trees 2 | // 100 ms 3 | func mergeTrees(_ t1: TreeNode?, _ t2: TreeNode?) -> TreeNode? { 4 | let root = mergeNote(t1, t2) 5 | root?.left = mergeTrees(t1?.left, t2?.left) 6 | root?.right = mergeTrees(t1?.right, t2?.right) 7 | 8 | return root 9 | } 10 | 11 | func mergeNote(_ t1: TreeNode?, _ t2: TreeNode?) -> TreeNode? { 12 | if let c1 = t1, let c2 = t2 { 13 | return TreeNode(c1.val + c2.val) 14 | } else if let c1 = t1 { 15 | return TreeNode(c1.val) 16 | } else if let c2 = t2 { 17 | return TreeNode(c2.val) 18 | } else { 19 | return nil 20 | } 21 | } -------------------------------------------------------------------------------- /Swift/62. Unique Paths.swift: -------------------------------------------------------------------------------- 1 | // 62. Unique Paths 2 | // 16 ms, 39.53% 3 | func uniquePaths(_ m: Int, _ n: Int) -> Int { 4 | pathMatrix = Array(repeating: Array(repeating: 0, count: n+1), count: m+1) 5 | return pathMatrix(m, n) 6 | } 7 | 8 | private var pathMatrix: [[Int]]! 9 | private func pathMatrix(_ m: Int, _ n: Int) -> Int { 10 | if m <= 0 || n <= 0 { return 0 } 11 | if m < 2 || n < 2 { pathMatrix[m][n] = 1; return 1 } 12 | 13 | if pathMatrix[m-1][n] == 0 { 14 | pathMatrix[m-1][n] = pathMatrix(m-1, n) 15 | } 16 | if pathMatrix[m][n-1] == 0 { 17 | pathMatrix[m][n-1] = pathMatrix(m, n-1) 18 | } 19 | return pathMatrix[m-1][n] + pathMatrix[m][n-1] 20 | } -------------------------------------------------------------------------------- /Swift/657. Judge Route Circle.swift: -------------------------------------------------------------------------------- 1 | // 657. Judge Route Circle 2 | // 236 ms 3 | return moves.filter({$0 == "U"}).count == moves.filter({$0 == "D"}).count && moves.filter({$0 == "R"}).count == moves.filter({$0 == "L"}).count -------------------------------------------------------------------------------- /Swift/695. Max Area of Island.swift: -------------------------------------------------------------------------------- 1 | // 695. Max Area of Island 2 | // 44ms, 79.31% 3 | 4 | func maxAreaOfIsland(_ grid: [[Int]]) -> Int { 5 | var i = 0, j = 0, v = 0 6 | var g = grid 7 | while i < grid.count { 8 | while j < grid[i].count { 9 | v = max(area(&g, i, j), v) 10 | j += 1 11 | } 12 | i += 1; j = 0 13 | } 14 | return v 15 | } 16 | 17 | private func area(_ g: inout [[Int]], _ i: Int, _ j: Int) -> Int { 18 | var v = 0 19 | if i < 0 || i >= g.count || j < 0 || j >= g[i].count { 20 | return 0 21 | } 22 | if g[i][j] == 1 { 23 | g[i][j] = 0; v = 1 24 | v += area(&g, i, j+1) 25 | v += area(&g, i+1, j) 26 | v += area(&g, i-1, j) 27 | v += area(&g, i, j-1) 28 | } 29 | return v 30 | } 31 | -------------------------------------------------------------------------------- /Swift/70. Climbing Stairs.swift: -------------------------------------------------------------------------------- 1 | func climbStairs(_ n: Int) -> Int { 2 | if n < 4 { return n } 3 | var arr = Array(repeating: 1, count: n+1) 4 | 5 | arr[2] = 2; arr[3] = 3 6 | for i in (4...n) { 7 | arr[i] = arr[i-1] + arr[i-2] 8 | } 9 | 10 | return arr[n] 11 | } -------------------------------------------------------------------------------- /Swift/709. To Lower Case.swift: -------------------------------------------------------------------------------- 1 | // 709. To Lower Case 2 | // 8 ms 3 | return str.lowercased() -------------------------------------------------------------------------------- /Swift/75. Sort Colors.swift: -------------------------------------------------------------------------------- 1 | // 75. Sort Colors 2 | // 12 ms, 68.92% 3 | func sortColors(_ nums: inout [Int]) { 4 | var i0 = 0, i1 = 0, i2 = nums.count-1 5 | while i1 <= i2 { 6 | if nums[i1] == 2 { 7 | nums.swapAt(i1, i2) 8 | i2 -= 1 9 | } else if nums[i1] == 0 { 10 | nums.swapAt(i0, i1) 11 | i0 += 1; i1 += 1 12 | } else { 13 | i1 += 1 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Swift/771. Jewels and Stones.swift: -------------------------------------------------------------------------------- 1 | // 771. Jewels and Stones 2 | // 20 ms 3 | return J.reduce(0) { sum, j in 4 | sum + S.filter({$0 == j}).count 5 | } 6 | -------------------------------------------------------------------------------- /Swift/804. Unique Morse Code Words.swift: -------------------------------------------------------------------------------- 1 | // 804. Unique Morse Code Words 2 | // 20 ms 3 | let morseCode = ["a": "01", "b": "1000", "c": "1010", "d": "100", "e": "0", "f": "0010", "g": "110", "h": "0000", "i": "00", "j": "0111", "k": "101", "l": "0100", "m": "11", "n": "10", "o": "111", "p": "0110", "q": "1101", "r": "010", "s": "000", "t": "1", "u": "001", "v": "0001", "w": "011", "x": "1001", "y": "1011", "z": "1100"] 4 | return Set( 5 | words.map { w in 6 | w.reduce("") { s, c in 7 | s + morseCode[String(c)]! 8 | } 9 | }).count -------------------------------------------------------------------------------- /Swift/832. Flipping an Image.swift: -------------------------------------------------------------------------------- 1 | // 832. Flipping an Image 2 | // 16 ms 3 | return A.map({$0.map({1-$0}).reversed()}) -------------------------------------------------------------------------------- /Swift/94. Binary Tree Inorder Traversal.swift: -------------------------------------------------------------------------------- 1 | // 94. Binary Tree Inorder Traversal 2 | // 8 ms, 100% 3 | 4 | func inorderTraversal(_ root: TreeNode?) -> [Int] { 5 | var list = [Int](), stack = [TreeNode](), p = root 6 | 7 | while p != nil || !stack.isEmpty { 8 | if let t = p { 9 | stack.append(t) 10 | p = t.left 11 | } else { 12 | let t = stack.popLast()! 13 | list.append(t.val) 14 | p = t.right 15 | } 16 | } 17 | 18 | return list 19 | } -------------------------------------------------------------------------------- /Swift/96. Unique Binary Search Trees.swift: -------------------------------------------------------------------------------- 1 | // 96. Unique Binary Search Trees 2 | // 8 ms 3 | 4 | func numTrees(_ n: Int) -> Int { 5 | list = Array(repeating: 1, count: n+1) 6 | if n >= 2 { list[2] = 2 } 7 | return g(n) 8 | } 9 | 10 | private var list: [Int]! 11 | private func g(_ n: Int) -> Int { 12 | if n > 2 && list[n] == 1 { 13 | list[n] = (1...n).reduce(0) { $0 + f($1, n) } 14 | } 15 | return list[n] 16 | } 17 | 18 | private func f(_ i: Int, _ n: Int) -> Int { 19 | return g(i-1) * g(n-i) 20 | } -------------------------------------------------------------------------------- /Swift/98. Validate Binary Search Tree.swift: -------------------------------------------------------------------------------- 1 | // 98. Validate Binary Search Tree 2 | // 28 ms, 100% 3 | 4 | func isValidBST(_ root: TreeNode?) -> Bool { 5 | return isValidNode(root, Int.min, Int.max) 6 | } 7 | 8 | private func isValidNode(_ root: TreeNode?, _ min: Int, _ max: Int) -> Bool { 9 | guard let p = root else { return true } 10 | if p.val >= max || p.val <= min { return false } 11 | return isValidNode(p.left, min, p.val) && isValidNode(p.right, p.val, max) 12 | } --------------------------------------------------------------------------------