├── C++ ├── 001. Two Sum.cpp ├── 002. Add Two Numbers.cpp ├── 003. Longest Substring Without Repeating Characters.cpp ├── 004. Median of Two Sorted Arrays.cpp ├── 005. Longest Palindromic Substring.cpp ├── 006. ZigZag Conversion.cpp ├── 007. Reverse Integer.cpp ├── 008. String to Integer (atoi).cpp ├── 009. Palindrome Number.cpp ├── 010. Regular Expression Matching.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 ├── 023. Merge k Sorted Lists.cpp ├── 024. Swap Nodes in Pairs.cpp ├── 025. Reverse Nodes in k-Group.cpp ├── 026. Remove Duplicates from Sorted Array.cpp ├── 027. Remove Element.cpp ├── 028. Implement strStr().cpp ├── 031. Next Permutation.cpp ├── 033. Search in Rotated Sorted Array.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 ├── 041. First Missing Positive.cpp ├── 042. Trapping Rain Water.cpp ├── 043. Multiply Strings.cpp ├── 044. Wildcard Matching.cpp ├── 045. Jump Game II.cpp ├── 046. Permutations.cpp ├── 047. Permutations II.cpp ├── 048. Rotate Image.cpp ├── 049. Group Anagrams.cpp ├── 050. Pow(x, n).cpp ├── 053. Maximum Subarray.cpp ├── 054. Spiral Matrix.cpp ├── 055. Jump Game.cpp ├── 056. Merge Intervals.cpp ├── 057. Insert Interval.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 ├── 068. Text Justification.cpp ├── 069. Sqrt(x).cpp ├── 070. Climbing Stairs.cpp ├── 071. Simplify Path.cpp ├── 073. Set Matrix Zeroes.cpp ├── 074. Search a 2D Matrix.cpp ├── 075. Sort Colors.cpp ├── 076. Minimum Window Substring.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 ├── 085. Maximal Rectangle.cpp ├── 086. Partition List.cpp ├── 088. Merge Sorted Array.cpp ├── 090. Subsets II.cpp ├── 091. Decode Ways.cpp ├── 092. Reverse Linked List II.cpp ├── 094. Binary Tree Inorder Traversal.cpp ├── 095. Unique Binary Search Trees II.cpp ├── 098. Validate Binary Search Tree.cpp ├── 099. Recover 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 ├── 105. Construct Binary Tree from Preorder and Inorder Traversal.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 Tree.cpp ├── 110. Balanced Binary Tree.cpp ├── 111. Minimum Depth of Binary Tree.cpp ├── 112. Path Sum.cpp ├── 113. Path Sum II.cpp ├── 114. Flatten Binary Tree to Linked List.cpp ├── 116. Populating Next Right Pointers in Each Node.cpp ├── 117. Populating Next Right Pointers in Each Node 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 ├── 124. Binary Tree Maximum Path Sum.cpp ├── 125. Valid Palindrome.cpp ├── 127. Word Ladder.cpp ├── 128. Longest Consecutive Sequence.cpp ├── 129. Sum Root to Leaf Numbers.cpp ├── 130. Surrounded Regions.cpp ├── 131. Palindrome Partitioning.cpp ├── 133. Clone Graph.cpp ├── 134. Gas Station.cpp ├── 136. Single Number.cpp ├── 138. Copy List with Random Pointer.cpp ├── 139. Word Break.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 ├── 146. LRU Cache.cpp ├── 151. Reverse Words in a String.cpp ├── 155. Min Stack.cpp ├── 157. Read N Characters Given Read4.cpp ├── 158. Read N Characters Given Read4 II - Call multiple times.cpp ├── 159. Longest Substring with At Most Two Distinct Characters.cpp ├── 161. One Edit Distance.cpp ├── 162. Find Peak Element.cpp ├── 163. Missing Ranges.cpp ├── 168. Excel Sheet Column Title.cpp ├── 169. Majority Element.cpp ├── 171. Excel Sheet Column Number.cpp ├── 173. Binary Search Tree Iterator.cpp ├── 186. Reverse Words in a String II.cpp ├── 191. Number of 1 Bits.cpp ├── 198. House Robber.cpp ├── 200. Number of Islands.cpp ├── 205. Isomorphic Strings.cpp ├── 206. Reverse Linked List.cpp ├── 207. Course Schedule.cpp ├── 208. Implement Trie (Prefix Tree).cpp ├── 209. Minimum Size Subarray Sum.cpp ├── 210. Course Schedule II.cpp ├── 211. Add and Search Word - Data structure design.cpp ├── 212. Word Search II.cpp ├── 214. Shortest Palindrome.cpp ├── 215. Kth Largest Element in an Array.cpp ├── 221. Maximal Square.cpp ├── 223. Rectangle Area.cpp ├── 224. Basic Calculator.cpp ├── 226. Invert Binary Tree.cpp ├── 227. Basic Calculator II.cpp ├── 228. Summary Ranges.cpp ├── 229. Majority Element II.cpp ├── 230. Kth Smallest Element in a BST.cpp ├── 231. Power of Two.cpp ├── 234. Palindrome Linked List.cpp ├── 235. Lowest Common Ancestor of a Binary Search Tree.cpp ├── 236. Lowest Common Ancestor of a Binary Tree.cpp ├── 238. Product of Array Except Self.cpp ├── 239. Sliding Window Maximum.cpp ├── 240. Search a 2D Matrix II.cpp ├── 244. Shortest Word Distance II.cpp ├── 246. Strobogrammatic Number.cpp ├── 247. Strobogrammatic Number II.cpp ├── 249. Group Shifted Strings.cpp ├── 251. Flatten 2D Vector.cpp ├── 252. Meeting Rooms.cpp ├── 253. Meeting Rooms II.cpp ├── 255. Verify Preorder Sequence in Binary Search Tree.cpp ├── 257. Binary Tree Paths.cpp ├── 258. Add Digits.cpp ├── 259. 3Sum Smaller.cpp ├── 261. Graph Valid Tree.cpp ├── 263. Ugly Number.cpp ├── 264. Ugly Number II.cpp ├── 266. Palindrome Permutation.cpp ├── 267. Palindrome Permutation II.cpp ├── 268. Missing Number.cpp ├── 269. Alien Dictionary.cpp ├── 270. Closest Binary Search Tree Value.cpp ├── 271. Encode and Decode Strings.cpp ├── 272. Closest Binary Search Tree Value II.cpp ├── 273. Integer to English Words.cpp ├── 274. H-Index.cpp ├── 275. H-Index II.cpp ├── 276. Paint Fence.cpp ├── 277. Find the Celebrity.cpp ├── 278. First Bad Version.cpp ├── 279. Perfect Squares.cpp ├── 280. Wiggle Sort.cpp ├── 281. Zigzag Iterator.cpp ├── 282. Expression Add Operators.cpp ├── 283. Move Zeroes.cpp ├── 284. Peeking Iterator.cpp ├── 285. Inorder Successor in BST.cpp ├── 286. Walls and Gates.cpp ├── 289. Game of Life.cpp ├── 290. Word Pattern.cpp ├── 293. Flip Game.cpp ├── 294. Flip Game II.cpp ├── 295. Find Median from Data Stream.cpp ├── 297. Serialize and Deserialize Binary Tree.cpp ├── 298. Binary Tree Longest Consecutive Sequence.cpp ├── 300. Longest Increasing Subsequence.cpp ├── 301. Remove Invalid Parentheses.cpp ├── 303. Range Sum Query - Immutable.cpp ├── 304. Range Sum Query 2D - Immutable.cpp ├── 305. Number of Islands II.cpp ├── 307. Range Sum Query - Mutable.cpp ├── 309. Best Time to Buy and Sell Stock with Cooldown.cpp ├── 310. Minimum Height Trees.cpp ├── 311. Sparse Matrix Multiplication.cpp ├── 313. Super Ugly Number.cpp ├── 314. Binary Tree Vertical Order Traversal.cpp ├── 315. Count of Smaller Numbers After Self.cpp ├── 317. Shortest Distance from All Buildings.cpp ├── 318. Maximum Product of Word Lengths.cpp ├── 323. Number of Connected Components in an Undirected Graph.cpp ├── 325. Maximum Size Subarray Sum Equals k.cpp ├── 329. Longest Increasing Path in a Matrix.cpp ├── 331. Verify Preorder Serialization of a Binary Tree.cpp ├── 332. Reconstruct Itinerary.cpp ├── 333. Largest BST Subtree.cpp ├── 334. Increasing Triplet Subsequence.cpp ├── 336. Palindrome Pairs.cpp ├── 339. Nested List Weight Sum.cpp ├── 340. Longest Substring with At Most K Distinct Characters.cpp ├── 341. Flatten Nested List Iterator.cpp ├── 344. Reverse String.cpp ├── 347. Top K Frequent Elements.cpp ├── 348. Design Tic-Tac-Toe.cpp ├── 351. Android Unlock Patterns.cpp ├── 354. Russian Doll Envelopes.cpp ├── 355. Design Twitter.cpp ├── 359. Logger Rate Limiter.cpp ├── 360. Sort Transformed Array.cpp ├── 361. Bomb Enemy.cpp ├── 362. Design Hit Counter.cpp ├── 364. Nested List Weight Sum II.cpp ├── 369. Plus One Linked List.cpp ├── 373. Find K Pairs with Smallest Sums.cpp ├── 377. Combination Sum IV.cpp ├── 378. Kth Smallest Element in a Sorted Matrix.cpp ├── 380. Insert Delete GetRandom O(1).cpp ├── 382. Linked List Random Node.cpp ├── 394. Decode String.cpp ├── 398. Random Pick Index.cpp ├── 399. Evaluate Division.cpp ├── 402. Remove K Digits.cpp ├── 404. Sum of Left Leaves.cpp ├── 408. Valid Word Abbreviation.cpp ├── 409. Longest Palindrome.cpp ├── 411. Minimum Unique Word Abbreviation.cpp ├── 412. Fizz Buzz.cpp ├── 416. Partition Equal Subset Sum.cpp ├── 417. Pacific Atlantic Water Flow.cpp ├── 418. Sentence Screen Fitting.cpp ├── 433. Minimum Genetic Mutation.cpp ├── 435. Non-overlapping Intervals.cpp ├── 436. Find Right Interval.cpp ├── 438. Find All Anagrams in a String.cpp ├── 441. Arranging Coins.cpp ├── 444. Sequence Reconstruction.cpp ├── 450. Delete Node in a BST.cpp ├── 451. Sort Characters By Frequency.cpp ├── 461. Hamming Distance.cpp ├── 467. Unique Substrings in Wraparound String.cpp ├── 473. Matchsticks to Square.cpp ├── 477. Total Hamming Distance.cpp ├── 482. License Key Formatting.cpp ├── 484. Find Permutation.cpp ├── 486. Predict the Winner.cpp ├── 487. Max Consecutive Ones II.cpp ├── 489. Robot Room Cleaner.cpp ├── 490. The Maze.cpp ├── 494. Target Sum.cpp ├── 496. Next Greater Element I.cpp ├── 498. Diagonal Traverse.cpp ├── 499. The Maze III.cpp ├── 503. Next Greater Element II.cpp ├── 505. The Maze II.cpp ├── 508. Most Frequent Subtree Sum.cpp ├── 513. Find Bottom Left Tree Value.cpp ├── 515. Find Largest Value in Each Tree Row.cpp ├── 523. Continuous Subarray Sum.cpp ├── 524. Longest Word in Dictionary through Deleting.cpp ├── 525. Contiguous Array.cpp ├── 531. Lonely Pixel I.cpp ├── 535. Encode and Decode TinyURL.cpp ├── 536. Construct Binary Tree from String.cpp ├── 538. Convert BST to Greater Tree.cpp ├── 540. Single Element in a Sorted Array.cpp ├── 541. Reverse String II.cpp ├── 542. 01 Matrix.cpp ├── 543. Diameter of Binary Tree.cpp ├── 547. Friend Circles.cpp ├── 549. Binary Tree Longest Consecutive Sequence II.cpp ├── 554. Brick Wall.cpp ├── 556. Next Greater Element III.cpp ├── 560. Subarray Sum Equals K.cpp ├── 562. Longest Line of Consecutive One in Matrix.cpp ├── 565. Array Nesting.cpp ├── 566. Reshape the Matrix.cpp ├── 567. Permutation in String.cpp ├── 572. Subtree of Another Tree.cpp ├── 582. Kill Process.cpp ├── 583. Delete Operation for Two Strings.cpp ├── 599. Minimum Index Sum of Two Lists.cpp ├── 606. Construct String from Binary Tree.cpp ├── 611. Valid Triangle Number.cpp ├── 616. Add Bold Tag in String.cpp ├── 621. Task Scheduler.cpp ├── 632. Smallest Range.cpp ├── 633. Sum of Square Numbers.cpp ├── 635. Design Log Storage System.cpp ├── 636. Exclusive Time of Functions.cpp ├── 637. Average of Levels in Binary Tree.cpp ├── 639. Decode Ways II.cpp ├── 642. Design Search Autocomplete System.cpp ├── 643. Maximum Average Subarray I.cpp ├── 645. Set Mismatch.cpp ├── 647. Palindromic Substrings.cpp ├── 648. Replace Words.cpp ├── 652. Find Duplicate Subtrees.cpp ├── 653. Two Sum IV - Input is a BST.cpp ├── 654. Maximum Binary Tree.cpp ├── 657. Judge Route Circle.cpp ├── 658. Find K Closest Elements.cpp ├── 659. Split Array into Consecutive Subsequences.cpp ├── 662. Maximum Width of Binary Tree.cpp ├── 663. Equal Tree Partition.cpp ├── 665. Non-decreasing Array.cpp ├── 669. Trim a Binary Search Tree.cpp ├── 670. Maximum Swap.cpp ├── 671. Second Minimum Node In a Binary Tree.cpp ├── 673. Number of Longest Increasing Subsequence.cpp ├── 674. Longest Continuous Increasing Subsequence.cpp ├── 676. Implement Magic Dictionary.cpp ├── 677. Map Sum Pairs.cpp ├── 679. 24 Game.cpp ├── 680. Valid Palindrome II.cpp ├── 681. Next Closest Time.cpp ├── 683. K Empty Slots.cpp ├── 684. Redundant Connection.cpp ├── 685. Redundant Connection II.cpp ├── 686. Repeated String Match.cpp ├── 687. Longest Univalue Path.cpp ├── 688. Knight Probability in Chessboard.cpp ├── 689. Maximum Sum of 3 Non-Overlapping Subarrays.cpp ├── 690. Employee Importance.cpp ├── 692. Top K Frequent Words.cpp ├── 693. Binary Number with Alternating Bits.cpp ├── 694. Number of Distinct Islands.cpp ├── 695. Max Area of Island.cpp ├── 696. Count Binary Substrings.cpp ├── 697. Degree of an Array.cpp ├── 701. Insert into a Binary Search Tree.cpp ├── 713. Subarray Product Less Than K.cpp ├── 717. 1-bit and 2-bit Characters.cpp ├── 718. Maximum Length of Repeated Subarray.cpp ├── 720. Longest Word in Dictionary.cpp ├── 723. Candy Crush.cpp ├── 724. Find Pivot Index.cpp ├── 725. Split Linked List in Parts.cpp ├── 728. Self Dividing Numbers.cpp ├── 729. My Calendar I.cpp ├── 733. Flood Fill.cpp ├── 734. Sentence Similarity.cpp ├── 735. Asteroid Collision.cpp ├── 739. Daily Temperatures.cpp ├── 740. Delete and Earn.cpp ├── 742. Closest Leaf in a Binary Tree.cpp ├── 746. Min Cost Climbing Stairs.cpp ├── 747. Largest Number At Least Twice of Others.cpp ├── 750. Number Of Corner Rectangles.cpp ├── 753. Cracking the Safe.cpp ├── 758. Bold Words in String.cpp ├── 760. Find Anagram Mappings.cpp ├── 763. Partition Labels.cpp ├── 765. Couples Holding Hands.cpp ├── 766. Toeplitz Matrix.cpp ├── 769. Max Chunks To Make Sorted.cpp ├── 771. Jewels and Stones.cpp ├── 773. Sliding Puzzle.cpp ├── 777. Swap Adjacent in LR String.cpp ├── 779. K-th Symbol in Grammar.cpp ├── 783. Minimum Distance Between BST Nodes.cpp ├── 784. Letter Case Permutation.cpp ├── 785. Is Graph Bipartite.cpp ├── 787. Cheapest Flights Within K Stops.cpp ├── 791. Custom Sort String.cpp ├── 792. Number of Matching Subsequences.cpp ├── 797. All Paths From Source to Target.cpp ├── 798. Smallest Rotation with Highest Score.cpp ├── 799. Champagne Tower.cpp ├── 802. Find Eventual Safe States.cpp ├── 803. Bricks Falling When Hit.cpp ├── 804. Unique Morse Code Words.cpp ├── 805. Split Array With Same Average.cpp ├── 806. Number of Lines To Write String.cpp ├── 807. Max Increase to Keep City Skyline.cpp ├── 809. Expressive Words.cpp ├── 814. Binary Tree Pruning.cpp ├── 815. Bus Routes.cpp ├── 819. Most Common Word.cpp ├── 820. Short Encoding of Words.cpp ├── 821. Shortest Distance to a Character.cpp ├── 826. Most Profit Assigning Work.cpp ├── 830. Positions of Large Groups.cpp ├── 832. Flipping an Image.cpp ├── 834. Sum of Distances in Tree.cpp ├── 836. Rectangle Overlap.cpp ├── 841. Keys and Rooms.cpp ├── 843. Guess the Word.cpp ├── 844. Backspace String Compare.cpp ├── 845. Longest Mountain in Array.cpp ├── 846. Hand of Straights.cpp ├── 848. Shifting Letters.cpp ├── 849. Maximize Distance to Closest Person.cpp ├── 852. Peak Index in a Mountain Array.cpp ├── 853. Car Fleet.cpp ├── 855. Exam Room.cpp ├── 857. Minimum Cost to Hire K Workers.cpp ├── 859. Buddy Strings.cpp ├── 872. Leaf-Similar Trees.cpp ├── 876. Middle of the Linked List.cpp ├── 884. Uncommon Words from Two Sentences.cpp ├── 888. Fair Candy Swap.cpp ├── 889. Construct Binary Tree from Preorder and Postorder Traversal.cpp ├── 890. Find and Replace Pattern.cpp ├── 894. All Possible Full Binary Trees.cpp ├── 896. Monotonic Array.cpp ├── 900. RLE Iterator.cpp ├── 904. Fruit Into Baskets.cpp ├── 911. Online Election.cpp ├── 914. X of a Kind in a Deck of Cards.cpp ├── 916. Word Subsets.cpp ├── 925. Long Pressed Name.cpp ├── 929. Unique Email Addresses.cpp ├── 932. Beautiful Array.cpp ├── 933. Number of Recent Calls.cpp ├── 935. Knight Dialer.cpp ├── 938. Range Sum of BST.cpp ├── 939. Minimum Area Rectangle.cpp ├── 941. Valid Mountain Array.cpp ├── 946. Validate Stack Sequences.cpp ├── 951. Flip Equivalent Binary Trees.cpp └── LCS.cpp └── README.md /C++/001. Two Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& nums, int target) { 4 | unordered_mapm; 5 | for(int i = 0; i < nums.size(); i++){ 6 | if(m.count(target - nums[i])) return {m[target - nums[i]], i}; 7 | m[nums[i]] = i; 8 | } 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /C++/002. Add Two Numbers.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 12 | ListNode head(0); 13 | ListNode* cur = &head; 14 | int carry = 0; 15 | while(l1 || l2 || carry){ 16 | int x = l1 ? l1->val : 0; 17 | int y = l2 ? l2->val : 0; 18 | 19 | ListNode* node = new ListNode((x + y + carry) % 10); 20 | cur->next = node; 21 | cur = node; 22 | 23 | carry = (x + y + carry) / 10; 24 | 25 | if(l1) l1 = l1->next; 26 | if(l2) l2 = l2->next; 27 | } 28 | return head.next; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /C++/003. Longest Substring Without Repeating Characters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLongestSubstring(string s) { 4 | unordered_mapm; 5 | int maxlen = 0; 6 | for(int i = 0, j = 0; j < s.size(); j++){ 7 | m[s[j]]++; 8 | while(m[s[j]] > 1) m[s[i++]]--; 9 | maxlen = max(maxlen, j - i + 1); 10 | } 11 | return maxlen; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /C++/004. Median of Two Sorted Arrays.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double findMedianSortedArrays(vector& nums1, vector& nums2) { 4 | int m = nums1.size(), n = nums2.size(); 5 | if(m > n) return findMedianSortedArrays(nums2, nums1); 6 | int lo = 0, hi = m, mid = (m + n + 1)/2; 7 | while(lo <= hi){ 8 | int i = (lo + hi)/2; 9 | int j = mid - i; 10 | if(i < m && nums2[j - 1] > nums1[i]) 11 | lo = i + 1; 12 | else if(i > 0 && nums1[i - 1] > nums2[j]) 13 | hi = i - 1; 14 | else{ 15 | int maxLeft = (i == 0) ? nums2[j - 1] : (j == 0) ? nums1[i - 1] : max(nums1[i - 1], nums2[j - 1]); 16 | int minRight = (i == m) ? nums2[j] : (j == n) ? nums1[i] : min(nums1[i], nums2[j]); 17 | return (m + n) % 2 ? maxLeft : (maxLeft + minRight) / 2.0; 18 | } 19 | } 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /C++/005. Longest Palindromic Substring.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string longestPalindrome(string s) { 4 | if (s.size() == 0 || s.size() == 1) return s; 5 | string res; 6 | int maxlen = 0; 7 | for (int i = 0; i < s.size() - maxlen; i++) { 8 | for (int j = s.size() - 1; j >= i + maxlen; j--) { 9 | if (s[j] != s[i]) continue; 10 | string str = s.substr(i, j - i + 1); 11 | if (isPalindrome(str) && str.size() > maxlen) { 12 | maxlen = str.size(); 13 | res = str; 14 | } 15 | } 16 | } 17 | return res; 18 | } 19 | 20 | bool isPalindrome(string s) { 21 | if (s.size() == 0 || s.size() == 1) return true; 22 | int i(0), j(s.size() - 1); 23 | while (s[i] == s[j] && i < j) i++, j--; 24 | return i >= j; 25 | } 26 | }; -------------------------------------------------------------------------------- /C++/006. ZigZag Conversion.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string convert(string s, int numRows) { 4 | if(numRows == 1) return s; 5 | vectorv(numRows, ""); 6 | int d = 1; 7 | int row = 0; 8 | for(auto c: s){ 9 | v[row].push_back(c); 10 | row += d; 11 | if(row == numRows - 1) d = -1; 12 | if(row == 0) d = 1; 13 | } 14 | string res; 15 | for(auto x: v) res.append(x); 16 | return res; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /C++/007. Reverse Integer.cpp: -------------------------------------------------------------------------------- 1 | // My Solution 2 | class Solution { 3 | public: 4 | int reverse(int x) { 5 | string s = to_string(x); 6 | int base = 1; 7 | int i = s[0] == '-' ? 1 : 0; 8 | int res = 0; 9 | while(i < s.size()){ 10 | if(base == 1000000000 && (s[i] - '0' > 2 || INT_MAX - (s[i] - '0') * base < res)) return 0; 11 | res += (s[i] - '0') * base; 12 | base *= 10; 13 | i++; 14 | } 15 | return s[0] == '-' ? -res : res; 16 | } 17 | }; 18 | 19 | // Solution from https://discuss.leetcode.com/topic/6005/shortest-code-possible-in-c 20 | class Solution { 21 | public: 22 | int reverse(int x) { 23 | long long res = 0; 24 | while(x) { 25 | res = res*10 + x%10; 26 | x /= 10; 27 | } 28 | return (resINT_MAX) ? 0 : res; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /C++/008. String to Integer (atoi).cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int myAtoi(string str) { 4 | if (str.size() == 0) return 0; 5 | int cur = 0; 6 | while (cur < str.size() && str[cur] == ' ') cur++; 7 | if (cur == str.size() || (!isdigit(str[cur]) && str[cur] != '+' && str[cur] != '-')) return 0; 8 | int end = cur + 1; 9 | while (isdigit(str[end])) end++; 10 | string s = str.substr(cur, end - cur); 11 | int num = 0; 12 | int base = 1; 13 | for (int i = s.size() - 1; i >= 0; i--) { 14 | if (s[i] == '+' || s[i] == '-') break; 15 | int add = base * (s[i] - '0'); 16 | if (INT_MAX - num < add || (s.size() - i > 10 && s[i] != '0')) 17 | return s[0] == '-' ? INT_MIN : INT_MAX; 18 | num += add; 19 | base *= 10; 20 | } 21 | if (s[0] == '-') num = -num; 22 | return num; 23 | } 24 | }; -------------------------------------------------------------------------------- /C++/009. Palindrome Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPalindrome(int x) { 4 | if (x < 0 || (x != 0 && x%10 == 0)) return false; 5 | int y = 0; 6 | while (x > y){ 7 | y = y*10 + x%10; 8 | x = x/10; 9 | } 10 | return (x==y || x==y/10); 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /C++/013. Roman to Integer.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int romanToInt(string s) { 4 | // Rule: 5 | // 'I'= 1, 'X' = 10,'C' = 100, 'M' = 1000, 'V' = 5, 'L' = 50, 'D' = 500; 6 | // Adjacent(Left) >= Adjacent(Right): Right + Left; 7 | // Adjacent(Left) < Adjacent(Right): Right - Left; 8 | unordered_mapm({{'I',1}, {'X',10}, {'C',100}, {'M',1000}, {'V',5}, {'L',50}, {'D',500}}); 9 | if(s.size() == 0) return 0; 10 | int sum = m[s[s.size() - 1]]; 11 | for(int i = s.size() - 2; i >= 0; i--){ 12 | if(m[s[i]] >= m[s[i + 1]]) sum += m[s[i]]; 13 | else sum -= m[s[i]]; 14 | } 15 | return sum; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /C++/014. Longest Common Prefix.cpp: -------------------------------------------------------------------------------- 1 | // Solution 1 2 | class Solution { 3 | public: 4 | string longestCommonPrefix(vector& strs) { 5 | if(strs.empty()) return ""; 6 | string res = strs[0]; 7 | for(auto s: strs) res = match(res, s); 8 | return res; 9 | } 10 | 11 | string match(const string& pre, const string& s){ 12 | int i = 0, len = min(pre.size(), s.size()); 13 | for(; i < len; i++) if(s[i] != pre[i]) break; 14 | return pre.substr(0, i); 15 | } 16 | }; 17 | 18 | // Solution 2 19 | // Using sort and only compare the first string with the last string. 20 | class Solution { 21 | public: 22 | string longestCommonPrefix(vector& strs) { 23 | if(strs.empty()) return ""; 24 | sort(strs.begin(), strs.end()); 25 | string a = strs[0], b = strs.back(); 26 | int i = 0; 27 | for(; i < min(a.size(), b.size()); i++) if(a[i] != b[i]) break; 28 | return a.substr(0, i); 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /C++/016. 3Sum Closest.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int threeSumClosest(vector& nums, int target) { 4 | sort(nums.begin(), nums.end()); 5 | int diff = INT_MAX, res = 0; 6 | for(int i = 0; i < nums.size() - 2; i++){ 7 | int lo = i + 1, hi = nums.size() - 1; 8 | while(lo < hi){ 9 | int sum = nums[i] + nums[lo] + nums[hi]; 10 | if(sum == target) return target; 11 | if(abs(sum - target) < diff) diff = abs(sum - target), res = sum; 12 | (sum > target) ? hi-- : lo++; 13 | } 14 | } 15 | return res; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /C++/018. 4Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> fourSum(vector& nums, int target) { 4 | sort(nums.begin(), nums.end()); 5 | vector>res; 6 | vectorpath; 7 | DFS(res, nums, 0, target, 0, 0, path); 8 | return res; 9 | } 10 | 11 | void DFS(vector>& res, vector& nums, int pos, int target, int count, int sum, vector& path){ 12 | if(count == 4){ 13 | if(sum == target) res.push_back(path); 14 | return; 15 | } 16 | for(int i = pos; i < nums.size(); i++){ 17 | if(i != pos && nums[i] == nums[i - 1]) continue; 18 | if(sum + nums[i] + (3 - count) * nums[nums.size() - 1] < target) continue; 19 | if(sum + (4 - count)* nums[i] > target) break; 20 | path.push_back(nums[i]); 21 | DFS(res, nums, i + 1, target, count + 1, sum + nums[i], path); 22 | path.pop_back(); 23 | } 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /C++/019. Remove Nth Node From End of List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode* removeNthFromEnd(ListNode* head, int n) { 12 | ListNode* slow(head), *fast(head); 13 | while(n--) fast = fast->next; 14 | if(!fast) return head->next; 15 | while(fast->next) slow = slow->next, fast = fast->next; 16 | slow->next = slow->next->next; 17 | return head; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /C++/020. Valid Parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isValid(string s) { 4 | stackstk; 5 | for(auto c: s){ 6 | if(stk.empty() && (c == ')' || c == ']' || c == '}')) return false; 7 | if(c == '(' || c == '[' || c == '{') stk.push(c); 8 | else{ 9 | char left = stk.top(); 10 | if((c == ')' && left != '(') || (c == ']' && left != '[') || (c == '}' && left != '{')) return false; 11 | stk.pop(); 12 | } 13 | } 14 | return stk.empty(); 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /C++/021. Merge Two Sorted Lists.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 12 | if (!l1 || !l2) return l1 ? l1 : l2; 13 | ListNode head(0); 14 | ListNode* cur = &head; 15 | while (l1 && l2) { 16 | if (l1->val < l2->val) { 17 | cur->next = l1; 18 | l1 = l1->next; 19 | } 20 | else { 21 | cur->next = l2; 22 | l2 = l2->next; 23 | } 24 | cur = cur->next; 25 | } 26 | cur->next = l1 ? l1 : l2; 27 | return head.next; 28 | } 29 | }; -------------------------------------------------------------------------------- /C++/022. Generate Parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector generateParenthesis(int n) { 4 | vectorres; 5 | string path = ""; 6 | DFS(res, n, 0, 0, path); 7 | return res; 8 | } 9 | 10 | void DFS(vector& res, int n, int k, int left, string& path){ 11 | if(left > n) return; 12 | if(k == n){ 13 | if(left == 0) res.push_back(path); 14 | return; 15 | } 16 | path.push_back('('); 17 | DFS(res, n, k, left + 1, path); 18 | path.pop_back(); 19 | 20 | if(left != 0){ 21 | path.push_back(')'); 22 | DFS(res, n, k + 1, left - 1, path); 23 | path.pop_back(); 24 | } 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /C++/024. Swap Nodes in Pairs.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode* swapPairs(ListNode* head) { 12 | if (!head || !head->next) return head; 13 | ListNode res(0); 14 | ListNode *pre = &res, *one = head, *two = head->next; 15 | while (one && two) { 16 | one->next = two->next; 17 | two->next = one; 18 | pre->next = two; 19 | pre = one; 20 | one = one->next; 21 | if (one) two = one->next; 22 | } 23 | return res.next; 24 | } 25 | }; -------------------------------------------------------------------------------- /C++/026. Remove Duplicates from Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeDuplicates(vector& nums) { 4 | int i = 0, j = 0; 5 | while(j < nums.size()){ 6 | while(j < nums.size() - 1 && nums[j] == nums[j + 1]) j++; 7 | nums[i++] = nums[j++]; 8 | } 9 | return i; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /C++/027. Remove Element.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeElement(vector& nums, int val) { 4 | int i = 0, j = 0; 5 | while(j != nums.size()) 6 | if(nums[j] == val) j++; 7 | else nums[i++] = nums[j++]; 8 | return i; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /C++/031. Next Permutation.cpp: -------------------------------------------------------------------------------- 1 | // My BF O(n^2) solution 2 | class Solution { 3 | public: 4 | void nextPermutation(vector& nums) { 5 | int left = 0, right = -1; 6 | for(int i = nums.size() - 1; i >= 0; i--) 7 | for(int j = i - 1; j >= 0; j--) 8 | if(nums[j] < nums[i] && (j > left || right == -1)) left = j, right = i; 9 | if(right == -1) sort(nums.begin(), nums.end()); 10 | else{ 11 | swap(nums[left], nums[right]); 12 | sort(nums.begin() + left + 1, nums.end()); 13 | } 14 | } 15 | }; 16 | 17 | // O(n) Solution from Stefan: https://discuss.leetcode.com/topic/19264/1-4-11-lines-c 18 | void nextPermutation(vector& nums) { 19 | int i = nums.size() - 1, k = i; 20 | while (i > 0 && nums[i-1] >= nums[i]) 21 | i--; 22 | for (int j=i; j 0) { 25 | k = i--; 26 | while (nums[k] <= nums[i]) 27 | k++; 28 | swap(nums[i], nums[k]); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /C++/034. Search for a Range.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector searchRange(vector& nums, int target) { 4 | int lo = lower_bound(nums.begin(), nums.end(), target) - nums.begin(); 5 | int hi = upper_bound(nums.begin(), nums.end(), target) - nums.begin() - 1; 6 | if(lo > hi) return {-1,-1}; 7 | return {lo, hi}; 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /C++/035. Search Insert Position.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int searchInsert(vector& nums, int target) { 4 | int lo = 0, hi = nums.size() - 1; 5 | int mid = lo + (hi - lo) / 2; 6 | while(lo <= hi){ 7 | if(nums[mid] == target) return mid; 8 | if(nums[mid] > target) hi = mid - 1; 9 | else lo = mid + 1; 10 | mid = lo + (hi - lo) / 2; 11 | } 12 | return lo; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /C++/036. Valid Sudoku.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isValidSudoku(vector>& board) { 4 | int n = board.size(); 5 | vector>row(n); 6 | vector>col(n); 7 | vector>>sub(n/3, vector>(n/3)); 8 | for(int i = 0; i < n; i++) 9 | for(int j = 0; j < n; j++){ 10 | char c = board[i][j]; 11 | if(c == '.') continue; 12 | if(row[i][c]++ > 0 || col[j][c]++ > 0 || sub[i/3][j/3][c]++ > 0) return false; 13 | } 14 | return true; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /C++/038. Count and Say.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string countAndSay(int n) { 4 | if(n == 1) return "1"; 5 | string s = countAndSay(n - 1); 6 | string res = ""; 7 | for(int i = 0; i < s.size(); i++){ 8 | int count = 1; 9 | while(i < s.size() - 1 && s[i] == s[i + 1]) i++, count++; 10 | res.append(to_string(count) + s[i]); 11 | } 12 | return res; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /C++/039. Combination Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> combinationSum(vector& candidates, int target) { 4 | vector>res; 5 | vectorcomb; 6 | backtrack(res, candidates, 0, 0, target, comb); 7 | return res; 8 | } 9 | 10 | void backtrack(vector>& res, vector& candidates, int pos, int sum, int target, vector& comb){ 11 | if(sum > target || pos == candidates.size()) return; 12 | if(sum == target){ 13 | res.push_back(comb); 14 | return; 15 | } 16 | backtrack(res, candidates, pos + 1, sum, target, comb); 17 | comb.push_back(candidates[pos]); 18 | backtrack(res, candidates, pos, sum + candidates[pos], target, comb); 19 | comb.pop_back(); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /C++/040. Combination Sum II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> combinationSum2(vector& candidates, int target) { 4 | sort(candidates.begin(), candidates.end()); 5 | vector>res; 6 | vectorpath; 7 | DFS(res, candidates, 0, 0, target, path); 8 | return res; 9 | } 10 | 11 | void DFS(vector>& res, vector& candidates, int pos, int sum, int target, vector& path){ 12 | if(sum >= target){ 13 | if(sum == target) res.push_back(path); 14 | return; 15 | } 16 | for(int i = pos; i < candidates.size(); i++){ 17 | if(i != pos && candidates[i] == candidates[i - 1]) continue; 18 | path.push_back(candidates[i]); 19 | DFS(res, candidates, i + 1, sum + candidates[i], target, path); 20 | path.pop_back(); 21 | } 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /C++/041. First Missing Positive.cpp: -------------------------------------------------------------------------------- 1 | // O(nlogn) 2 | class Solution { 3 | public: 4 | int firstMissingPositive(vector& nums) { 5 | sort(nums.begin(), nums.end()); 6 | int i = 1; 7 | for(int x: nums) if(x == i) i++; 8 | return i; 9 | } 10 | }; 11 | 12 | // O(n) 13 | class Solution { 14 | public: 15 | int firstMissingPositive(vector& nums) { 16 | if(nums.empty()) return 1; 17 | for(int i = 0; i < nums.size(); i++) 18 | while(nums[i] > 0 && nums[i] < nums.size() && nums[i] != nums[nums[i] - 1]) swap(nums[i], nums[nums[i] - 1]); 19 | for(int i = 0; i < nums.size(); i++) if(nums[i] != i + 1) return i + 1; 20 | return nums.size() + 1; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /C++/042. Trapping Rain Water.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int trap(vector& height) { 4 | int sum = 0, maxH = 0; 5 | stackstk, idx; 6 | for(int i = 0; i < height.size(); i++){ 7 | int h = min(maxH, height[i]); 8 | if(!stk.empty()){ 9 | int temp = 0, preIdx = i, preH = h, curH = h; 10 | while(!stk.empty() && stk.top() < height[i]){ 11 | curH = stk.top(); 12 | temp += (h - preH) * (preIdx - idx.top()) - (curH - preH); 13 | preH = stk.top(); 14 | stk.pop(); 15 | preIdx = idx.top(); 16 | idx.pop(); 17 | } 18 | if(!stk.empty()) temp += (h - preH) * (preIdx - 1 - idx.top()); 19 | sum += temp; 20 | } 21 | stk.push(height[i]); 22 | idx.push(i); 23 | maxH = max(maxH, height[i]); 24 | } 25 | return sum; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /C++/045. Jump Game II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int jump(vector& nums) { 4 | int minJump = nums.size(); 5 | DFS(nums, 0, 0, minJump); 6 | return minJump; 7 | } 8 | 9 | void DFS(vector& nums, int pos, int jump, int& minJump){ 10 | if(pos == nums.size() - 1){ 11 | minJump = min(minJump, jump); 12 | return; 13 | } 14 | int next = pos + 1, maxlen = 1 + nums[pos + 1]; 15 | for(int i = 1; i <= nums[pos] && pos + i < nums.size(); i++) 16 | if(i + nums[pos + i] > maxlen || pos + i == nums.size() - 1) next = pos + i, maxlen = i + nums[next]; 17 | DFS(nums, next, jump + 1, minJump); 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /C++/046. Permutations.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> permute(vector& nums) { 4 | vector>res; 5 | DFS(res, nums, 0); 6 | return res; 7 | } 8 | 9 | void DFS(vector>& res, vector& nums, int pos){ 10 | if(pos == nums.size() - 1){ 11 | res.push_back(nums); 12 | return; 13 | } 14 | for(int i = pos; i < nums.size(); i++){ 15 | swap(nums[pos], nums[i]); 16 | DFS(res, nums, pos + 1); 17 | swap(nums[pos], nums[i]); 18 | } 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /C++/047. Permutations II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> permuteUnique(vector& nums) { 4 | sort(nums.begin(), nums.end()); 5 | vector>res; 6 | DFS(res, nums, 0); 7 | return res; 8 | } 9 | 10 | void DFS(vector>& res, vector nums, int pos){ 11 | if(pos == nums.size() - 1){ 12 | res.push_back(nums); 13 | return; 14 | } 15 | for(int i = pos; i < nums.size(); i++){ 16 | if(i != pos && nums[i] == nums[pos]) continue; 17 | swap(nums[pos], nums[i]); 18 | DFS(res, nums, pos + 1); 19 | } 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /C++/053. Maximum Subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxSubArray(vector& nums) { 4 | // dp[i] = max(dp[i - 1] + A[i], A[i]) 5 | vectordp(nums.size()); 6 | dp[0] = nums[0]; 7 | int maxSum = dp[0]; 8 | for(int i = 1; i < nums.size(); i++){ 9 | dp[i] = max(dp[i - 1] + nums[i], nums[i]); 10 | maxSum = max(maxSum, dp[i]); 11 | } 12 | return maxSum; 13 | } 14 | }; 15 | 16 | // Then we notice dp[i] only depends on dp[i - 1], so actually we only need one variable here to replace the array. 17 | class Solution { 18 | public: 19 | int maxSubArray(vector& nums) { 20 | int dp = nums[0]; 21 | int maxSum = dp; 22 | for(int i = 1; i < nums.size(); i++){ 23 | dp = max(dp + nums[i], nums[i]); 24 | maxSum = max(maxSum, dp); 25 | } 26 | return maxSum; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /C++/055. Jump Game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canJump(vector& nums) { 4 | int distance = 0; 5 | for(int i = 0; i < nums.size() - 1; i++){ 6 | distance = max(distance, i + nums[i]); 7 | if(distance == i) return false; 8 | } 9 | return true; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /C++/056. Merge Intervals.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for an interval. 3 | * struct Interval { 4 | * int start; 5 | * int end; 6 | * Interval() : start(0), end(0) {} 7 | * Interval(int s, int e) : start(s), end(e) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | vector merge(vector& intervals) { 13 | sort(intervals.begin(), intervals.end(), [](Interval& a, Interval& b){ return a.start < b.start; }); 14 | vectorres; 15 | for(int i = 0; i < intervals.size(); i++) 16 | if(res.empty() || res.back().end < intervals[i].start) res.push_back(intervals[i]); 17 | else res.back().end = max(res.back().end, intervals[i].end); 18 | return res; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /C++/058. Length of Last Word.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLastWord(string s) { 4 | int i = s.size() - 1; 5 | while(i >= 0 && s[i] == ' ') i--; 6 | int j = i; 7 | while(j >= 0 && s[j] != ' ') j--; 8 | return i - j; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /C++/059. Spiral Matrix II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> generateMatrix(int n) { 4 | vector>matrix(n, vector(n, 0)); 5 | if(n == 0) return matrix; 6 | spiral(matrix, 0, n - 1, 0, n - 1, 1, n); 7 | return matrix; 8 | } 9 | 10 | void spiral(vector>& matrix, int minRow, int maxRow, int minCol, int maxCol, int k, int n){ 11 | if(k > n * n) return; 12 | if(k == n * n){ 13 | matrix[minRow][minCol] = k; 14 | return; 15 | } 16 | for(int i = minCol; i <= maxCol; i++) matrix[minRow][i] = k++; 17 | minRow++; 18 | for(int i = minRow; i <= maxRow; i++) matrix[i][maxCol] = k++; 19 | maxCol--; 20 | for(int i = maxCol; i >= minCol; i--) matrix[maxRow][i] = k++; 21 | maxRow--; 22 | for(int i = maxRow; i >= minRow; i--) matrix[i][minCol] = k++; 23 | minCol++; 24 | spiral(matrix, minRow, maxRow, minCol, maxCol, k, n); 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /C++/063. Unique Paths II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int uniquePathsWithObstacles(vector>& obstacleGrid) { 4 | int m = obstacleGrid.size(), n = obstacleGrid[0].size(); 5 | vectordp(n); 6 | dp[0] = 1; 7 | for (int i = 0; i < m; ++i) { 8 | for (int j = 0; j < n; ++j) { 9 | if (obstacleGrid[i][j] == 1) { 10 | dp[j] = 0; 11 | } else { 12 | dp[j] += dp[j - 1]; 13 | } 14 | } 15 | } 16 | return dp[n - 1]; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /C++/064. Minimum Path Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minPathSum(vector>& grid) { 4 | if(grid.empty()) return 0; 5 | int m = grid.size(), n = grid[0].size(); 6 | vector>dp(m, vector(n)); 7 | dp[0][0] = grid[0][0]; 8 | for(int i = 1; i < m; i++) dp[i][0] = grid[i][0] + dp[i - 1][0]; 9 | for(int i = 1; i < n; i++) dp[0][i] = grid[0][i] + dp[0][i - 1]; 10 | for(int i = 1; i < m; i++) 11 | for(int j = 1; j < n; j++) 12 | dp[i][j] = min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j]; 13 | return dp[m - 1][n - 1]; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /C++/066. Plus One.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector plusOne(vector& digits) { 4 | int i = digits.size() - 1; 5 | while(i >= 0 && digits[i] == 9) digits[i--] = 0; 6 | if(i < 0) digits.push_back(0), i++; 7 | digits[i]++; 8 | return digits; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /C++/068. Text Justification.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector fullJustify(vector& words, int maxWidth) { 4 | vectorres; 5 | if(maxWidth == 0) return {""}; 6 | int i = 0, j = 0; 7 | while(j != words.size()){ 8 | int len = -1; 9 | while(j < words.size() && len + words[j].size() + 1 <= maxWidth) 10 | len += words[j++].size() + 1; 11 | int space = maxWidth - len + j - i - 1; 12 | int k = i; 13 | while(space){ 14 | words[k++] += " "; 15 | space--; 16 | if(j != words.size() && (k == j - 1 || k == j)) k = i; 17 | if(j == words.size() && k == j) k = j - 1; 18 | } 19 | string line = ""; 20 | for(int l = i; l < j; l++) 21 | line += words[l]; 22 | res.push_back(line); 23 | i = j; 24 | } 25 | return res; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /C++/069. Sqrt(x).cpp: -------------------------------------------------------------------------------- 1 | // Solution 1. Binary Search 2 | class Solution { 3 | public: 4 | int mySqrt(int x) { 5 | if(x == 0) return x; 6 | int lo = 1, hi = x; 7 | while (true) { 8 | int mid = lo + (hi - lo)/2; 9 | if (mid > x/mid) hi = mid - 1; 10 | else if (mid + 1 > x/(mid + 1)) return mid; 11 | else lo = mid + 1; 12 | } 13 | } 14 | }; 15 | 16 | // Solution 2. Newton's Method. 17 | /** 18 | * Guess Result Quotient Average Result 19 | * 1 2 / 1 = 2 (2 + 1) / 2 = 1.5 20 | * 1.5 2 / 1.5 = 1.3333 (1.3333 + 1.5) / 2 = 1.4167 21 | * 1.4167 2 / 1.4167 = 1.4118 (1.4167 + 1.4118) / 2 = 1.4142 22 | */ 23 | class Solution { 24 | public: 25 | int mySqrt(int x) { 26 | long r = x; 27 | while (r*r > x) 28 | r = (r + x/r) / 2; 29 | return r; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /C++/070. Climbing Stairs.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Idea: 3 | * Get to stair n has two ways: 4 | * 1. Stand at stair n - 1, take step = 1 forward. 5 | * 2. Stand at stair n - 2, take step = 2 forward. 6 | * So the total ways to get to the stair(n) = total ways to stair(n - 1) + total ways to stair(n - 2). 7 | */ 8 | class Solution { 9 | public: 10 | int climbStairs(int n) { 11 | vectordp(n + 1); 12 | dp[0] = 1; 13 | dp[1] = 1; 14 | for(int i = 2; i < n + 1; i++) 15 | dp[i] = dp[i - 1] + dp[i - 2]; 16 | return dp[n]; 17 | } 18 | }; 19 | 20 | // Then we notice that dp[i] only concerns with dp[i - 1] and dp[i - 2], 21 | // so we could use two variables to replace the array, reduce space to O(1). 22 | class Solution { 23 | public: 24 | int climbStairs(int n) { 25 | int one = 1, two = 1, three = 1; 26 | for(int i = 2; i < n + 1; i++){ 27 | three = one + two; 28 | one = two; 29 | two = three; 30 | } 31 | return three; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /C++/071. Simplify Path.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string simplifyPath(string path) { 4 | string res, s; 5 | stackstk; 6 | stringstream ss(path); 7 | while(getline(ss, s, '/')) { 8 | if (s == "" || s == ".") continue; 9 | if (s == ".." && !stk.empty()) stk.pop(); 10 | else if (s != "..") stk.push(s); 11 | } 12 | while(!stk.empty()){ 13 | res = "/"+ stk.top() + res; 14 | stk.pop(); 15 | } 16 | return res.empty() ? "/" : res; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /C++/076. Minimum Window Substring.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string minWindow(string s, string t) { 4 | unordered_mapm; 5 | int i = 0, j = 0, count = 0, minLen = INT_MAX; 6 | string res = ""; 7 | for(auto x: t) m[x]++, count++; 8 | while(j < s.size()){ 9 | if(m[s[j++]]-- > 0) count--; 10 | if(count == 0){ 11 | while(m[s[i]] < 0) m[s[i++]]++; 12 | int len = j - i; 13 | if(len < minLen){ 14 | minLen = len; 15 | res = s.substr(i, len); 16 | } 17 | m[s[i++]]++; 18 | count++; 19 | } 20 | } 21 | return res; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /C++/078. Subsets.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> subsets(vector& nums) { 4 | vector>res; 5 | backtrack(nums, 0, vector(), res); 6 | return res; 7 | } 8 | 9 | void backtrack(vector& nums, int k, vector subset, vector>& res){ 10 | if(k == nums.size()){ 11 | res.push_back(subset); 12 | return; 13 | } 14 | backtrack(nums, k+1, subset, res); 15 | subset.push_back(nums[k]); 16 | backtrack(nums, k+1, subset, res); 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /C++/080. Remove Duplicates from Sorted Array II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeDuplicates(vector& nums) { 4 | if(nums.size() < 3) return nums.size(); 5 | int i = 2, j = 2; 6 | while(j < nums.size()) 7 | if(nums[j] > nums[i - 2]) nums[i++] = nums[j++]; 8 | else j++; 9 | return i; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /C++/082. Remove Duplicates from Sorted List II.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode* deleteDuplicates(ListNode* head) { 12 | ListNode res(0); 13 | res.next = head; 14 | ListNode* pre = &res, *cur = head, *next = cur ? cur->next : NULL; 15 | while(cur){ 16 | bool dup = false; 17 | while(next && next->val == cur->val){ 18 | dup = true; 19 | next = next->next; 20 | } 21 | if(dup){ 22 | cur = next; 23 | next = next ? next->next : NULL; 24 | pre->next = cur; 25 | } 26 | else{ 27 | pre = cur; 28 | cur = next; 29 | next = next ? next->next : NULL; 30 | } 31 | } 32 | return res.next; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /C++/083. Remove Duplicates from Sorted List.cpp: -------------------------------------------------------------------------------- 1 | // Recursive 2 | class Solution { 3 | public: 4 | ListNode* deleteDuplicates(ListNode* head) { 5 | if(!head || !head->next) return head; 6 | auto p = deleteDuplicates(head->next); 7 | head->next = p; 8 | return p->val == head->val ? p : head; 9 | } 10 | }; 11 | 12 | // Non-recursive 13 | class Solution { 14 | public: 15 | ListNode* deleteDuplicates(ListNode* head) { 16 | if(!head || !head->next) return head; 17 | ListNode* pre = head, *cur = head->next; 18 | while(cur){ 19 | pre->val == cur->val ? pre->next = cur->next : pre = cur; 20 | cur = cur->next; 21 | } 22 | return head; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /C++/085. Maximal Rectangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximalRectangle(vector>& matrix) { 4 | if(matrix.size() == 0) return 0; 5 | int m = matrix.size(), n = matrix[0].size(), maxArea = 0; 6 | for(int i = 0; i < m; i++) 7 | for(int j = 0; j < n; j++) 8 | if(matrix[i][j] == '1') maxArea = max(maxArea, BFS(matrix, i, j)); 9 | return maxArea; 10 | } 11 | 12 | int BFS(vector>& matrix, int r, int c){ 13 | int row = r - 1, maxArea = 0; 14 | while(row >= 0 && matrix[row][c] == '1') row--; 15 | for(int i = c; i >= 0 && matrix[r][i] == '1'; i--){ 16 | for(int j = row + 1; j <= r; j++) 17 | if(matrix[j][i] == '0') row = max(row, j); 18 | maxArea = max(maxArea, (r - row) * (c - i + 1)); 19 | } 20 | return maxArea; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /C++/086. Partition List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode* partition(ListNode* head, int x) { 12 | ListNode left(0); 13 | ListNode right(0); 14 | ListNode* l = &left; 15 | ListNode* r = &right; 16 | ListNode* cur = head; 17 | while(cur){ 18 | if(cur->val < x){ 19 | l->next = cur; 20 | l = l->next; 21 | } 22 | else{ 23 | r->next = cur; 24 | r = r->next; 25 | } 26 | cur = cur->next; 27 | } 28 | r->next = NULL; 29 | l->next = right.next; 30 | return left.next; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /C++/088. Merge Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void merge(vector& nums1, int m, vector& nums2, int n) { 4 | for(int i = m - 1, j = n - 1; j >= 0;) nums1[i + j + 1] = (i < 0 || nums1[i] < nums2[j]) ? nums2[j--] : nums1[i--]; 5 | } 6 | }; 7 | 8 | // longer. 9 | class Solution { 10 | public: 11 | void merge(vector& nums1, int m, vector& nums2, int n) { 12 | int i = m - 1, j = n - 1; 13 | while(i + j + 1 >= 0){ 14 | nums1[i + j + 1] = i < 0 ? nums2[j--] : j < 0 ? nums1[i--] : nums1[i] > nums2[j] ? nums1[i--] : nums2[j--]; 15 | } 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /C++/092. Reverse Linked List II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* reverseBetween(ListNode* head, int m, int n) { 4 | ListNode* l = new ListNode(0); 5 | l->next = head; 6 | int x = m, y = n - m; 7 | while(--x) l = l->next; 8 | ListNode* pre = l->next, *cur = pre->next, *next; 9 | while(y--){ 10 | next = cur->next; 11 | cur->next = pre; 12 | pre = cur; 13 | cur = next; 14 | } 15 | l->next->next = cur; 16 | l->next = pre; 17 | return m == 1 ? pre : head; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /C++/095. Unique Binary Search Trees II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector generateTrees(int n) { 4 | if(n == 0) return {}; 5 | return DFS(1, n); 6 | } 7 | 8 | vector DFS(int l, int r){ 9 | vectorres; 10 | if(l > r) return {NULL}; 11 | for(int i = l; i <= r; i++){ 12 | auto left = DFS(l, i - 1); 13 | auto right = DFS(i + 1, r); 14 | for(auto x: left) 15 | for(auto y: right){ 16 | TreeNode* root = new TreeNode(i); 17 | root->left = x; 18 | root->right = y; 19 | res.push_back(root); 20 | } 21 | } 22 | return res; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /C++/099. Recover Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | void recoverTree(TreeNode* root) { 13 | TreeNode* pre = NULL, *one = NULL, *two = NULL; 14 | DFS(root, pre, one, two); 15 | swap(one->val, two->val); 16 | } 17 | 18 | void DFS(TreeNode* cur, TreeNode* &pre, TreeNode* &one, TreeNode* &two){ 19 | if(!cur) return; 20 | DFS(cur->left, pre, one, two); 21 | if(pre && cur->val < pre->val){ 22 | if(!one) one = pre; 23 | two = cur; 24 | } 25 | pre = cur; 26 | DFS(cur->right, pre, one, two); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /C++/104. Maximum Depth of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | int maxDepth(TreeNode* root) { 13 | if (!root) return 0; 14 | return max(maxDepth(root->left), maxDepth(root->right)) + 1; 15 | } 16 | }; -------------------------------------------------------------------------------- /C++/107. Binary Tree Level Order Traversal II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> levelOrderBottom(TreeNode* root) { 4 | vector>v; 5 | dfs(root, v, 0); 6 | reverse(v.begin(), v.end()); 7 | return v; 8 | } 9 | 10 | void dfs(TreeNode* root, vector>& v, int level){ 11 | if(!root) return; 12 | if(level == v.size()) v.push_back({}); 13 | v[level].push_back(root->val); 14 | dfs(root->left, v, level + 1); 15 | dfs(root->right, v, level + 1); 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /C++/108. Convert Sorted Array to Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | TreeNode* sortedArrayToBST(vector& nums) { 13 | if(nums.empty()) return NULL; 14 | TreeNode* root = new TreeNode(nums[nums.size() / 2]); 15 | vectorleft(nums.begin(), nums.begin() + nums.size() / 2); 16 | vectorright(nums.begin() + nums.size() / 2 + 1, nums.end()); 17 | root->left = sortedArrayToBST(left); 18 | root->right = sortedArrayToBST(right); 19 | return root; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /C++/110. Balanced Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | bool isBalanced(TreeNode* root) { 13 | bool res = true; 14 | dfs(root, res); 15 | return res; 16 | } 17 | 18 | int dfs(TreeNode* root, bool& res){ 19 | if(!root) return 0; 20 | int l = dfs(root->left, res); 21 | int r = dfs(root->right, res); 22 | if(abs(l - r) > 1) res = false; 23 | return max(l, r) + 1; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /C++/111. Minimum Depth of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | int minDepth(TreeNode* root) { 13 | if(!root) return 0; 14 | int l = minDepth(root->left); 15 | int r = minDepth(root->right); 16 | return root->left && root->right ? min(l, r) + 1 : l + r + 1; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /C++/112. Path Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool hasPathSum(TreeNode* root, int sum) { 4 | if(!root) return false; 5 | sum -= root->val; 6 | if(!sum && !root->left && !root->right) return true; 7 | return hasPathSum(root->left, sum) || hasPathSum(root->right, sum); 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /C++/113. Path Sum II.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | vector> pathSum(TreeNode* root, int sum) { 13 | vector>res; 14 | if(!root) return res; 15 | DFS(root, res, vector(), 0, sum); 16 | return res; 17 | } 18 | 19 | void DFS(TreeNode* root, vector>& res, vectorpath, int sum, int target){ 20 | if(!root) return; 21 | path.push_back(root->val); 22 | sum += root->val; 23 | if(!root->left && !root->right){ 24 | if(sum == target) res.push_back(path); 25 | return; 26 | } 27 | DFS(root->left, res, path, sum, target); 28 | DFS(root->right, res, path, sum, target); 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /C++/118. Pascal's Triangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> generate(int numRows) { 4 | if(numRows == 0) return {}; 5 | if(numRows == 1) return {{1}}; 6 | auto v = generate(numRows - 1); 7 | auto lastRow = *(v.end() - 1); 8 | vectorres(1, 1); 9 | for(int i = 0; i < lastRow.size() - 1; i++) res.push_back(lastRow[i] + lastRow[i + 1]); 10 | res.push_back(1); 11 | v.push_back(res); 12 | return v; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /C++/119. Pascal's Triangle II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector getRow(int rowIndex) { 4 | if(rowIndex == 0) return {1}; 5 | auto v = getRow(rowIndex - 1); 6 | int n = v.size(); 7 | for(int i = 1; i < n; i++) 8 | v[i] = (i <= n/2) ? v[i] + v[n - i] : v[n - i]; 9 | v.push_back(1); 10 | return v; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /C++/120. Triangle.cpp: -------------------------------------------------------------------------------- 1 | // Bottom-up 2 | class Solution { 3 | public: 4 | int minimumTotal(vector>& triangle) { 5 | int n = triangle.size(); 6 | vectordp(n + 1); 7 | for(int i = n - 1; i >= 0; i--) 8 | for(int j = 0; j <= i; j++) 9 | dp[j] = triangle[i][j] + min(dp[j], dp[j + 1]); 10 | return dp[0]; 11 | } 12 | }; 13 | 14 | // Top-down 15 | class Solution { 16 | public: 17 | int minimumTotal(vector>& triangle) { 18 | int n = triangle.size(); 19 | vectordp(n); 20 | for(int i = 0; i < n; i++){ 21 | if(i != 0) dp[i] = dp[i - 1] + triangle[i][i]; 22 | for(int j = i - 1; j > 0; j--) 23 | dp[j] = triangle[i][j] + min(dp[j], dp[j - 1]); 24 | dp[0] = dp[0] + triangle[i][0]; 25 | } 26 | return *min_element(dp.begin(), dp.end()); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /C++/124. Binary Tree Maximum Path Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxPathSum(TreeNode* root) { 4 | int maxSum = INT_MIN; 5 | DFS(root, maxSum); 6 | return maxSum; 7 | } 8 | 9 | int DFS(TreeNode* root, int& maxSum){ 10 | if(!root) return 0; 11 | int left = max(0, DFS(root->left, maxSum)); 12 | int right = max(0, DFS(root->right, maxSum)); 13 | maxSum = max(maxSum, left + right + root->val); 14 | return max(left, right) + root->val; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /C++/125. Valid Palindrome.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPalindrome(string s) { 4 | int i = 0, j = s.size() - 1; 5 | while(i < j){ 6 | while(i < j && !isalnum(s[i])) i++; 7 | while(i < j && !isalnum(s[j])) j--; 8 | if(tolower(s[i++]) != tolower(s[j--])) return false; 9 | } 10 | return true; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /C++/128. Longest Consecutive Sequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestConsecutive(vector& nums) { 4 | int maxlen = 0; 5 | unordered_mapm; 6 | for(auto x: nums){ 7 | if(m[x]) continue; 8 | int left = m[x - 1]; 9 | int right = m[x + 1]; 10 | m[x + right] = m[x - left] = m[x] = left + right + 1; 11 | maxlen = max(maxlen, m[x]); 12 | } 13 | return maxlen; 14 | } 15 | }; 16 | 17 | class Solution { 18 | public: 19 | int longestConsecutive(vector& nums) { 20 | unordered_mapm; 21 | int res = 0; 22 | for (int& x: nums) { 23 | if (m[x]) { 24 | continue; 25 | } 26 | int l = m[x - 1]; 27 | int r = m[x + 1]; 28 | m[x] = l + r + 1; 29 | m[x - l] = l + r + 1; 30 | m[x + r] = l + r + 1; 31 | res = max(res, m[x]); 32 | } 33 | return res; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /C++/131. Palindrome Partitioning.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> partition(string s) { 4 | vector>res; 5 | vectorv; 6 | dfs(s, 0, v, res); 7 | return res; 8 | } 9 | 10 | void dfs(string s, int pos, vector& v, vector>& res){ 11 | if(pos >= s.size()){ 12 | res.push_back(v); 13 | return; 14 | } 15 | 16 | for(int i = pos; i < s.size(); i++){ 17 | int l = pos, r = i; 18 | bool b = true; 19 | while(l < r && b) if(s[l++] != s[r--]) b = false; 20 | if(b){ 21 | v.push_back(s.substr(pos, i - pos + 1)); 22 | dfs(s, i + 1, v, res); 23 | v.pop_back(); 24 | } 25 | } 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /C++/134. Gas Station.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int canCompleteCircuit(vector& gas, vector& cost) { 4 | int n(gas.size()), sum(0), total(0), res(0); 5 | for (int i = 0; i < n; ++i) { 6 | sum += gas[i] - cost[i]; 7 | if (sum < 0) { 8 | res = i + 1; 9 | sum = 0; 10 | } 11 | total += gas[i] - cost[i]; 12 | } 13 | return total >= 0 ? res : -1; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /C++/136. Single Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int singleNumber(vector& nums) { 4 | int res = 0; 5 | for(auto& x: nums) res ^= x; 6 | return res; 7 | } 8 | }; 9 | -------------------------------------------------------------------------------- /C++/138. Copy List with Random Pointer.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list with a random pointer. 3 | * struct RandomListNode { 4 | * int label; 5 | * RandomListNode *next, *random; 6 | * RandomListNode(int x) : label(x), next(NULL), random(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | RandomListNode *copyRandomList(RandomListNode *head) { 12 | unordered_mapm; 13 | auto p = head; 14 | while(p){ 15 | m[p] = new RandomListNode(p->label); 16 | p = p->next; 17 | } 18 | p = head; 19 | while(p){ 20 | m[p]->next = m[p->next]; 21 | m[p]->random = m[p->random]; 22 | p = p->next; 23 | } 24 | return m[head]; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /C++/139. Word Break.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | unordered_mapm; 4 | unordered_mapdp; 5 | public: 6 | bool wordBreak(string s, vector& wordDict) { 7 | for(auto x: wordDict) m[x]++; 8 | return DFS(s); 9 | } 10 | 11 | bool DFS(string s){ 12 | if(dp.count(s)) return dp[s]; 13 | if(s.empty()) return true; 14 | bool found = false; 15 | for(int i = 1; i <= s.size() && !found; i++) 16 | if(m.count(s.substr(0, i))) found |= DFS(s.substr(i)); 17 | dp[s] = found; 18 | return found; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /C++/141. Linked List Cycle.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | bool hasCycle(ListNode *head) { 12 | auto one = head, two = head; 13 | while(two && two->next){ 14 | one = one->next; 15 | two = two->next->next; 16 | if(one == two) return true; 17 | } 18 | return false; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /C++/142. Linked List Cycle II.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode *detectCycle(ListNode *head) { 12 | auto one = head, two = head, meet = head; 13 | while(two && two->next){ 14 | one = one->next; 15 | two = two->next->next; 16 | if(one == two){ 17 | meet = one; 18 | break; 19 | } 20 | } 21 | if(!two || !two->next) return NULL; 22 | auto p = head; 23 | while(p != meet){ 24 | p = p->next; 25 | meet = meet->next; 26 | } 27 | return p; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /C++/144. Binary Tree Preorder Traversal.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector preorderTraversal(TreeNode* root) { 4 | vectorres; 5 | stacks; 6 | auto p = root; 7 | while(p || !s.empty()){ 8 | if(!p) p = s.top(), s.pop(); 9 | res.push_back(p->val); 10 | if(p->right) s.push(p->right); 11 | p = p->left; 12 | } 13 | return res; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /C++/145. Binary Tree Postorder Traversal.cpp: -------------------------------------------------------------------------------- 1 | // Iterative 2 | class Solution { 3 | public: 4 | vector postorderTraversal(TreeNode* root) { 5 | vectorres; 6 | stacks; 7 | while(!s.empty() || root){ 8 | if(root){ 9 | s.push(root->left); 10 | res.push_back(root->val); 11 | root = root->right; 12 | } 13 | else{ 14 | root = s.top(); 15 | s.pop(); 16 | } 17 | } 18 | reverse(res.begin(), res.end()); 19 | return res; 20 | } 21 | }; 22 | 23 | // Recursive 24 | class Solution { 25 | public: 26 | vector postorderTraversal(TreeNode* root) { 27 | vectorres; 28 | DFS(root, res); 29 | return res; 30 | } 31 | 32 | void DFS(TreeNode* root, vector& res){ 33 | if(!root) return; 34 | DFS(root->left, res); 35 | DFS(root->right, res); 36 | res.push_back(root->val); 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /C++/155. Min Stack.cpp: -------------------------------------------------------------------------------- 1 | class MinStack { 2 | private: 3 | stacks; 4 | stackmin; 5 | public: 6 | /** initialize your data structure here. */ 7 | MinStack() {} 8 | 9 | void push(int x) { 10 | s.push(x); 11 | if(min.empty() || x <= min.top()) min.push(x); 12 | } 13 | 14 | void pop() { 15 | if(s.top() == min.top()) min.pop(); 16 | s.pop(); 17 | } 18 | 19 | int top() { 20 | return s.top(); 21 | } 22 | 23 | int getMin() { 24 | return min.top(); 25 | } 26 | }; 27 | 28 | /** 29 | * Your MinStack object will be instantiated and called as such: 30 | * MinStack obj = new MinStack(); 31 | * obj.push(x); 32 | * obj.pop(); 33 | * int param_3 = obj.top(); 34 | * int param_4 = obj.getMin(); 35 | */ 36 | -------------------------------------------------------------------------------- /C++/159. Longest Substring with At Most Two Distinct Characters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLongestSubstringTwoDistinct(string s) { 4 | int maxlen = 0, i = 0, j = 0, next = 0; 5 | unordered_setset; 6 | while(j < s.size()){ 7 | j = i; 8 | while(j < s.size()){ 9 | if(set.size() == 1) next = j; 10 | set.insert(s[j]); 11 | if(set.size() > 2){ 12 | maxlen = max(maxlen, j - i); 13 | i = next; 14 | set.clear(); 15 | break; 16 | } 17 | j++; 18 | } 19 | } 20 | maxlen = max(maxlen, j - i); 21 | return maxlen; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /C++/161. One Edit Distance.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isOneEditDistance(string s, string t) { 4 | int diff = abs((int)s.size() - (int)t.size()); 5 | if(diff > 1) return false; 6 | int distance = 0; 7 | if(diff == 0){ 8 | for(int i = 0; i < s.size(); i++) if(s[i] != t[i]) distance++; 9 | } 10 | else{ 11 | int i = 0, j = 0; 12 | while(i < s.size() && j < t.size()){ 13 | if(s[i] != t[j]){ 14 | s.size() > t.size() ? i++ : j++; 15 | distance++; 16 | } 17 | else i++, j++; 18 | } 19 | if(i != s.size() || j != t.size()) distance++; 20 | } 21 | return distance == 1; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /C++/162. Find Peak Element.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findPeakElement(vector& nums) { 4 | if (nums.size() == 1) { 5 | return 0; 6 | } 7 | int n = nums.size(); 8 | 9 | if (nums[n - 2] < nums[n - 1]) { 10 | return n - 1; 11 | } else if (nums[1] < nums[0]) { 12 | return 0; 13 | } 14 | 15 | int l = 1, r = n - 2, mid; 16 | while (l <= r) { 17 | mid = l + (r - l)/2; 18 | if (nums[mid - 1] > nums[mid]) { 19 | r = mid - 1; 20 | } else if (nums[mid + 1] > nums[mid]) { 21 | l = mid + 1; 22 | } else { 23 | return mid; 24 | } 25 | } 26 | return -1; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /C++/163. Missing Ranges.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findMissingRanges(vector& nums, int lower, int upper) { 4 | vectorres; 5 | if(nums.empty()){ 6 | res.push_back((lower == upper) ? to_string(lower) : to_string(lower) + "->" + to_string(upper)); 7 | return res; 8 | } 9 | int cur = lower; 10 | for(int i = 0; i < nums.size(); i++){ 11 | if(i > 0 && nums[i] == nums[i - 1]) continue; 12 | string s = ""; 13 | if(nums[i] > cur) s += to_string(cur++); 14 | if(nums[i] > cur) s += "->" + to_string(nums[i] - 1); 15 | cur = nums[i] + 1; 16 | if(!s.empty()) res.push_back(s); 17 | } 18 | if(nums.back() == upper - 1) res.push_back(to_string(upper)); 19 | else if(nums.back() < upper) res.push_back(to_string(nums.back() + 1) + "->" + to_string(upper)); 20 | return res; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /C++/168. Excel Sheet Column Title.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string convertToTitle(int n) { 4 | string res; 5 | char c; 6 | while(n){ 7 | c = 'A' + (n - 1) % 26; 8 | res = c + res; 9 | n = (n - 1) / 26; 10 | } 11 | return res; 12 | } 13 | }; 14 | 15 | // Or 16 | class Solution { 17 | public: 18 | string convertToTitle(int n) { 19 | string res = ""; 20 | while(n){ 21 | res.push_back('A' + (n - 1)%26); 22 | n = (n - 1) / 26; 23 | } 24 | reverse(res.begin(), res.end()); 25 | return res; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /C++/169. Majority Element.cpp: -------------------------------------------------------------------------------- 1 | // Solution 1 2 | // Space: O(n) 3 | class Solution { 4 | public: 5 | int majorityElement(vector& nums) { 6 | unordered_mapm; 7 | for(auto x: nums) if(++m[x] > nums.size()/2) return x; 8 | } 9 | }; 10 | 11 | // Solution 2 12 | // [Boyer-Moore Majority Vote algorithm](https://gregable.com/2013/10/majority-vote-algorithm-find-majority.html). 13 | // Space: O(1) 14 | class Solution { 15 | public: 16 | int majorityElement(vector& nums) { 17 | int candidate = 0; 18 | int count = 0; 19 | for(auto x: nums){ 20 | if(count == 0) candidate = x; 21 | if(candidate == x) count++; 22 | else count--; 23 | } 24 | return candidate; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /C++/171. Excel Sheet Column Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int titleToNumber(string s) { 4 | int res = 0; 5 | for(auto c: s){ 6 | res *= 26; 7 | res += c - 'A' + 1; 8 | } 9 | return res; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /C++/186. Reverse Words in a String II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void reverseWords(vector& str) { 4 | for(int i = 0; i < str.size(); i++){ 5 | int j = i + 1; 6 | while(j < str.size() && str[j] != ' ') j++; 7 | int a = i, b = j - 1; 8 | while(a < b) swap(str[a++], str[b--]); 9 | i = j; 10 | } 11 | reverse(str.begin(), str.end()); 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /C++/191. Number of 1 Bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int hammingWeight(uint32_t n) { 4 | int count = 0; 5 | while(n){ 6 | if(n & 1) count++; 7 | n >>= 1; 8 | } 9 | return count; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /C++/198. House Robber.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int rob(vector& nums) { 4 | int n = nums.size(); 5 | if(n < 2) return n ? nums[0] : 0; 6 | vectordp(n); 7 | dp[0] = nums[0], dp[1] = max(nums[0], nums[1]); 8 | for(int i = 2; i < n; i++) 9 | dp[i] = max(dp[i - 2] + nums[i], dp[i - 1]); 10 | return dp[n - 1]; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /C++/200. Number of Islands.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numIslands(vector>& grid) { 4 | if (grid.empty()) { 5 | return 0; 6 | } 7 | int res = 0, m = grid.size(), n = grid[0].size(); 8 | for (int i = 0; i < m; ++i) { 9 | for (int j = 0; j < n; ++j) { 10 | if (grid[i][j] == '1') { 11 | ++res; 12 | dfs(grid, i, j, m, n); 13 | } 14 | } 15 | } 16 | return res; 17 | } 18 | 19 | void dfs(vector>& grid, int r, int c, int& m, int& n) { 20 | if (r < 0 || c < 0 || r == m || c == n || grid[r][c] == '0') { 21 | return; 22 | } 23 | grid[r][c] = '0'; 24 | dfs(grid, r + 1, c, m, n); 25 | dfs(grid, r - 1, c, m, n); 26 | dfs(grid, r, c - 1, m, n); 27 | dfs(grid, r, c + 1, m, n); 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /C++/205. Isomorphic Strings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isIsomorphic(string s, string t) { 4 | unordered_mapms, mt; 5 | for (int i = 0; i < s.size(); ++i) { 6 | if (ms.count(s[i]) && mt.count(t[i])) { 7 | if (ms[s[i]] != t[i]) { 8 | return false; 9 | } 10 | } else if (ms.count(s[i]) || mt.count(t[i])) { 11 | return false; 12 | } else { 13 | ms[s[i]] = t[i]; 14 | mt[t[i]] = s[i]; 15 | } 16 | } 17 | return true; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /C++/206. Reverse Linked List.cpp: -------------------------------------------------------------------------------- 1 | // Iterative 2 | class Solution { 3 | public: 4 | ListNode* reverseList(ListNode* head) { 5 | ListNode* pre(NULL), *cur(head), *next; 6 | while(cur){ 7 | next = cur->next; 8 | cur->next = pre; 9 | pre = cur; 10 | cur = next; 11 | } 12 | return pre; 13 | } 14 | }; 15 | 16 | // Recursive 17 | class Solution { 18 | public: 19 | ListNode* reverseList(ListNode* head) { 20 | if (!head || !head->next) return head; 21 | ListNode* node = reverseList(head->next); 22 | head->next->next = head; 23 | head->next = NULL; 24 | return node; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /C++/207. Course Schedule.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canFinish(int numCourses, vector>& prerequisites) { 4 | vectorindegree(numCourses); 5 | vector>graph(numCourses); 6 | for(auto p: prerequisites){ 7 | graph[p.second].push_back(p.first); 8 | indegree[p.first]++; 9 | } 10 | for(int i = 0; i < numCourses; i++){ 11 | int j = 0; 12 | for(; j < numCourses; j++) if(indegree[j] == 0) break; 13 | if(j == numCourses) return false; 14 | indegree[j] = -1; 15 | for(auto x: graph[j]) indegree[x]--; 16 | } 17 | return true; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /C++/209. Minimum Size Subarray Sum.cpp: -------------------------------------------------------------------------------- 1 | // Solution 1. 2 | class Solution { 3 | public: 4 | int minSubArrayLen(int s, vector& nums) { 5 | int i = 0, j = 0, sum = 0, len = nums.size(); 6 | while(j < nums.size()){ 7 | while(j < nums.size() && sum < s) sum += nums[j++]; 8 | if(i == 0 && sum < s) return 0; 9 | while(sum - nums[i]>= s) sum -= nums[i++]; 10 | len = min(len, j - i); 11 | sum -= nums[i++]; 12 | } 13 | return len; 14 | } 15 | }; 16 | 17 | // Solution 2. 18 | class Solution { 19 | public: 20 | int minSubArrayLen(int s, vector& nums) { 21 | int i = 0, j = 0, len = INT_MAX, sum = 0; 22 | while(j < nums.size()){ 23 | sum += nums[j++]; 24 | while(sum >= s){ 25 | len = min(len, j - i); 26 | sum -= nums[i++]; 27 | } 28 | } 29 | return len == INT_MAX ? 0 : len; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /C++/210. Course Schedule II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findOrder(int numCourses, vector>& prerequisites) { 4 | vectorres; 5 | vectorindegree(numCourses); 6 | vector>graph(numCourses); 7 | for(auto p: prerequisites){ 8 | graph[p.second].push_back(p.first); 9 | indegree[p.first]++; 10 | } 11 | for(int i = 0; i < numCourses; i++){ 12 | int j = 0; 13 | for(; j < numCourses; j++) if(indegree[j] == 0) break; 14 | if(j == numCourses) return vector(); 15 | indegree[j] = -1; 16 | for(auto x: graph[j]) indegree[x]--; 17 | res.push_back(j); 18 | } 19 | return res; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /C++/214. Shortest Palindrome.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string shortestPalindrome(string s) { 4 | string r = s; 5 | reverse(r.begin(), r.end()); 6 | int i = 0, j = s.size(); 7 | while(r.substr(i, j) != s.substr(0, j)) i++, j--; 8 | return r.substr(0, i) + s; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /C++/221. Maximal Square.cpp: -------------------------------------------------------------------------------- 1 | // See detailed explanation in discuss. 2 | class Solution { 3 | public: 4 | int maximalSquare(vector>& matrix) { 5 | if(matrix.size() == 0 || matrix[0].size() == 0) return 0; 6 | int maxSquare = 0; 7 | for(int i = 0; i < matrix.size(); i++) 8 | for(int j = 0; j < matrix[0].size(); j++) 9 | if(matrix[i][j] != '0') maxSquare = max(maxSquare, findSquare(matrix, i, j)); 10 | return maxSquare; 11 | } 12 | 13 | int findSquare(vector>& matrix, int r, int c){ 14 | int row = r - 1; 15 | int col = c - 1; 16 | while(row >= 0 && col >= 0 && matrix[r][col] == '1' && matrix[row][c] == '1'){ 17 | int i = row; 18 | int j = col; 19 | while(i < r && matrix[i][col] == '1') i++; 20 | while(j < c && matrix[row][j] == '1') j++; 21 | if(i != r || j != c) break; 22 | row--; 23 | col--; 24 | } 25 | return pow(r - row, 2); 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /C++/223. Rectangle Area.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { 4 | int areaA = (C - A) * (D - B); 5 | int areaB = (G - E) * (H - F); 6 | if (C < E || A > G || B > H || D < F) return areaA + areaB; 7 | // Bottom left(I, J), Top right(K, L). 8 | int I = max(A, E); 9 | int J = max(B, F); 10 | int K = min(C, G); 11 | int L = min(D, H); 12 | int overlap = (K - I) * (L - J); 13 | return areaA + areaB - overlap; 14 | } 15 | }; -------------------------------------------------------------------------------- /C++/224. Basic Calculator.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int calculate(string s) { 4 | stackstk, op; 5 | int res = 0, sign = 1; 6 | for(int i = 0; i < s.size(); i++){ 7 | char c = s[i]; 8 | if(isdigit(c)){ 9 | int num = c - '0'; 10 | while(i + 1 < s.size() && isdigit(s[i + 1])){ 11 | num = num * 10 + s[i + 1] - '0'; 12 | i++; 13 | } 14 | res += num * sign; 15 | } 16 | else if(c == '+') sign = 1; 17 | else if(c == '-') sign = -1; 18 | else if(c == '('){ 19 | stk.push(res); 20 | op.push(sign); 21 | res = 0; 22 | sign = 1; 23 | } 24 | else if(c == ')'){ 25 | res = res * op.top(); 26 | op.pop(); 27 | res += stk.top(); 28 | stk.pop(); 29 | } 30 | } 31 | return res; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /C++/228. Summary Ranges.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector summaryRanges(vector& nums) { 4 | vectorres; 5 | for(int i = 0, j = 1; i < nums.size(); i = j, j = i + 1){ 6 | while(j < nums.size() && nums[j] == nums[j - 1] + 1) j++; 7 | res.push_back((j == i + 1) ? to_string(nums[i]) : to_string(nums[i]) + "->" + to_string(nums[j - 1])); 8 | } 9 | return res; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /C++/231. Power of Two.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfTwo(int n) { 4 | return n > 0 && !(n & (n - 1)); 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /C++/238. Product of Array Except Self.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector productExceptSelf(vector& nums) { 4 | vectorres(nums.size(), 1); 5 | for(int i = 1; i < nums.size(); i++) 6 | res[i] = res[i-1] * nums[i-1]; 7 | int right = 1; 8 | for(int i = nums.size() - 1; i >= 0; i--){ 9 | res[i] *= right; 10 | right *= nums[i]; 11 | } 12 | return res; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /C++/239. Sliding Window Maximum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector maxSlidingWindow(vector& nums, int k) { 4 | vectorres; 5 | if (nums.size() == 0) return res; 6 | int start = 0; 7 | int end = k - 1; 8 | int maxIndex = findMax(nums, start, end); 9 | for (; end < nums.size(); start++, end++) { 10 | if (nums[end] > nums[maxIndex]) maxIndex = end; 11 | if (start > maxIndex) maxIndex = findMax(nums, start, end); 12 | res.push_back(nums[maxIndex]); 13 | } 14 | return res; 15 | } 16 | 17 | int findMax(vector& nums, int start, int end) { 18 | int maxIndex = start; 19 | for (int i = start + 1; i <= end; i++) 20 | if (nums[i] > nums[maxIndex]) maxIndex = i; 21 | return maxIndex; 22 | } 23 | }; -------------------------------------------------------------------------------- /C++/244. Shortest Word Distance II.cpp: -------------------------------------------------------------------------------- 1 | class WordDistance { 2 | public: 3 | WordDistance(vector words) { 4 | for(int i = 0; i < words.size(); i++) m[words[i]].push_back(i); 5 | } 6 | 7 | int shortest(string word1, string word2) { 8 | auto v1 = m[word1]; 9 | auto v2 = m[word2]; 10 | int res = INT_MAX; 11 | while(!v1.empty() && !v2.empty()){ 12 | res = min(res, abs(v1.back() - v2.back())); 13 | v1.back() > v2.back() ? v1.pop_back() : v2.pop_back(); 14 | } 15 | return res; 16 | } 17 | 18 | private: 19 | unordered_map>m; 20 | }; 21 | -------------------------------------------------------------------------------- /C++/246. Strobogrammatic Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isStrobogrammatic(string num) { 4 | unordered_mapm{{'6', '9'}, {'9', '6'}, {'1', '1'}, {'0', '0'}, {'8', '8'}}; 5 | string s = ""; 6 | for(auto x: num) 7 | if(!m.count(x)) return false; 8 | else s.push_back(m[x]); 9 | reverse(s.begin(), s.end()); 10 | return s == num; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /C++/247. Strobogrammatic Number II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findStrobogrammatic(int n) { 4 | return helper(n, n); 5 | } 6 | 7 | vector helper(int m, int n){ 8 | if(m == 0) return {""}; 9 | if(m == 1) return {"0", "1", "8"}; 10 | vectorv = helper(m - 2, n); 11 | vectorres; 12 | for(auto x: v){ 13 | if(m != n) res.push_back('0' + x + '0'); 14 | res.push_back('6' + x + '9'); 15 | res.push_back('9' + x + '6'); 16 | res.push_back('1' + x + '1'); 17 | res.push_back('8' + x + '8'); 18 | } 19 | return res; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /C++/251. Flatten 2D Vector.cpp: -------------------------------------------------------------------------------- 1 | class Vector2D { 2 | public: 3 | Vector2D(vector>& vec2d) { 4 | for(int i = 0; i < vec2d.size(); i++) q.push_back(vec2d[i].begin()), end.push_back(vec2d[i].end()); 5 | } 6 | 7 | int next() { 8 | return *q.front()++;; 9 | } 10 | 11 | bool hasNext() { 12 | while(!q.empty() && (q.front() == end.front())) q.pop_front(), end.pop_front(); 13 | return !q.empty(); 14 | } 15 | 16 | private: 17 | deque::iterator>q; 18 | deque::iterator>end; 19 | }; 20 | -------------------------------------------------------------------------------- /C++/252. Meeting Rooms.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for an interval. 3 | * struct Interval { 4 | * int start; 5 | * int end; 6 | * Interval() : start(0), end(0) {} 7 | * Interval(int s, int e) : start(s), end(e) {} 8 | * }; 9 | */ 10 | // Solution 1. 11 | class Solution { 12 | public: 13 | bool canAttendMeetings(vector& intervals) { 14 | if(intervals.empty()) return true; 15 | sort(intervals.begin(), intervals.end(),[](Interval& a,Interval& b){ return a.start < b.start; }); 16 | for(int i = 0; i < intervals.size() - 1; i++) if(intervals[i].end > intervals[i + 1].start) return false; 17 | return true; 18 | } 19 | }; 20 | 21 | // Solution 2. 22 | class Solution { 23 | public: 24 | bool canAttendMeetings(vector& intervals) { 25 | mapm; 26 | for(auto x: intervals) m[x.start]++, m[x.end]--; 27 | int sum = 0; 28 | for(auto x: m) if((sum += x.second) > 1) return false; 29 | return true; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /C++/255. Verify Preorder Sequence in Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool verifyPreorder(vector& preorder) { 4 | return dfs(preorder, 0, preorder.size(), INT_MIN, INT_MAX); 5 | } 6 | 7 | bool dfs(vector& preorder, int l, int r, int minVal, int maxVal){ 8 | if(l >= r) return true; 9 | int root = preorder[l], mid = r; 10 | for(int i = l; i < r; i++) 11 | if(preorder[i] < minVal || preorder[i] > maxVal) return false; 12 | else if(preorder[i] > root && mid == r) mid = i; 13 | return dfs(preorder, l + 1, mid, minVal, root) && dfs(preorder, mid, r, root, maxVal); 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /C++/258. Add Digits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int addDigits(int num) { 4 | return num%9 ? num%9 : num ? 9 : 0; 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /C++/259. 3Sum Smaller.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int threeSumSmaller(vector& nums, int target) { 4 | int count = 0; 5 | sort(nums.begin(), nums.end()); 6 | for(int i = 0; i < nums.size(); i++) 7 | for(int lo = i + 1, hi = nums.size() - 1; lo < hi; count += hi - lo++) 8 | while(lo < hi && nums[i] + nums[lo] + nums[hi] >= target) hi--; 9 | return count; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /C++/263. Ugly Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isUgly(int num) { 4 | return num ? !(num%2) ? isUgly(num/2) : !(num%3) ? isUgly(num/3) : !(num%5) ? isUgly(num/5) : num == 1 : false; 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /C++/264. Ugly Number II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int nthUglyNumber(int n) { 4 | vectordp(n); 5 | dp[0] = 1; 6 | int p2 = 0, p3 = 0, p5 = 0; 7 | for(int i = 1; i < n; i++){ 8 | dp[i] = min(dp[p2] * 2, min(dp[p3] * 3, dp[p5] * 5)); 9 | if(dp[i] == dp[p2] * 2) p2++; 10 | if(dp[i] == dp[p3] * 3) p3++; 11 | if(dp[i] == dp[p5] * 5) p5++; 12 | } 13 | return dp[n - 1]; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /C++/266. Palindrome Permutation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canPermutePalindrome(string s) { 4 | unordered_mapm; 5 | int odd = 0; 6 | for(auto c: s) (m[c]++ % 2) ? odd-- : odd++; 7 | return odd <= 1; 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /C++/268. Missing Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int missingNumber(vector& nums) { 4 | int res = 0, i = 0; 5 | for(auto& x: nums) res ^= ++i ^ x; 6 | return res; 7 | } 8 | }; 9 | 10 | class Solution { 11 | public: 12 | int missingNumber(vector& nums) { 13 | int sum = 0, n = nums.size(); 14 | for (int& x: nums) { 15 | sum += x; 16 | } 17 | return (1 + n) * n/2 - sum; 18 | } 19 | }; 20 | 21 | class Solution { 22 | public: 23 | int missingNumber(vector& nums) { 24 | sort(nums.begin(), nums.end()); 25 | int l = 0, r = nums.size() - 1, mid; 26 | while (l <= r) { 27 | mid = l + (r - l)/2; 28 | if (nums[mid] > mid) { 29 | r = mid - 1; 30 | } else { 31 | l = mid + 1; 32 | } 33 | } 34 | return l; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /C++/270. Closest Binary Search Tree Value.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int closestValue(TreeNode* root, double target) { 4 | double minDiff = abs(root->val - target); 5 | int res = root->val; 6 | DFS(root, target, res, minDiff); 7 | return res; 8 | } 9 | 10 | void DFS(TreeNode* root, double target, int& res, double& minDiff){ 11 | if(!root) return; 12 | if(abs(root->val - target) < minDiff) minDiff = abs(root->val - target), res = root->val; 13 | target > root->val ? DFS(root->right, target, res, minDiff) : DFS(root->left, target, res, minDiff); 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /C++/271. Encode and Decode Strings.cpp: -------------------------------------------------------------------------------- 1 | class Codec { 2 | public: 3 | 4 | // Encodes a list of strings to a single string. 5 | string encode(vector& strs) { 6 | string res = ""; 7 | for(auto s: strs) 8 | res += to_string(s.size()) + '#' + s; 9 | return res; 10 | } 11 | 12 | // Decodes a single string to a list of strings. 13 | vector decode(string s) { 14 | vectorres; 15 | for(int i = 0; i < s.size();){ 16 | int j = i; 17 | while(isdigit(s[j])) j++; 18 | int len = stoi(s.substr(i, j - i)); 19 | res.push_back(s.substr(j + 1, len)); 20 | i = j + len + 1; 21 | } 22 | return res; 23 | } 24 | }; 25 | 26 | // Your Codec object will be instantiated and called as such: 27 | // Codec codec; 28 | // codec.decode(codec.encode(strs)); 29 | -------------------------------------------------------------------------------- /C++/272. Closest Binary Search Tree Value II.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | vector closestKValues(TreeNode* root, double target, int k) { 13 | vectorres; 14 | priority_queue>pq; 15 | DFS(root, target, k, pq); 16 | while(!pq.empty()) res.push_back(pq.top().second), pq.pop(); 17 | return res; 18 | } 19 | 20 | void DFS(TreeNode* root, double target, int k, priority_queue>& pq){ 21 | if(!root) return; 22 | pq.push({abs(root->val - target), root->val}); 23 | if(pq.size() > k) pq.pop(); 24 | DFS(root->left, target, k, pq); 25 | DFS(root->right, target, k, pq); 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /C++/274. H-Index.cpp: -------------------------------------------------------------------------------- 1 | // Solution 1. 2 | class Solution { 3 | public: 4 | int hIndex(vector& citations) { 5 | sort(citations.begin(), citations.end()); 6 | int i = 0, j = citations.size() - 1; 7 | while(j >= 0 && citations[j] > i) i++, j--; 8 | return i; 9 | } 10 | }; 11 | 12 | // Solution 2. 13 | class Solution { 14 | public: 15 | int hIndex(vector& citations) { 16 | int n = citations.size(); 17 | vectorbuckets(n + 1); 18 | for(auto x: citations) x >= n ? buckets[n]++ : buckets[x]++; 19 | int count = 0; 20 | for(int i = n; i >= 0; i--){ 21 | count += buckets[i]; 22 | if(count >= i) return i; 23 | } 24 | return 0; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /C++/275. H-Index II.cpp: -------------------------------------------------------------------------------- 1 | // O(n) 2 | class Solution { 3 | public: 4 | int hIndex(vector& citations) { 5 | int i = 0, j = citations.size() - 1; 6 | while(j >= 0 && citations[j] > i) i++, j--; 7 | return i; 8 | } 9 | }; 10 | 11 | // Binary Search, O(logn) 12 | class Solution { 13 | public: 14 | int hIndex(vector& citations) { 15 | int lo = 0, len = citations.size(), hi = len - 1; 16 | int mid = lo + (hi - lo) / 2; 17 | while(lo <= hi){ 18 | if(citations[mid] >= len - mid) hi = mid - 1; 19 | else lo = mid + 1; 20 | mid = lo + (hi - lo) / 2; 21 | } 22 | return len - lo; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /C++/276. Paint Fence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numWays(int n, int k) { 4 | vectordp(n + 1); 5 | dp[0] = 0, dp[1] = k, dp[2] = k * k; 6 | for(int i = 3; i <= n; i++) dp[i] = (dp[i - 2] + dp[i - 1]) * (k - 1); 7 | return dp[n]; 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /C++/277. Find the Celebrity.cpp: -------------------------------------------------------------------------------- 1 | // Forward declaration of the knows API. 2 | bool knows(int a, int b); 3 | 4 | class Solution { 5 | public: 6 | int findCelebrity(int n) { 7 | int i = 0, j = 1; 8 | while(j < n){ 9 | if(knows(i, j)) i = j; 10 | j++; 11 | } 12 | for(int k = 0; k < n; k++){ 13 | if(k == i) continue; 14 | if(!knows(k, i) || knows(i, k)){ 15 | i = -1; 16 | break; 17 | } 18 | } 19 | return i; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /C++/278. First Bad Version.cpp: -------------------------------------------------------------------------------- 1 | // Forward declaration of isBadVersion API. 2 | bool isBadVersion(int version); 3 | 4 | class Solution { 5 | public: 6 | int firstBadVersion(int n) { 7 | int lower = 1, upper = n; 8 | while(lower < upper) 9 | if(isBadVersion(lower + (upper - lower)/2)) upper = lower + (upper - lower)/2; 10 | else lower = lower + (upper - lower)/2 + 1; 11 | return lower; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /C++/279. Perfect Squares.cpp: -------------------------------------------------------------------------------- 1 | // Non-static DP, 89ms. 2 | class Solution { 3 | public: 4 | int numSquares(int n) { 5 | vectordp(n + 1, INT_MAX); 6 | dp[0] = 0; 7 | for(int i = 1; i <= n; i++) 8 | for(int j = 1; j * j <= i; j++) 9 | dp[i] = min(dp[i], dp[i - j * j] + 1); 10 | return dp[n]; 11 | } 12 | }; 13 | 14 | // Static DP, 6ms. 15 | class Solution { 16 | public: 17 | int numSquares(int n) { 18 | static vectordp(1, 0); 19 | for(int i = dp.size(); i <= n; i++){ 20 | dp.push_back(INT_MAX); 21 | for(int j = 1; j * j <= i; j++) 22 | dp[i] = min(dp[i], dp[i - j * j] + 1); 23 | } 24 | return dp[n]; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /C++/280. Wiggle Sort.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void wiggleSort(vector& nums) { 4 | for(int i = 1; i < nums.size(); i++) 5 | if(i % 2 && nums[i - 1] > nums[i] || !(i % 2) && nums[i - 1] < nums[i]) swap(nums[i], nums[i - 1]); 6 | } 7 | }; 8 | -------------------------------------------------------------------------------- /C++/283. Move Zeroes.cpp: -------------------------------------------------------------------------------- 1 | // One line. 2 | class Solution { 3 | public: 4 | void moveZeroes(vector& nums) { 5 | for(int i = 0, j = 0; j < nums.size(); j++) if(nums[j] != 0) swap(nums[i++], nums[j]); 6 | } 7 | }; 8 | 9 | // Three lines. 10 | class Solution { 11 | public: 12 | void moveZeroes(vector& nums) { 13 | int j = 0; 14 | for(auto x: nums) if(x) nums[j++] = x; 15 | while(j < nums.size()) nums[j++] = 0; 16 | } 17 | }; 18 | 19 | // Without maintaining the relative order, min steps. 20 | class Solution { 21 | public: 22 | void moveZeroes(vector& nums) { 23 | int i = 0, j = nums.size() - 1; 24 | while(i < j){ 25 | while(i < j && nums[i] != 0) i++; 26 | while(i < j && nums[j] == 0) j--; 27 | swap(nums[i++], nums[j--]); 28 | } 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /C++/290. Word Pattern.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool wordPattern(string pattern, string str) { 4 | unordered_mapc2s; 5 | unordered_maps2c; 6 | stringstream ss(str); 7 | string s = ""; 8 | int i = 0; 9 | while(ss>>s){ 10 | if(i == pattern.size() || c2s.count(pattern[i]) && c2s[pattern[i]] != s || s2c.count(s) && s2c[s] != pattern[i]) return false; 11 | c2s[pattern[i]] = s; 12 | s2c[s] = pattern[i++]; 13 | } 14 | return i == pattern.size(); 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /C++/293. Flip Game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector generatePossibleNextMoves(string s) { 4 | vectorres; 5 | for(int i = 1; i < s.size(); i++) 6 | if(s[i - 1] == '+' && s[i] == '+'){ 7 | res.push_back(s); 8 | res.back()[i - 1] = '-'; 9 | res.back()[i] = '-'; 10 | } 11 | return res; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /C++/294. Flip Game II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canWin(string s) { 4 | for(int i = 1; i < s.size(); i++) 5 | if(s[i - 1] == '+' && s[i] == '+'){ 6 | s[i - 1] = s[i] = '-'; 7 | if(!canWin(s)) return true; 8 | s[i - 1] = s[i] = '+'; 9 | } 10 | return false; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /C++/295. Find Median from Data Stream.cpp: -------------------------------------------------------------------------------- 1 | class MedianFinder { 2 | public: 3 | /** initialize your data structure here. */ 4 | MedianFinder() {} 5 | 6 | void addNum(int num) { 7 | (left.empty() || num <= left.top()) ? left.push(num) : right.push(num); 8 | if(left.size() > right.size() + 1){ 9 | right.push(left.top()); 10 | left.pop(); 11 | } 12 | if(right.size() > left.size()){ 13 | left.push(right.top()); 14 | right.pop(); 15 | } 16 | } 17 | 18 | double findMedian() { 19 | return left.size() > right.size()? left.top() : (left.top() + right.top()) / 2.0; 20 | } 21 | 22 | private: 23 | priority_queueleft; 24 | priority_queue, greater>right; 25 | }; 26 | 27 | /** 28 | * Your MedianFinder object will be instantiated and called as such: 29 | * MedianFinder obj = new MedianFinder(); 30 | * obj.addNum(num); 31 | * double param_2 = obj.findMedian(); 32 | */ 33 | -------------------------------------------------------------------------------- /C++/300. Longest Increasing Subsequence.cpp: -------------------------------------------------------------------------------- 1 | // Solution 1. DP, O(n^2). 2 | class Solution { 3 | public: 4 | int lengthOfLIS(vector& nums) { 5 | int maxlen = 0; 6 | vectordp(nums.size(), 1); 7 | for(int i = 0; i < nums.size(); i++){ 8 | for(int j = 0; j < i; j++) 9 | if(nums[j] < nums[i]) dp[i] = max(dp[i], dp[j] + 1); 10 | maxlen = max(maxlen, dp[i]); 11 | } 12 | return maxlen; 13 | } 14 | }; 15 | 16 | // Solution 2. Binary search, O(nlogn). 17 | class Solution { 18 | public: 19 | int lengthOfLIS(vector& nums) { 20 | vectordp; 21 | for(int x: nums){ 22 | int pos = lower_bound(dp.begin(), dp.end(), x) - dp.begin(); 23 | if(pos == dp.size()) dp.push_back(x); 24 | else dp[pos] = x; 25 | } 26 | return dp.size(); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /C++/303. Range Sum Query - Immutable.cpp: -------------------------------------------------------------------------------- 1 | class NumArray { 2 | public: 3 | NumArray(vector nums) { 4 | int sum = 0; 5 | for(auto x: nums){ 6 | sum += x; 7 | dp.push_back(sum); 8 | } 9 | } 10 | 11 | int sumRange(int i, int j) { 12 | return i == 0 ? dp[j] : dp[j] - dp[i - 1]; 13 | } 14 | 15 | private: 16 | vectordp; 17 | }; 18 | -------------------------------------------------------------------------------- /C++/325. Maximum Size Subarray Sum Equals k.cpp: -------------------------------------------------------------------------------- 1 | // Brute Force, O(n^2). 2 | class Solution { 3 | public: 4 | int maxSubArrayLen(vector& nums, int k) { 5 | int len = 0; 6 | for(int i = 0; i < nums.size(); i++){ 7 | int sum = 0; 8 | for(int j = i; j < nums.size(); j++){ 9 | sum += nums[j]; 10 | if(sum == k) len = max(len, j - i + 1); 11 | } 12 | } 13 | return len; 14 | } 15 | }; 16 | 17 | // O(n). 18 | class Solution { 19 | public: 20 | int maxSubArrayLen(vector& nums, int k) { 21 | unordered_mapm; 22 | int sum = 0; 23 | int maxlen = 0; 24 | for(int i = 0; i < nums.size(); i++){ 25 | sum += nums[i]; 26 | if(!m.count(sum)) m[sum] = i; 27 | if(sum == k) maxlen = i + 1; 28 | else if(m.count(sum - k) > 0) maxlen = max(maxlen, i - m[sum - k]); 29 | } 30 | return maxlen; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /C++/331. Verify Preorder Serialization of a Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isValidSerialization(string preorder) { 4 | if(preorder == "#") return true; 5 | stringstream ss(preorder); 6 | stackstk; 7 | string s = ""; 8 | while(getline(ss, s, ',')){ 9 | if(s == "#" && stk.empty()) return false; 10 | if(!stk.empty()) stk.top()++; 11 | if(!stk.empty() && stk.top() == 2) stk.pop(); 12 | if(s != "#") stk.push(0); 13 | if(stk.empty() && !ss.eof()) return false; 14 | } 15 | return stk.empty(); 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /C++/332. Reconstruct Itinerary.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findItinerary(vector> tickets) { 4 | unordered_map, greater>>m; 5 | vectorres; 6 | for(auto x: tickets) m[x.first].push(x.second); 7 | DFS("JFK", res, m); 8 | reverse(res.begin(), res.end()); 9 | return res; 10 | } 11 | 12 | void DFS(string cur, vector& res, unordered_map, greater>>& m){ 13 | while(!m[cur].empty()){ 14 | string s = m[cur].top(); 15 | m[cur].pop(); 16 | DFS(s, res, m); 17 | } 18 | res.push_back(cur); 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /C++/333. Largest BST Subtree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | int largestBSTSubtree(TreeNode* root) { 13 | int res = 0; 14 | dfs(root, res); 15 | return res; 16 | } 17 | 18 | vector dfs(TreeNode* root, int& res){ 19 | if(!root) return {INT_MAX, INT_MIN, 0}; 20 | auto l = dfs(root->left, res); 21 | auto r = dfs(root->right, res); 22 | int count = (l[2] == -1 || r[2] == -1 || l[1] >= root->val || r[0] <= root->val) ? -1 : l[2] + r[2] + 1; 23 | res = max(res, count); 24 | return {min(root->val, min(l[0], r[0])), max(root->val, max(l[1], r[1])), count}; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /C++/334. Increasing Triplet Subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool increasingTriplet(vector& nums) { 4 | int c1 = INT_MAX, c2 = INT_MAX; 5 | for(auto x: nums) 6 | if(x <= c1) c1 = x; 7 | else if(x <= c2) c2 = x; 8 | else return true; 9 | return false; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /C++/344. Reverse String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string reverseString(string s) { 4 | reverse(s.begin(), s.end()); 5 | return s; 6 | } 7 | }; -------------------------------------------------------------------------------- /C++/354. Russian Doll Envelopes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxEnvelopes(vector>& envelopes) { 4 | sort(envelopes.begin(), envelopes.end(), [](pair& p1, pair& p2){ 5 | return p1.first == p2.first ? p1.second > p2.second : p1.first < p2.first; 6 | }); 7 | vectordp; 8 | for(auto x: envelopes){ 9 | int pos = lower_bound(dp.begin(), dp.end(), x.second) - dp.begin(); 10 | if(pos == dp.size()) dp.push_back(x.second); 11 | else dp[pos] = x.second; 12 | } 13 | return dp.size(); 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /C++/355. Design Twitter.cpp: -------------------------------------------------------------------------------- 1 | class Twitter { 2 | private: 3 | vector>posts; 4 | unordered_map>follows; 5 | public: 6 | Twitter() {} 7 | 8 | void postTweet(int userId, int tweetId) { 9 | posts.push_back(make_pair(userId, tweetId)); 10 | } 11 | 12 | vector getNewsFeed(int userId) { 13 | vectorfeed; 14 | int count = 0; 15 | for(int i = posts.size() - 1; i >= 0 && count < 10; i--) 16 | if(posts[i].first == userId || follows[userId][posts[i].first]) 17 | feed.push_back(posts[i].second), count++; 18 | return feed; 19 | } 20 | 21 | void follow(int followerId, int followeeId) { 22 | follows[followerId][followeeId] = 1; 23 | } 24 | 25 | void unfollow(int followerId, int followeeId) { 26 | follows[followerId][followeeId] = 0; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /C++/359. Logger Rate Limiter.cpp: -------------------------------------------------------------------------------- 1 | class Logger { 2 | public: 3 | /** Initialize your data structure here. */ 4 | Logger() {} 5 | 6 | /** Returns true if the message should be printed in the given timestamp, otherwise returns false. 7 | If this method returns false, the message will not be printed. 8 | The timestamp is in seconds granularity. */ 9 | bool shouldPrintMessage(int timestamp, string message) { 10 | if (!m.count(message) || timestamp - m[message] >= 10) { 11 | m[message] = timestamp; 12 | return true; 13 | } else { 14 | return false; 15 | } 16 | } 17 | 18 | private: 19 | mapm; 20 | }; 21 | 22 | /** 23 | * Your Logger object will be instantiated and called as such: 24 | * Logger obj = new Logger(); 25 | * bool param_1 = obj.shouldPrintMessage(timestamp,message); 26 | */ 27 | -------------------------------------------------------------------------------- /C++/360. Sort Transformed Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector sortTransformedArray(vector& nums, int a, int b, int c) { 4 | vectorres; 5 | int i = 0, j = nums.size() - 1; 6 | while(i <= j){ 7 | int x = a * nums[i] * nums[i] + b * nums[i] + c; 8 | int y = a * nums[j] * nums[j] + b * nums[j] + c; 9 | if(a * x > a * y){ 10 | i++; 11 | res.push_back(x); 12 | } 13 | else{ 14 | j--; 15 | res.push_back(y); 16 | } 17 | } 18 | if(a > 0 || a == 0 && b > 0) reverse(res.begin(), res.end()); 19 | return res; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /C++/361. Bomb Enemy.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxKilledEnemies(vector>& grid) { 4 | int maxKill = 0; 5 | for(int i = 0; i < grid.size(); i++) 6 | for(int j = 0; j < grid[0].size(); j++) 7 | if(grid[i][j] == '0') maxKill = max(maxKill, getKills(grid, i, j)); 8 | return maxKill; 9 | } 10 | 11 | int getKills(vector>& grid, int r, int c){ 12 | int m = grid.size(), n = grid[0].size(), count = 0; 13 | int up = r - 1, down = r + 1, left = c - 1, right = c + 1; 14 | while(up >= 0 && grid[up][c] != 'W') if(grid[up--][c] == 'E') count++; 15 | while(down < m && grid[down][c] != 'W') if(grid[down++][c] == 'E') count++; 16 | while(left >= 0 && grid[r][left] != 'W') if(grid[r][left--] == 'E') count++; 17 | while(right < n && grid[r][right] != 'W') if(grid[r][right++] == 'E') count++; 18 | return count; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /C++/362. Design Hit Counter.cpp: -------------------------------------------------------------------------------- 1 | class HitCounter { 2 | private: 3 | dequeq; 4 | public: 5 | /** Initialize your data structure here. */ 6 | HitCounter() {} 7 | 8 | /** Record a hit. 9 | @param timestamp - The current timestamp (in seconds granularity). */ 10 | void hit(int timestamp) { 11 | q.push_back(timestamp); 12 | } 13 | 14 | /** Return the number of hits in the past 5 minutes. 15 | @param timestamp - The current timestamp (in seconds granularity). */ 16 | int getHits(int timestamp) { 17 | while(!q.empty() && q.front() <= timestamp - 300) q.pop_front(); 18 | return q.size(); 19 | } 20 | }; 21 | 22 | /** 23 | * Your HitCounter object will be instantiated and called as such: 24 | * HitCounter obj = new HitCounter(); 25 | * obj.hit(timestamp); 26 | * int param_2 = obj.getHits(timestamp); 27 | */ 28 | -------------------------------------------------------------------------------- /C++/369. Plus One Linked List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode* plusOne(ListNode* head) { 12 | ListNode* p = reverse(head); 13 | ListNode* tmp = p; 14 | while(p->val + 1 == 10){ 15 | p->val = 0; 16 | if(!p->next) p->next = new ListNode(0); 17 | p = p->next; 18 | } 19 | p->val += 1; 20 | return reverse(tmp); 21 | } 22 | 23 | ListNode* reverse(ListNode* head){ 24 | ListNode* pre = NULL, *cur = head, *next; 25 | while(cur){ 26 | next = cur->next; 27 | cur->next = pre; 28 | pre = cur; 29 | cur = next; 30 | } 31 | return pre; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /C++/377. Combination Sum IV.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | unordered_mapm; 4 | public: 5 | int combinationSum4(vector& nums, int target) { 6 | if(target == 0) return 1; 7 | if(m.count(target) > 0) return m[target]; 8 | int sum = 0; 9 | for(auto x: nums) 10 | if(target >= x) 11 | sum += combinationSum4(nums, target - x); 12 | m[target] = sum; 13 | return sum; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /C++/378. Kth Smallest Element in a Sorted Matrix.cpp: -------------------------------------------------------------------------------- 1 | // Solution 1. MinHeap 2 | class Solution { 3 | public: 4 | int kthSmallest(vector>& matrix, int k) { 5 | priority_queue, greater>pq; 6 | for(auto x: matrix) 7 | for(auto y: x) pq.push(y); 8 | while(--k) pq.pop(); 9 | return pq.top(); 10 | } 11 | }; 12 | 13 | // Solution 2. Multiset 14 | class Solution { 15 | public: 16 | int kthSmallest(vector>& matrix, int k) { 17 | multisets; 18 | for(auto x: matrix) 19 | for(auto y: x) s.insert(y); 20 | auto p = s.begin(); 21 | while(--k) p++; 22 | return *p; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /C++/394. Decode String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string decodeString(string s) { 4 | if(s.empty()) return ""; 5 | string res = ""; 6 | int i = 0, j = 0; 7 | while(j < s.size()){ 8 | while(j < s.size() && isalpha(s[j])) j++; 9 | res += s.substr(i, j - i); 10 | i = j; 11 | if(j == s.size()) break; 12 | while(isdigit(s[j])) j++; 13 | int k = stoi(s.substr(i, j - i)); 14 | int cnt = 1; 15 | i = j + 1; 16 | while(cnt != 0) 17 | if(s[++j] == ']') cnt--; 18 | else if(s[j] == '[') cnt++; 19 | while(k--) res += decodeString(s.substr(i, j - i)); 20 | i = ++j; 21 | } 22 | return res; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /C++/398. Random Pick Index.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | Solution(vector nums) { 4 | this->nums = nums; 5 | } 6 | 7 | int pick(int target) { 8 | int res = -1, count = 0; 9 | for(int i = 0; i < nums.size(); i++){ 10 | if(nums[i] != target) continue; 11 | if(res == -1) res = i, count++; 12 | else{ 13 | count++; 14 | if(rand() % count == 0) res = i; 15 | } 16 | } 17 | return res; 18 | } 19 | 20 | private: 21 | vectornums; 22 | }; 23 | 24 | /** 25 | * Your Solution object will be instantiated and called as such: 26 | * Solution obj = new Solution(nums); 27 | * int param_1 = obj.pick(target); 28 | */ 29 | -------------------------------------------------------------------------------- /C++/402. Remove K Digits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string removeKdigits(string num, int k) { 4 | int n = num.size(), remain = n - k; 5 | if(remain == 0) return "0"; 6 | string s = ""; 7 | for(auto x: num){ 8 | while(n > remain && !s.empty() && s.back() - '0' > x - '0'){ 9 | s.pop_back(); 10 | n--; 11 | } 12 | s.push_back(x); 13 | } 14 | int i = 0; 15 | while(i < s.size() && s[i] == '0') i++; 16 | return s.substr(i, remain) == "" ? "0" : s.substr(i, remain); 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /C++/408. Valid Word Abbreviation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool validWordAbbreviation(string word, string abbr) { 4 | int i = 0, j = 0; 5 | while(i < word.size() && j < abbr.size()) 6 | if(isdigit(abbr[j])){ 7 | if(abbr[j] == '0') return false; 8 | int k = j + 1; 9 | while(k < abbr.size() && isdigit(abbr[k])) k++; 10 | i += stoi(abbr.substr(j, k - j)); 11 | j = k; 12 | } 13 | else if(word[i++] != abbr[j++]) return false; 14 | return i == word.size() && j == abbr.size(); 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /C++/409. Longest Palindrome.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestPalindrome(string s) { 4 | int odd = 0; 5 | unordered_mapm; 6 | for(auto c: s) odd += m[c]++ % 2 ? -1 : 1; 7 | return min(s.size(), s.size() - odd + 1); 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /C++/412. Fizz Buzz.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector fizzBuzz(int n) { 4 | vectorres; 5 | for(int i = 1; i < n + 1; i++){ 6 | string s = to_string(i); 7 | if(i % 15 ==0) s = "FizzBuzz"; 8 | else if(i % 3 == 0) s = "Fizz"; 9 | else if(i % 5 == 0) s = "Buzz"; 10 | res.push_back(s); 11 | } 12 | return res; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /C++/416. Partition Equal Subset Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canPartition(vector& nums) { 4 | // dp[i][j] = dp[i - 1][j] || dp[i - 1][j - nums[i]] 5 | int sum = 0; 6 | for(auto x: nums) sum += x; 7 | if(sum % 2) return false; 8 | vector>dp(nums.size(), vector(sum / 2 + 1, false)); 9 | dp[0][0] = true; 10 | for(int i = 1; i < nums.size(); i++) 11 | for(int j = 0; j < sum / 2 + 1; j++) 12 | dp[i][j] = dp[i - 1][j] || ((j >= nums[i]) ? dp[i - 1][j - nums[i]] : 0); 13 | return dp[nums.size() - 1][sum / 2]; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /C++/418. Sentence Screen Fitting.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int wordsTyping(vector& sentence, int rows, int cols) { 4 | int count = 0, n = sentence.size(), idx = 0; 5 | for (int i = 0; i < rows; ++i) { 6 | int slot = cols; 7 | while (slot > 0 && slot >= sentence[idx].size()) { 8 | slot -= sentence[idx].size() + 1; 9 | ++idx; 10 | if (idx == n) { 11 | ++count; 12 | idx = 0; 13 | } 14 | } 15 | } 16 | return count; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /C++/433. Minimum Genetic Mutation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minMutation(string start, string end, vector& bank) { 4 | int step = 1; 5 | dequecur; 6 | dequenext; 7 | cur.push_back(start); 8 | while(!cur.empty()){ 9 | string node = cur.front(); 10 | cur.pop_front(); 11 | for(auto& s: bank){ 12 | if(s == "" || !isNeighbor(node, s)) continue; 13 | if(s == end) return step; 14 | next.push_back(s); 15 | s = ""; 16 | } 17 | if(cur.empty()){ 18 | step++; 19 | swap(cur, next); 20 | } 21 | } 22 | return -1; 23 | } 24 | 25 | bool isNeighbor(const string& a, const string& b){ 26 | int diff = 0; 27 | for(int i = 0; i < a.size(); i++) if(a[i] != b[i] && ++diff > 1) return false; 28 | return diff == 1; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /C++/435. Non-overlapping Intervals.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for an interval. 3 | * struct Interval { 4 | * int start; 5 | * int end; 6 | * Interval() : start(0), end(0) {} 7 | * Interval(int s, int e) : start(s), end(e) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | int eraseOverlapIntervals(vector& intervals) { 13 | sort(intervals.begin(), intervals.end(), [](Interval& a, Interval& b){ return a.start < b.start; }); 14 | int count = 0; 15 | for(int i = 1, j = 0; i < intervals.size(); i++){ 16 | int pre = i; 17 | if(intervals[i].start < intervals[j].end){ 18 | count++; 19 | if(intervals[i].end > intervals[j].end) pre = j; 20 | } 21 | j = pre; 22 | } 23 | return count; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /C++/436. Find Right Interval.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for an interval. 3 | * struct Interval { 4 | * int start; 5 | * int end; 6 | * Interval() : start(0), end(0) {} 7 | * Interval(int s, int e) : start(s), end(e) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | vector findRightInterval(vector& intervals) { 13 | vectorres; 14 | mapm; 15 | for(int i = 0; i < intervals.size(); i++) m[intervals[i].start] = i; 16 | for(auto i: intervals){ 17 | auto p = m.lower_bound(i.end); 18 | res.push_back(p == m.end() ? -1 : (*p).second); 19 | } 20 | return res; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /C++/438. Find All Anagrams in a String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findAnagrams(string s, string p) { 4 | vectorres; 5 | unordered_mapm; 6 | for(auto c: p) m[c]++; 7 | int i = 0, j = 0, count = p.size(); 8 | while(j < s.size()){ 9 | if(m[s[j++]]-- > 0) count--; 10 | while(count == 0){ 11 | if(j - i == p.size()) res.push_back(i); 12 | if(m[s[i++]]++ == 0) count++; 13 | } 14 | } 15 | return res; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /C++/441. Arranging Coins.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int arrangeCoins(int n) { 4 | int i = 1; 5 | while(n >= i) n -= i, i++; 6 | return i - 1; 7 | } 8 | }; 9 | 10 | // Math solution from this thread https://discuss.leetcode.com/topic/65655/c-1-line-code 11 | class Solution { 12 | public: 13 | int arrangeCoins(int n) { 14 | return floor(-0.5+sqrt((double)2*n+0.25)); 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /C++/444. Sequence Reconstruction.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool sequenceReconstruction(vector& org, vector>& seqs) { 4 | int n = org.size(); 5 | unordered_map>graph; 6 | vectorindegree(n + 1, -1); 7 | for(auto v: seqs) 8 | for(int i = 0; i < v.size(); i++){ 9 | if(v[i] > n || v[i] < 0) return false; 10 | if(indegree[v[i]] == -1) indegree[v[i]] = 0; 11 | if(i + 1 < v.size() && graph[v[i]].insert(v[i + 1]).second) 12 | if(v[i + 1] > n || v[i + 1] < 0) return false; 13 | else indegree[v[i + 1]] += indegree[v[i + 1]] < 0 ? 2 : 1; 14 | } 15 | for(int i = 0; i < n - 1; i++) 16 | if(indegree[org[i]] || !indegree[org[i + 1]]) return false; 17 | else for(auto x: graph[org[i]]) indegree[x]--; 18 | return indegree[org.back()] == 0; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /C++/451. Sort Characters By Frequency.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string frequencySort(string s) { 4 | string res = ""; 5 | unordered_mapm; 6 | for(auto c: s) m[c]++; 7 | auto comp = [](pair& a, pair& b){ return a.first < b.first; }; 8 | priority_queue, vector>, decltype(comp)>pq(comp); 9 | for(auto x: m) pq.push({x.second, x.first}); 10 | while(!pq.empty()){ 11 | auto p = pq.top(); 12 | pq.pop(); 13 | while(p.first--) res += p.second; 14 | } 15 | return res; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /C++/461. Hamming Distance.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int hammingDistance(int x, int y) { 4 | int n = x^y; 5 | int d = 0; 6 | while(n) n &= n-1, d++; 7 | return d; 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /C++/467. Unique Substrings in Wraparound String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findSubstringInWraproundString(string p) { 4 | vectordp(26); 5 | int len = 0; 6 | for(int i = 0; i < p.size(); i++){ 7 | len = (i > 0 && (p[i] - p[i - 1] == 1 || p[i] - p[i - 1] == -25)) ? len + 1 : 1; 8 | dp[p[i] - 'a'] = max(dp[p[i] - 'a'], len); 9 | } 10 | int sum = 0; 11 | for(int x: dp) sum += x; 12 | return sum; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /C++/477. Total Hamming Distance.cpp: -------------------------------------------------------------------------------- 1 | // O(n) 2 | class Solution { 3 | public: 4 | int totalHammingDistance(vector& nums) { 5 | int distance = 0; 6 | for(int i = 0; i < 32; i++){ 7 | int one = 0, zero = 0; 8 | for(auto x: nums) (x & (1 << i)) ? one++ : zero++; 9 | distance += one * zero; 10 | } 11 | return distance; 12 | } 13 | }; 14 | 15 | // Brute Force, O(n^2), TLE 16 | /* 17 | class Solution { 18 | public: 19 | int totalHammingDistance(vector& nums) { 20 | int distance = 0; 21 | for(int i = 0; i < nums.size(); i++) 22 | for(int j = i + 1; j < nums.size(); j++) 23 | distance += helper(nums[i] ^ nums[j]); 24 | return distance; 25 | } 26 | 27 | int helper(int c){ 28 | int sum = 0; 29 | while(c){ 30 | sum++; 31 | c &= c - 1; 32 | } 33 | return sum; 34 | } 35 | }; 36 | */ 37 | -------------------------------------------------------------------------------- /C++/482. License Key Formatting.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string licenseKeyFormatting(string S, int K) { 4 | stringstream ss(S); 5 | string s = "", tmp = "", res = ""; 6 | while(getline(ss, tmp, '-')) s += tmp; 7 | for(auto& c: s) c = toupper(c); 8 | int i = 0, step = (s.size() % K == 0) ? K : s.size() % K; 9 | while(i < s.size()){ 10 | res += s.substr(i, step) + '-'; 11 | i += step; 12 | step = K; 13 | } 14 | res.pop_back(); 15 | return res; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /C++/484. Find Permutation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findPermutation(string s) { 4 | vectorres; 5 | for(int i = 1; i <= s.size() + 1; i++) res.push_back(i); 6 | for(int i = 0; i < s.size(); i++){ 7 | int j = i; 8 | while(j < s.size() && s[j] == 'D') j++; 9 | reverse(res.begin() + i, res.begin() + j + 1); 10 | i = j; 11 | } 12 | return res; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /C++/487. Max Consecutive Ones II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMaxConsecutiveOnes(vector& nums) { 4 | int res = 0, l = 0, r = 0, count = 0; 5 | while(r < nums.size()){ 6 | if(nums[r++] == 0) count++; 7 | while(count > 1) if(nums[l++] == 0) count--; 8 | res = max(res, r - l); 9 | } 10 | return res; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /C++/496. Next Greater Element I.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector nextGreaterElement(vector& findNums, vector& nums) { 4 | unordered_mapm; 5 | stacks; 6 | for(auto x: nums){ 7 | while(!s.empty() && s.top() < x){ 8 | m[s.top()] = x; 9 | s.pop(); 10 | } 11 | s.push(x); 12 | } 13 | for(auto& x: findNums) x = m.count(x) ? m[x] : -1; 14 | return findNums; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /C++/498. Diagonal Traverse.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findDiagonalOrder(vector>& matrix) { 4 | vectorres; 5 | if(matrix.empty()) return res; 6 | int m = matrix.size(), n = matrix[0].size(); 7 | vector>dir({{-1, 1}, {1, -1}}); 8 | DFS(matrix, res, 0, 0, m, n, dir, 0); 9 | return res; 10 | } 11 | 12 | void DFS(vector>& matrix, vector& res, int r, int c, int m, int n, vector>& dir, int d){ 13 | if(res.size() == m * n) return; 14 | res.push_back(matrix[r][c]); 15 | int R = r + dir[d].first; 16 | int C = c + dir[d].second; 17 | if(R < 0 || C < 0 || R >= m || C >= n){ 18 | d = (d + 1) % 2; 19 | if(R < 0 || R >= m) R = r, C = c + 1; 20 | if(C < 0 || C >= n) R = r + 1, C = c; 21 | } 22 | DFS(matrix, res, R, C, m, n, dir, d); 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /C++/508. Most Frequent Subtree Sum.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | vector findFrequentTreeSum(TreeNode* root) { 13 | vectorres; 14 | unordered_mapm; 15 | DFS(root, m); 16 | int maxFreq = 0; 17 | for(auto x: m) 18 | if(x.second > maxFreq) res.clear(), res.push_back(x.first), maxFreq = x.second; 19 | else if(x.second == maxFreq) res.push_back(x.first); 20 | return res; 21 | } 22 | 23 | int DFS(TreeNode* root, unordered_map& m){ 24 | if(!root) return 0; 25 | int l = DFS(root->left, m); 26 | int r = DFS(root->right, m); 27 | int sum = root->val + l + r; 28 | m[sum]++; 29 | return sum; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /C++/513. Find Bottom Left Tree Value.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | int findBottomLeftValue(TreeNode* root) { 13 | int res = 0, maxLevel = -1; 14 | DFS(root, 0, maxLevel, res); 15 | return res; 16 | } 17 | 18 | void DFS(TreeNode* root, int level, int& maxLevel, int& res){ 19 | if(!root) return; 20 | DFS(root->left, level + 1, maxLevel, res); 21 | DFS(root->right, level + 1, maxLevel, res); 22 | if(level > maxLevel) res = root->val; 23 | maxLevel = max(maxLevel, level); 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /C++/523. Continuous Subarray Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkSubarraySum(vector& nums, int k) { 4 | unordered_mapm; 5 | k = abs(k); 6 | int sum = 0; 7 | for(int i = 0; i < nums.size(); i++){ 8 | sum += nums[i]; 9 | if(i < nums.size() - 1 && nums[i] == 0 && nums[i + 1] == 0) return true; 10 | if(k != 0 && sum % k == 0 && i > 0) return true; 11 | for(int j = 0; k != 0 && j*k < sum; j++) 12 | if(m.count(sum - j*k) > 0 && i - m[sum - j*k] > 0) return true; 13 | m[sum] = i; 14 | } 15 | return false; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /C++/524. Longest Word in Dictionary through Deleting.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string findLongestWord(string s, vector& d) { 4 | vectorp(d.size()); 5 | int maxlen = 0; 6 | string res = ""; 7 | for(auto c: s) 8 | for(int i = 0; i < d.size(); i++){ 9 | if(p[i] == d[i].size()) continue; 10 | if(c == d[i][p[i]]) p[i]++; 11 | } 12 | for(int i = 0; i < p.size(); i++){ 13 | if(p[i] != d[i].size()) continue; 14 | if(p[i] == maxlen && d[i].compare(res) < 0) res = d[i]; 15 | if(p[i] > maxlen){ 16 | maxlen = p[i]; 17 | res = d[i]; 18 | } 19 | } 20 | return res; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /C++/525. Contiguous Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMaxLength(vector& nums) { 4 | for(auto& x: nums) if(!x) x = -1; 5 | unordered_mapm; 6 | m[0] = -1; 7 | int sum = 0, maxlen = 0; 8 | for(int i = 0; i < nums.size(); i++){ 9 | sum += nums[i]; 10 | if(m.count(sum)) maxlen = max(maxlen, i - m[sum]); 11 | else m[sum] = i; 12 | } 13 | return maxlen; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /C++/531. Lonely Pixel I.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findLonelyPixel(vector>& picture) { 4 | if(picture.empty()) return 0; 5 | int m = picture.size(), n = picture[0].size(); 6 | int count = 0; 7 | for(int i = 0; i < m; i++){ 8 | bool B = true; 9 | for(int j = 0; j < n && B; j++){ 10 | if(picture[i][j] == 'B'){ 11 | B = false; 12 | int r = 0, c = j + 1; 13 | for(; r < m; r++) if(r != i && picture[r][j] == 'B') break; 14 | for(; c < n; c++) if(picture[i][c] == 'B') break; 15 | if(r == m && c == n) count++; 16 | } 17 | } 18 | } 19 | return count; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /C++/535. Encode and Decode TinyURL.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | // Encodes a URL to a shortened URL. 4 | string encode(string longUrl) { 5 | v.push_back(longUrl); 6 | return to_string(v.size() - 1); 7 | } 8 | 9 | // Decodes a shortened URL to its original URL. 10 | string decode(string shortUrl) { 11 | return v[stoi(shortUrl)]; 12 | } 13 | 14 | private: 15 | vectorv; 16 | }; 17 | 18 | // Your Solution object will be instantiated and called as such: 19 | // Solution solution; 20 | // solution.decode(solution.encode(url)); 21 | 22 | // Best answer (joke). 23 | class Solution { 24 | public: 25 | // Encodes a URL to a shortened URL. 26 | string encode(string longUrl) { 27 | return longUrl; 28 | } 29 | 30 | // Decodes a shortened URL to its original URL. 31 | string decode(string shortUrl) { 32 | return shortUrl; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /C++/536. Construct Binary Tree from String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* str2tree(string s) { 4 | if(s.empty()) return NULL; 5 | int i = 0; 6 | while(i < s.size() && (isdigit(s[i]) || s[i] == '-')) i++; 7 | TreeNode* root = new TreeNode(stoi(s.substr(0, i))); 8 | int j = i, k = 0; 9 | while(j < s.size()){ 10 | if(s[j] == '(') k++; 11 | else if(s[j] == ')') k--; 12 | if(k == 0){ 13 | if(!root->left) root->left = str2tree(s.substr(i + 1, j - i - 1)); 14 | else root->right = str2tree(s.substr(i + 1, j - i - 1)); 15 | i = j + 1; 16 | } 17 | j++; 18 | } 19 | return root; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /C++/538. Convert BST to Greater Tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* convertBST(TreeNode* root) { 4 | int sum = 0; 5 | DFS(root, sum); 6 | return root; 7 | } 8 | 9 | void DFS(TreeNode* root, int& sum){ 10 | if(!root) return; 11 | DFS(root->right, sum); 12 | sum = (root->val += sum); 13 | DFS(root->left, sum); 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /C++/540. Single Element in a Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int singleNonDuplicate(vector& nums) { 4 | int lo = 0, hi = nums.size() - 1; 5 | int mid = (lo + hi) / 2; 6 | while(lo < hi - 2){ 7 | if(nums[mid] == nums[mid + 1]) mid++; 8 | if((hi - mid) % 2) lo = mid + 1; 9 | else hi = mid; 10 | mid = (lo + hi) / 2; 11 | } 12 | return nums[lo] == nums[lo + 1] ? nums[hi] : nums[lo]; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /C++/541. Reverse String II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string reverseStr(string s, int k) { 4 | int n = s.size(); 5 | for(int i = 0; i < n; i += 2*k) 6 | reverse(s.begin() + i, s.begin() + min(i + k, n)); 7 | return s; 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /C++/543. Diameter of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int diameterOfBinaryTree(TreeNode* root) { 4 | if(!root) return 0; 5 | int left = DFS(root->left); 6 | int right = DFS(root->right); 7 | return max(left + right, max(diameterOfBinaryTree(root->left), diameterOfBinaryTree(root->right))); 8 | } 9 | 10 | int DFS(TreeNode* root){ 11 | if(!root) return 0; 12 | return 1 + max(DFS(root->left), DFS(root->right)); 13 | } 14 | }; 15 | 16 | // Update(08/28/2017): 17 | class Solution { 18 | public: 19 | int diameterOfBinaryTree(TreeNode* root) { 20 | int maxLen = 0; 21 | DFS(root, maxLen); 22 | return maxLen; 23 | } 24 | 25 | private: 26 | int DFS(TreeNode* root, int& maxLen){ 27 | if(!root) return 0; 28 | int left = DFS(root->left, maxLen); 29 | int right = DFS(root->right, maxLen); 30 | maxLen = max(maxLen, left + right); 31 | return max(left, right) + 1; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /C++/547. Friend Circles.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findCircleNum(vector>& M) { 4 | vectorTags(M.size()); 5 | int tag = 0; 6 | for(int i = 0; i < M.size(); i++){ 7 | if(Tags[i]) continue; 8 | Tags[i] = ++tag; 9 | for(int j = 0; j < M[0].size(); j++){ 10 | if(j == i || M[i][j] == 0) continue; 11 | if(M[i][j]){ 12 | M[i][j] = M[j][i] = 0; 13 | DFS(Tags, M, j, tag); 14 | } 15 | } 16 | } 17 | return tag; 18 | } 19 | 20 | void DFS(vector& Tags, vector>& M, int row, int tag){ 21 | Tags[row] = tag; 22 | for(int i = 0; i < M[row].size(); i++){ 23 | if(M[row][i]){ 24 | M[row][i] = M[i][row] = 0; 25 | DFS(Tags, M, i, tag); 26 | } 27 | } 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /C++/549. Binary Tree Longest Consecutive Sequence II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestConsecutive(TreeNode* root) { 4 | int maxlen = 0; 5 | DFS(root, maxlen); 6 | return maxlen; 7 | } 8 | 9 | pair DFS(TreeNode* root, int& maxlen){ 10 | if(!root) return {0, 0}; 11 | int iL = 1, dL = 1, iR = 1, dR = 1; 12 | auto l = DFS(root->left, maxlen); 13 | auto r = DFS(root->right, maxlen); 14 | if(root->left && root->left->val == root->val + 1) iL += l.first; 15 | if(root->left && root->left->val == root->val - 1) dL += l.second; 16 | if(root->right && root->right->val == root->val + 1) iR += r.first; 17 | if(root->right && root->right->val == root->val - 1) dR += r.second; 18 | maxlen = max(maxlen, max(iL + dR - 1, iR + dL - 1)); 19 | return {max(iL, iR), max(dL, dR)}; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /C++/554. Brick Wall.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int leastBricks(vector>& wall) { 4 | if(wall.size() == 0 || wall[0].size() == 0) return 0; 5 | unordered_mapm; 6 | for(auto x: wall){ 7 | int len = 0; 8 | for(int i = 0; i < x.size() - 1; i++){ 9 | len += x[i]; 10 | m[len]++; 11 | } 12 | } 13 | int n = wall.size(); 14 | int res = n; 15 | for(auto x: m) res = min(res, n - x.second); 16 | return res; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /C++/560. Subarray Sum Equals K.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int subarraySum(vector& nums, int k) { 4 | int count = 0; 5 | unordered_mapm; 6 | int sum = 0; 7 | for(auto x: nums){ 8 | m[sum]++; 9 | sum += x; 10 | if(m.count(sum - k) > 0) count += m[sum - k]; 11 | } 12 | return count; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /C++/562. Longest Line of Consecutive One in Matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestLine(vector>& M) { 4 | if(M.empty()) return 0; 5 | int maxlen = 0, m = M.size(), n = M[0].size(); 6 | for(int i = 0; i < m; i++) 7 | for(int j = 0; j < n; j++) 8 | if(M[i][j]) BFS(M, i, j, m, n, maxlen); 9 | return maxlen; 10 | } 11 | 12 | void BFS(vector>& M, int r, int c, int m, int n, int& maxlen){ 13 | int h = 1, v = 1, d_left = 1, d_right = 1; 14 | for(int i = c + 1; i < n && M[r][i]; i++) h++; 15 | for(int i = r + 1; i < m && M[i][c]; i++) v++; 16 | for(int i = r + 1, j = c - 1; i < m && j >= 0 && M[i][j]; i++, j--) d_left++; 17 | for(int i = r + 1, j = c + 1; i < m && j < n && M[i][j]; i++, j++) d_right++; 18 | maxlen = max(maxlen, max(max(h, v), max(d_left, d_right))); 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /C++/565. Array Nesting.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int arrayNesting(vector& nums) { 4 | int maxDepth = 0; 5 | for(int i = 0; i < nums.size(); i++){ 6 | if(nums[i] == -1) continue; 7 | DFS(nums, i, 0, maxDepth); 8 | } 9 | return maxDepth; 10 | } 11 | 12 | void DFS(vector& nums, int num, int depth, int& maxDepth){ 13 | if(nums[num] == -1){ 14 | maxDepth = max(maxDepth, depth); 15 | return; 16 | } 17 | int next = nums[num]; 18 | nums[num] = -1; 19 | DFS(nums, next, depth + 1, maxDepth); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /C++/566. Reshape the Matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> matrixReshape(vector>& nums, int r, int c) { 4 | int m = nums.size(), n = nums[0].size(); 5 | if(m * n != r * c) return nums; 6 | vector>res(r, vector(c)); 7 | int row = 0, col = 0; 8 | for(int i = 0; i < r; i++) 9 | for(int j = 0; j < c; j++){ 10 | res[i][j] = nums[row][col++]; 11 | if(col == n) col = 0, row++; 12 | } 13 | return res; 14 | } 15 | }; 16 | 17 | // Or 18 | class Solution { 19 | public: 20 | vector> matrixReshape(vector>& nums, int r, int c) { 21 | int m = nums.size(), n = nums[0].size(); 22 | if(m * n != r * c) return nums; 23 | vector>res(r, vector(c)); 24 | for(int i = 0; i < r; i++) 25 | for(int j = 0; j < c; j++) 26 | res[i][j] = nums[(i * c + j) / n][(i * c + j) % n]; 27 | return res; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /C++/567. Permutation in String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkInclusion(string s1, string s2) { 4 | int count = s1.size(); 5 | unordered_mapm; 6 | for(auto c: s1) m[c]++; 7 | int l = 0, r = 0; 8 | while(r < s2.size()){ 9 | if(m[s2[r++]]-- > 0) count--; 10 | while(count == 0){ 11 | if(r - l == s1.size()) return true; 12 | if(m[s2[l++]]++ == 0) count++; 13 | } 14 | } 15 | return false; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /C++/572. Subtree of Another Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | bool isSubtree(TreeNode* s, TreeNode* t) { 13 | if(!s) return !t; 14 | return isEqual(s, t) || isSubtree(s->left, t) || isSubtree(s->right, t); 15 | } 16 | 17 | bool isEqual(TreeNode* p, TreeNode* t){ 18 | if(!p || !t) return !p && !t; 19 | return p->val == t->val && isEqual(p->left, t->left) && isEqual(p->right, t->right); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /C++/582. Kill Process.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector killProcess(vector& pid, vector& ppid, int kill) { 4 | vectorres; 5 | unordered_map>g; 6 | for(int i = 0; i < pid.size(); i++) g[ppid[i]].push_back(pid[i]); 7 | // BFS 8 | dequeq; 9 | q.push_back(kill); 10 | while(!q.empty()){ 11 | auto p = q.front(); 12 | q.pop_front(); 13 | for(auto child: g[p]) q.push_back(child); 14 | res.push_back(p); 15 | } 16 | // DFS 17 | // DFS(g, kill, res); 18 | return res; 19 | } 20 | 21 | void DFS(unordered_map>& g, int kill, vector& res){ 22 | res.push_back(kill); 23 | for(auto child: g[kill]) DFS(g, child, res); 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /C++/583. Delete Operation for Two Strings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minDistance(string word1, string word2) { 4 | // dp[i][j] = word1[i - 1] == word2[j - 1] ? dp[i - 1][j - 1] + 1 : max(dp[i - 1][j], dp[i][j - 1]); 5 | vector>dp(word1.size() + 1, vector(word2.size() + 1)); 6 | for(int i = 0; i <= word1.size(); i++) 7 | for(int j = 0; j <= word2.size(); j++) 8 | dp[i][j] = (!i || !j) ? 0 : (word1[i - 1] == word2[j - 1]) ? dp[i - 1][j - 1] + 1 : max(dp[i - 1][j], dp[i][j - 1]); 9 | int LCS = dp[word1.size()][word2.size()]; 10 | return (word1.size() - LCS) + (word2.size() - LCS); 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /C++/599. Minimum Index Sum of Two Lists.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findRestaurant(vector& list1, vector& list2) { 4 | vectorres; 5 | unordered_mapm; 6 | int min = INT_MAX; 7 | for (int i = 0; i < list1.size(); i++) m[list1[i]] = i; 8 | for (int i = 0; i < list2.size(); i++) 9 | if (m.count(list2[i]) != 0) 10 | if (m[list2[i]] + i < min) min = m[list2[i]] + i, res.clear(), res.push_back(list2[i]); 11 | else if (m[list2[i]] + i == min) res.push_back(list2[i]); 12 | return res; 13 | } 14 | }; -------------------------------------------------------------------------------- /C++/606. Construct String from Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string tree2str(TreeNode* t) { 4 | if(!t) return ""; 5 | string l = tree2str(t->left); 6 | string r = tree2str(t->right); 7 | if(!t->left && !t->right) return to_string(t->val); 8 | if(!t->right) return to_string(t->val) + "(" + l + ")"; 9 | return to_string(t->val) + "(" + l + ")" + "(" + r + ")"; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /C++/611. Valid Triangle Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int triangleNumber(vector& nums) { 4 | sort(nums.begin(), nums.end()); 5 | int count = 0, n = nums.size(); 6 | for(int i = 0; i < n; i++) 7 | for(int j = i + 1; j < n; j++) 8 | for(int k = j + 1; k < n; k++) 9 | if(nums[i] + nums[j] > nums[k]) count++; 10 | return count; 11 | } 12 | }; 13 | 14 | class Solution { 15 | public: 16 | int triangleNumber(vector& nums) { 17 | sort(nums.begin(), nums.end()); 18 | int count = 0, n = nums.size(); 19 | for(int i = n - 1; i > 1; --i) { 20 | int l = 0, r = i - 1; 21 | while (l < r) { 22 | if (nums[l] + nums[r] > nums[i]) { 23 | count += r - l; 24 | --r; 25 | } else { 26 | ++l; 27 | } 28 | } 29 | } 30 | return count; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /C++/632. Smallest Range.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector smallestRange(vector>& nums) { 4 | vectorres(2); 5 | auto comp = [](vector& a, vector& b){ return a[0] > b[0]; }; 6 | priority_queue, vector>, decltype(comp)>pq(comp); 7 | int lo = 0, hi = 0, minRange = INT_MAX; 8 | for(int i = 0; i < nums.size(); i++) hi = max(hi, nums[i][0]), pq.push({nums[i][0], 0, i}); 9 | while(true){ 10 | auto v = pq.top(); 11 | pq.pop(); 12 | lo = v[0]; 13 | if(hi - lo < minRange){ 14 | minRange = min(minRange, hi - lo); 15 | res[0] = lo; 16 | res[1] = hi; 17 | } 18 | if(++v[1] == nums[v[2]].size()) break; 19 | v[0] = nums[v[2]][v[1]]; 20 | pq.push(v); 21 | hi = max(hi, v[0]); 22 | } 23 | return res; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /C++/633. Sum of Square Numbers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool judgeSquareSum(int c) { 4 | for(int a = 0, b = sqrt(c); a <= sqrt(c); a++, b = sqrt(c - a * a)) 5 | if(b * b == c - a * a) return true; 6 | return false; 7 | } 8 | }; 9 | -------------------------------------------------------------------------------- /C++/635. Design Log Storage System.cpp: -------------------------------------------------------------------------------- 1 | class LogSystem { 2 | private: 3 | unordered_maplog; 4 | unordered_maptime{{"Year", 4}, {"Month", 7}, {"Day", 10}, {"Hour", 13}, {"Minute", 16}, {"Second", 19}}; 5 | 6 | public: 7 | LogSystem() {} 8 | 9 | void put(int id, string timestamp) { 10 | log[id] = timestamp; 11 | } 12 | 13 | vector retrieve(string s, string e, string gra) { 14 | vectorres; 15 | int l = time[gra]; 16 | s = s.substr(0, l); 17 | e = e.substr(0, l); 18 | for(auto x: log){ 19 | string t = x.second.substr(0, l); 20 | if(s.compare(t) <= 0 && e.compare(t) >= 0) res.push_back(x.first); 21 | } 22 | return res; 23 | } 24 | }; 25 | 26 | /** 27 | * Your LogSystem object will be instantiated and called as such: 28 | * LogSystem obj = new LogSystem(); 29 | * obj.put(id,timestamp); 30 | * vector param_2 = obj.retrieve(s,e,gra); 31 | */ 32 | -------------------------------------------------------------------------------- /C++/643. Maximum Average Subarray I.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double findMaxAverage(vector& nums, int k) { 4 | int sum = 0, maxSum; 5 | for(int i = 0; i < nums.size(); i++){ 6 | sum += nums[i]; 7 | if(i == k - 1) maxSum = sum; 8 | if(i >= k){ 9 | sum -= nums[i - k]; 10 | maxSum = max(maxSum, sum); 11 | } 12 | } 13 | return (double)maxSum / k; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /C++/645. Set Mismatch.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findErrorNums(vector& nums) { 4 | int n = nums.size(), sum = 0, dup = 0, miss = 0; 5 | vectorcount(n, 0); 6 | for(int i = 0; i < n; sum += nums[i++]) if(++count[nums[i] - 1] > 1) dup = nums[i]; 7 | miss = n * (n + 1) / 2 - sum + dup; 8 | return {dup, miss}; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /C++/647. Palindromic Substrings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countSubstrings(string s) { 4 | int count = 0; 5 | for(int i = 0; i < s.size(); i++) 6 | for(int j = i; j < s.size(); j++) 7 | if(isPanlindrome(s.substr(i, j - i + 1))) count++; 8 | return count; 9 | } 10 | 11 | bool isPanlindrome(string s){ 12 | int i = 0, j = s.size() - 1; 13 | while(i < j) if(s[i++] != s[j--]) return false; 14 | return true; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /C++/652. Find Duplicate Subtrees.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findDuplicateSubtrees(TreeNode* root) { 4 | unordered_mapm; 5 | vectorres; 6 | DFS(root, m, res); 7 | return res; 8 | } 9 | 10 | string DFS(TreeNode* root, unordered_map& m, vector& res){ 11 | if(!root) return ""; 12 | string s = to_string(root->val) + "," + DFS(root->left, m, res) + "," + DFS(root->right, m, res); 13 | if(m[s]++ == 1) res.push_back(root); 14 | return s; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /C++/653. Two Sum IV - Input is a BST.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | bool findTarget(TreeNode* root, int k) { 13 | unordered_mapm; 14 | return DFS(root, m, k); 15 | } 16 | 17 | bool DFS(TreeNode* root, unordered_map& m, int k){ 18 | if(!root) return false; 19 | if(m.count(k - root->val)) return true; 20 | m[root->val]++; 21 | return DFS(root->left, m, k) || DFS(root->right, m, k); 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /C++/657. Judge Route Circle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool judgeCircle(string moves) { 4 | int v = 0, h = 0; 5 | unordered_mapm{{'R', 1}, {'L', -1}, {'U', -1}, {'D', 1}}; 6 | for(auto x: moves) 7 | if(x == 'L' || x == 'R') h += m[x]; 8 | else v += m[x]; 9 | return v == 0 && h == 0; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /C++/658. Find K Closest Elements.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findClosestElements(vector& arr, int k, int x) { 4 | vectorres; 5 | int pos = lower_bound(arr.begin(), arr.end(), x) - arr.begin(); 6 | int i = pos - 1, j = pos; 7 | while(k--) 8 | (i >= 0 && (j == arr.size() || abs(arr[i] - x) <= abs(arr[j] - x))) ? i-- : j++; 9 | res.assign(arr.begin() + i + 1, arr.begin() + j); 10 | return res; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /C++/663. Equal Tree Partition.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkEqualTree(TreeNode* root) { 4 | vectorv; 5 | int sum = DFS(root, v); 6 | v.pop_back(); 7 | return !(sum % 2) && find(v.begin(), v.end(), sum / 2) != v.end(); 8 | } 9 | 10 | int DFS(TreeNode* root, vector& v){ 11 | if(!root) return 0; 12 | int l = DFS(root->left, v); 13 | int r = DFS(root->right, v); 14 | int sum = root->val + l + r; 15 | v.push_back(sum); 16 | return sum; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /C++/665. Non-decreasing Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkPossibility(vector& nums) { 4 | int count = 0; 5 | for(int i = 1, j = 0; i < nums.size(); i++, j++) 6 | if(nums[j] > nums[i]){ 7 | count++; 8 | if(j > 0 && nums[j - 1] > nums[i]) nums[i] = nums[j]; 9 | else nums[j] = nums[i]; 10 | } 11 | return count <= 1; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /C++/669. Trim a Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | TreeNode* trimBST(TreeNode* root, int L, int R) { 13 | while(root && (root->val < L || root->val > R)) root = root->val < L ? root->right : root->left; 14 | if(!root) return NULL; 15 | root->left = trimBST(root->left, L, R); 16 | root->right = trimBST(root->right, L, R); 17 | return root; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /C++/671. Second Minimum Node In a Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | int findSecondMinimumValue(TreeNode* root) { 13 | int res = INT_MAX; 14 | DFS(root, root->val, res); 15 | return res == INT_MAX ? -1 : res; 16 | } 17 | 18 | void DFS(TreeNode* root, int val, int& res){ 19 | if(!root) return; 20 | if(root->val != val) res = min(res, root->val); 21 | if(root->val == val) DFS(root->left, val, res), DFS(root->right, val, res); 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /C++/673. Number of Longest Increasing Subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findNumberOfLIS(vector& nums) { 4 | int n = nums.size(); 5 | vectorlen(n, 1); 6 | vectorcnt(n, 1); 7 | int maxlen = 1, res = 0; 8 | for(int i = 0; i < n; i++){ 9 | for(int j = 0; j < i; j++){ 10 | if(nums[i] > nums[j]){ 11 | if(len[i] == len[j] + 1) cnt[i] += cnt[j]; 12 | if(len[i] < len[j] + 1){ 13 | len[i] = len[j] + 1; 14 | cnt[i] = cnt[j]; 15 | } 16 | } 17 | } 18 | if(len[i] == maxlen) res += cnt[i]; 19 | if(len[i] > maxlen){ 20 | maxlen = len[i]; 21 | res = cnt[i]; 22 | } 23 | } 24 | return res; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /C++/674. Longest Continuous Increasing Subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findLengthOfLCIS(vector& nums) { 4 | if(nums.empty()) return 0; 5 | int i = 0, j = 1, maxlen = 1; 6 | while(j < nums.size()){ 7 | while(j < nums.size() && nums[j] > nums[j - 1]) j++; 8 | maxlen = max(maxlen, j - i); 9 | i = j++; 10 | } 11 | return maxlen; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /C++/680. Valid Palindrome II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool validPalindrome(string s) { 4 | int i = 0, j = s.size() - 1; 5 | while(i <= j && s[i] == s[j]) i++, j--; 6 | return i > j || isValid(s.substr(i, j - i)) || isValid(s.substr(i + 1, j - i)); 7 | } 8 | 9 | bool isValid(string s){ 10 | int i = 0, j = s.size() - 1; 11 | while(i <= j && s[i] == s[j]) i++, j--; 12 | return i > j; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /C++/683. K Empty Slots.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int kEmptySlots(vector& flowers, int k) { 4 | sets; 5 | for(int i = 0; i < flowers.size(); i++){ 6 | int l = -1, r = -1; 7 | if(s.empty()){ 8 | s.insert(flowers[i]); 9 | continue; 10 | } 11 | auto up = s.upper_bound(flowers[i]); 12 | auto low = up; 13 | low--; 14 | if(up == s.end()) 15 | l = flowers[i] - *low - 1; 16 | else if(up == s.begin()) 17 | r = *up - flowers[i] - 1; 18 | else{ 19 | l = flowers[i] - *low - 1; 20 | r = *up - flowers[i] - 1; 21 | } 22 | if(l == k || r == k) return i + 1; 23 | s.insert(flowers[i]); 24 | } 25 | return -1; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /C++/686. Repeated String Match.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int repeatedStringMatch(string A, string B) { 4 | int i = 0, j = 0, count = 1; 5 | while(j < B.size()){ 6 | while(i < A.size() && A[i] != B[j]) i++; 7 | if(i == A.size() || count > 1) return -1; 8 | while(j < B.size() && A[i++] == B[j++]){ 9 | if(j == B.size()) return count; 10 | if(i == A.size()) i = 0, count++; 11 | } 12 | j = 0; 13 | } 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /C++/687. Longest Univalue Path.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | int longestUnivaluePath(TreeNode* root) { 13 | int maxlen = 0; 14 | DFS(root, maxlen); 15 | return maxlen; 16 | } 17 | 18 | int DFS(TreeNode* root, int& maxlen){ 19 | if(!root) return 0; 20 | int left = DFS(root->left, maxlen); 21 | int right = DFS(root->right, maxlen); 22 | if(!root->left || root->left->val != root->val) left = 0; 23 | if(!root->right || root->right->val != root->val) right = 0; 24 | maxlen = max(maxlen, left + right); 25 | return max(left, right) + 1; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /C++/688. Knight Probability in Chessboard.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | unordered_map>>dp; 4 | public: 5 | double knightProbability(int N, int K, int r, int c) { 6 | if(dp.count(r) && dp[r].count(c) && dp[r][c].count(K)) return dp[r][c][K]; 7 | if(r < 0 || r >= N || c < 0 || c >= N) return 0; 8 | if(K == 0) return 1; 9 | double total = knightProbability(N, K - 1, r - 1, c - 2) + knightProbability(N, K - 1, r - 2, c - 1) 10 | + knightProbability(N, K - 1, r - 1, c + 2) + knightProbability(N, K - 1, r - 2, c + 1) 11 | + knightProbability(N, K - 1, r + 1, c + 2) + knightProbability(N, K - 1, r + 2, c + 1) 12 | + knightProbability(N, K - 1, r + 1, c - 2) + knightProbability(N, K - 1, r + 2, c - 1); 13 | double res = total / 8; 14 | dp[r][c][K] = res; 15 | return res; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /C++/692. Top K Frequent Words.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector topKFrequent(vector& words, int k) { 4 | vectorres; 5 | unordered_mapm; 6 | auto comp = [](pair& a, pair& b){ return a.first == b.first ? a.second < b.second : a.first > b.first; }; 7 | priority_queue, vector >, decltype(comp)>pq(comp); 8 | for(auto x: words) m[x]++; 9 | for(auto x: m){ 10 | pq.push({x.second, x.first}); 11 | if(pq.size() > k) pq.pop(); 12 | } 13 | while(!pq.empty()) res.push_back(pq.top().second), pq.pop(); 14 | reverse(res.begin(), res.end()); 15 | return res; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /C++/693. Binary Number with Alternating Bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool hasAlternatingBits(int n) { 4 | while(n) 5 | if(!((n & 1) ^ ((n >> 1) & 1))) return false; 6 | else n >>= 1; 7 | return true; 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /C++/695. Max Area of Island.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxAreaOfIsland(vector>& grid) { 4 | if(grid.empty()) return 0; 5 | int maxArea = 0, m = grid.size(), n = grid[0].size(); 6 | for(int i = 0; i < m; i++) 7 | for(int j = 0; j < n; j++) 8 | if(grid[i][j]){ 9 | int area = 0; 10 | DFS(grid, i, j, m, n, area, maxArea); 11 | } 12 | return maxArea; 13 | } 14 | 15 | void DFS(vector>& grid, int r, int c, int m, int n, int& area, int& maxArea){ 16 | if(r < 0 || c < 0 || r == m || c == n || grid[r][c] == 0){ 17 | maxArea = max(maxArea, area); 18 | return; 19 | } 20 | area++; 21 | grid[r][c] = 0; 22 | DFS(grid, r + 1, c, m, n, area, maxArea); 23 | DFS(grid, r - 1, c, m, n, area, maxArea); 24 | DFS(grid, r, c + 1, m, n, area, maxArea); 25 | DFS(grid, r, c - 1, m, n, area, maxArea); 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /C++/696. Count Binary Substrings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countBinarySubstrings(string s) { 4 | int count = 0; 5 | for(int i = 0, j = 0; i < s.size(); j = i){ 6 | int a = 0, b = 0; 7 | while(j < s.size() && s[j] == s[i]) j++, a++; 8 | i = j; 9 | while(j < s.size() && s[j] == s[i]) j++, b++; 10 | count += min(a, b); 11 | } 12 | return count; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /C++/697. Degree of an Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findShortestSubArray(vector& nums) { 4 | unordered_mapidx, cnt; 5 | int degree = 0, minlen = nums.size(); 6 | for(int i = 0; i < nums.size(); i++){ 7 | if(!idx.count(nums[i])) idx[nums[i]] = i; 8 | if(++cnt[nums[i]] == degree) minlen = min(minlen, i - idx[nums[i]] + 1); 9 | if(cnt[nums[i]] > degree){ 10 | degree = cnt[nums[i]]; 11 | minlen = i - idx[nums[i]] + 1; 12 | } 13 | } 14 | return minlen; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /C++/701. Insert into a Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | TreeNode* insertIntoBST(TreeNode* root, int val) { 13 | dfs(root, val); 14 | return root; 15 | } 16 | 17 | void dfs(TreeNode*& root, int val) { 18 | if (!root) { 19 | root = new TreeNode(val); 20 | return; 21 | } 22 | if (root->val > val) { 23 | dfs(root->left, val); 24 | } else { 25 | dfs(root->right, val); 26 | } 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /C++/713. Subarray Product Less Than K.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numSubarrayProductLessThanK(vector& nums, int k) { 4 | int count = 0, product = 1; 5 | for(int i = 0, j = 0, pre = 0; j < nums.size(); i++, pre = j, j = max(i, j)){ 6 | while(j < nums.size() && product * nums[j] < k) product *= nums[j++]; 7 | count += (long)(j - pre) * (1 + (j - pre)) / 2 + (j - pre) * (pre - i); 8 | product = max(product / nums[i], 1); 9 | } 10 | return count; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /C++/717. 1-bit and 2-bit Characters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isOneBitCharacter(vector& bits) { 4 | int i = 0, n = bits.size(); 5 | while(i < n - 1) i += bits[i] + 1; 6 | return i != n; 7 | } 8 | }; 9 | -------------------------------------------------------------------------------- /C++/718. Maximum Length of Repeated Subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findLength(vector& A, vector& B) { 4 | // dp[i][j] is the maximum length of subarray ending with A[i] and B[j] 5 | // dp[i][j] = (A[i] == B[j]) ? dp[i - 1][j - 1] + 1 : 0; 6 | int m = A.size(), n = B.size(); 7 | vector>dp(m, vector(n)); 8 | int maxlen = 0; 9 | for(int i = 0; i < m; i++) 10 | for(int j = 0; j < n; j++){ 11 | if(i == 0 || j == 0) dp[i][j] = (A[i] == B[j]); 12 | else dp[i][j] = (A[i] == B[j]) ? dp[i - 1][j - 1] + 1 : 0; 13 | maxlen = max(maxlen, dp[i][j]); 14 | } 15 | return maxlen; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /C++/720. Longest Word in Dictionary.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string longestWord(vector& words) { 4 | string res = ""; 5 | unordered_map>m; 6 | for(auto s: words) m[s.size()].insert(s); 7 | for(auto s: words){ 8 | int i = 1; 9 | while(i < s.size() && m[i].count(s.substr(0, i))) i++; 10 | if(i == s.size() && s.size() >= res.size()) res = s.size() > res.size() ? s : min(s, res); 11 | } 12 | return res; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /C++/724. Find Pivot Index.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int pivotIndex(vector& nums) { 4 | int n = nums.size(), left = 0, right = 0; 5 | for(int x: nums) right += x; 6 | for(int i = 0; i < n; left += nums[i], right -= nums[i], i++) 7 | if(left == right - nums[i]) return i; 8 | return -1; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /C++/725. Split Linked List in Parts.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | vector splitListToParts(ListNode* root, int k) { 12 | vectorres; 13 | int len = 0; 14 | ListNode* head = new ListNode(0), *pre = root, *cur = head, *next, *p = root; 15 | while(p && ++len) p = p->next; 16 | int m = len % k, l = len / k; 17 | while(k--){ 18 | cur->next = pre; 19 | for(int i = 0; i < l; i++) cur = cur->next; 20 | if(m) cur = cur->next, m--; 21 | next = cur->next; 22 | cur->next = NULL; 23 | res.push_back(pre); 24 | pre = next; 25 | cur = head; 26 | } 27 | return res; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /C++/728. Self Dividing Numbers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector selfDividingNumbers(int left, int right) { 4 | vectorres; 5 | for(int i = left; i <= right; i++) 6 | if(isValid(i)) res.push_back(i); 7 | return res; 8 | } 9 | 10 | bool isValid(int num){ 11 | int n = num; 12 | while(n){ 13 | if(!(n % 10) || num % (n % 10)) return false; 14 | n /= 10; 15 | } 16 | return true; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /C++/729. My Calendar I.cpp: -------------------------------------------------------------------------------- 1 | class MyCalendar { 2 | public: 3 | MyCalendar() {} 4 | 5 | bool book(int start, int end) { 6 | for(auto& x: v) 7 | if(start >= x[0] && start < x[1] || end > x[0] && end <= x[1] || start < x[0] && end > x[1]) return false; 8 | v.push_back({start, end}); 9 | return true; 10 | } 11 | 12 | private: 13 | vector>v; 14 | }; 15 | -------------------------------------------------------------------------------- /C++/733. Flood Fill.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> floodFill(vector>& image, int sr, int sc, int newColor) { 4 | int m = image.size(), n = image[0].size(); 5 | DFS(image, sr, sc, m, n, image[sr][sc], newColor); 6 | return image; 7 | } 8 | 9 | void DFS(vector>& image, int r, int c, int m, int n, int target, int newColor){ 10 | if(r < 0 || c < 0 || r == m || c == n || image[r][c] == newColor || image[r][c] != target) return; 11 | image[r][c] = newColor; 12 | DFS(image, r + 1, c, m, n, target, newColor); 13 | DFS(image, r - 1, c, m, n, target, newColor); 14 | DFS(image, r, c + 1, m, n, target, newColor); 15 | DFS(image, r, c - 1, m, n, target, newColor); 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /C++/734. Sentence Similarity.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool areSentencesSimilar(vector& words1, vector& words2, vector> pairs) { 4 | if(words1.size() != words2.size()) return false; 5 | unordered_map>m; 6 | for(auto x: pairs){ 7 | m[x.first].insert(x.second); 8 | m[x.second].insert(x.first); 9 | } 10 | for(int i = 0; i < words1.size(); i++) 11 | if(words1[i] != words2[i] && !m[words1[i]].count(words2[i])) return false; 12 | return true; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /C++/735. Asteroid Collision.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector asteroidCollision(vector& asteroids) { 4 | vectors; 5 | for(auto& x: asteroids) 6 | if(s.empty() || s.back() < 0 || x > 0) s.push_back(x); 7 | else{ 8 | while(!s.empty() && s.back() > 0 && abs(x) > s.back()) s.pop_back(); 9 | if(s.empty() || s.back() < 0) s.push_back(x); 10 | else if(abs(x) == s.back()) s.pop_back(); 11 | } 12 | return s; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /C++/739. Daily Temperatures.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector dailyTemperatures(vector& temperatures) { 4 | int n = temperatures.size(); 5 | vectorres(n); 6 | stack>s; // stack of 7 | for(int i = 0; i < n; i++){ 8 | while(!s.empty() && temperatures[i] > s.top()[0]){ 9 | res[s.top()[1]] = i - s.top()[1]; 10 | s.pop(); 11 | } 12 | s.push({temperatures[i], i}); 13 | } 14 | return res; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /C++/740. Delete and Earn.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int deleteAndEarn(vector& nums) { 4 | int n = nums.size(); 5 | if(n == 0) return 0; 6 | sort(nums.begin(), nums.end()); 7 | vector>dp(n, vector(2)); 8 | dp[0][0] = 0; 9 | dp[0][1] = nums[0]; 10 | for(int i = 1; i < n; i++){ 11 | if(nums[i] == nums[i - 1]){ 12 | dp[i][0] = dp[i - 1][0]; 13 | dp[i][1] = dp[i - 1][1] + nums[i]; 14 | continue; 15 | } 16 | dp[i][0] = max(dp[i - 1][0], dp[i - 1][1]); 17 | dp[i][1] = nums[i] == nums[i - 1] + 1 ? dp[i - 1][0] + nums[i] : dp[i][0] + nums[i]; 18 | } 19 | return max(dp[n - 1][0], dp[n - 1][1]); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /C++/746. Min Cost Climbing Stairs.cpp: -------------------------------------------------------------------------------- 1 | // Recursion: `dp[i] = min{dp[i - 1], dp[i - 2]} + cost[i];` 2 | // A straightforward solution is: 3 | class Solution { 4 | public: 5 | int minCostClimbingStairs(vector& cost) { 6 | int n = cost.size(); 7 | vectordp(n); 8 | dp[0] = cost[0]; 9 | dp[1] = cost[1]; 10 | for(int i = 2; i < n; i++) 11 | dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i]; 12 | return min(dp[n - 2], dp[n - 1]); 13 | } 14 | }; 15 | 16 | // If we take a look at the solution above, we can see the result dp[i] only depends on previous 2 steps(dp[i - 1] and dp[i - 2]). 17 | // So we can replace the 'dp' array with 2 variables. 18 | // Here is the final solution: 19 | class Solution { 20 | public: 21 | int minCostClimbingStairs(vector& cost) { 22 | int n = cost.size(), a = cost[0], b = cost[1], c; 23 | for(int i = 2; i < n; i++, a = b, b = c) 24 | c = min(a, b) + cost[i]; 25 | return min(a, b); 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /C++/747. Largest Number At Least Twice of Others.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int dominantIndex(vector& nums) { 4 | int a = 0, b = 0, idx = -1; 5 | for(int i = 0; i < nums.size(); i++){ 6 | if(nums[i] > a){ 7 | b = a; 8 | a = nums[i]; 9 | idx = i; 10 | } 11 | else if(nums[i] > b) b = nums[i]; 12 | } 13 | return a >= 2 * b ? idx : -1; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /C++/750. Number Of Corner Rectangles.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countCornerRectangles(vector>& grid) { 4 | int m = grid.size(), n = grid[0].size(); 5 | int res = 0; 6 | for (int i = 0; i < m; ++i) { 7 | for (int j = i + 1; j < m; ++j) { 8 | int count = 0; 9 | for (int k = 0; k < n; ++k) { 10 | if (grid[i][k] && grid[j][k]) { 11 | ++count; 12 | } 13 | } 14 | res += (count - 1) * count / 2; 15 | } 16 | } 17 | return res; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /C++/758. Bold Words in String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string boldWords(vector& words, string S) { 4 | int n = S.size(); 5 | vectorv(n + 1); 6 | vectorm(n + 1); 7 | string res = ""; 8 | for(auto s: words){ 9 | auto pos = S.find(s); 10 | while(pos != string::npos){ 11 | v[pos]++; 12 | v[pos + s.size()]--; 13 | pos = S.find(s, pos + 1); 14 | } 15 | } 16 | int pre = 0, cur = 0; 17 | for(int i = 0; i < n + 1; i++){ 18 | cur = pre + v[i]; 19 | if(pre == 0 && cur > 0) m[i] = 1; 20 | else if(pre > 0 && cur == 0) m[i] = -1; 21 | pre = cur; 22 | } 23 | for(int i = 0; i < n + 1; i++){ 24 | if(m[i]) res += m[i] == 1 ? "" : ""; 25 | if(i < n) res.push_back(S[i]); 26 | } 27 | return res; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /C++/760. Find Anagram Mappings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector anagramMappings(vector& A, vector& B) { 4 | vectorres; 5 | unordered_mapm; 6 | for(int i = 0; i < B.size(); i++) m[B[i]] = i; 7 | for(int x: A) res.push_back(m[x]); 8 | return res; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /C++/765. Couples Holding Hands.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minSwapsCouples(vector& row) { 4 | unordered_mapidx; 5 | int n = row.size(); 6 | for (int i = 0; i < n; ++i) { 7 | idx[row[i]] = i; 8 | } 9 | int res = 0; 10 | for (int i = 0; i < n; i += 2) { 11 | if (!isCouple(row[i], row[i + 1])) { 12 | int val = findMyCouple(row[i]); 13 | swap(row[i + 1], row[idx[val]]); 14 | // Update idx 15 | idx[row[idx[val]]] = idx[val]; 16 | idx[row[i + 1]] = i + 1; 17 | ++res; 18 | } 19 | } 20 | return res; 21 | } 22 | 23 | bool isCouple(int a, int b) { 24 | return (!(a%2) && (b == a + 1)) || (!(b%2) && (a == b + 1)); 25 | } 26 | 27 | int findMyCouple(int x) { 28 | return x%2 ? x - 1 : x + 1; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /C++/766. Toeplitz Matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isToeplitzMatrix(vector>& matrix) { 4 | for(int i = 1; i < matrix.size(); i++) 5 | for(int j = 1; j < matrix[0].size(); j++) 6 | if(matrix[i][j] != matrix[i - 1][j - 1]) return false; 7 | return true; 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /C++/769. Max Chunks To Make Sorted.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxChunksToSorted(vector& arr) { 4 | int count = 0, maxDis = 0; 5 | for(int i = 0; i < arr.size(); i++){ 6 | maxDis = max(maxDis, arr[i]); 7 | if(maxDis == i) count++; 8 | } 9 | return count; 10 | } 11 | }; 12 | 13 | class Solution { 14 | public: 15 | int maxChunksToSorted(vector& arr) { 16 | int curMax = 0, n = arr.size(), res = 0; 17 | for (int i = 0; i < n; ++i) { 18 | curMax = max(curMax, arr[i]); 19 | if (curMax == i) { 20 | ++res; 21 | } 22 | } 23 | return res; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /C++/771. Jewels and Stones.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numJewelsInStones(string J, string S) { 4 | int count = 0; 5 | unordered_sets; 6 | for(char c: J) s.insert(c); 7 | for(char c: S) if(s.count(c)) count++; 8 | return count; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /C++/777. Swap Adjacent in LR String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canTransform(string start, string end) { 4 | int n = start.size(); 5 | string a, b; 6 | vectorposA, posB; 7 | for (int i = 0; i < n; ++i) { 8 | if (start[i] != 'X') { 9 | a.push_back(start[i]); 10 | posA.push_back(i); 11 | } 12 | if (end[i] != 'X') { 13 | b.push_back(end[i]); 14 | posB.push_back(i); 15 | } 16 | } 17 | if (a.size() != b.size()) { 18 | return false; 19 | } 20 | for (int i = 0; i < a.size(); ++i) { 21 | if (a[i] != b[i] || (a[i] == 'L' && posA[i] < posB[i] || a[i] == 'R' && posA[i] > posB[i])) { 22 | return false; 23 | } 24 | } 25 | return true; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /C++/779. K-th Symbol in Grammar.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int kthGrammar(int N, int K) { 4 | return N == 1 ? 0 : kthGrammar(N - 1, (K + 1) / 2) ? K % 2 : !(K % 2); 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /C++/784. Letter Case Permutation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector letterCasePermutation(string S) { 4 | vectorres; 5 | DFS(S, 0, res); 6 | return res; 7 | } 8 | 9 | void DFS(string S, int pos, vector& res){ 10 | if(pos == S.size()){ 11 | res.push_back(S); 12 | return; 13 | } 14 | DFS(S, pos + 1, res); 15 | char c = S[pos]; 16 | if(isalpha(c)){ 17 | S[pos] = islower(c) ? toupper(c) : tolower(c); 18 | DFS(S, pos + 1, res); 19 | } 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /C++/785. Is Graph Bipartite.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isBipartite(vector>& graph) { 4 | int n = graph.size(); 5 | vectorcolor(n); 6 | color[0] = 1; 7 | for(int i = 0; i < n; i++){ 8 | auto neigh = graph[i]; 9 | if(!color[i]) for(auto j: neigh) if(color[j]){ color[i] = -color[j]; break; } // If un-colored, pick a color by neighbor 10 | if(!color[i]) color[i] = 1; // Empty neighbor or no colored neighbor, colored 1 as default 11 | for(auto j: neigh) 12 | if(!color[j]) color[j] = -color[i]; 13 | else if(color[i] != -color[j]) return false; 14 | } 15 | return true; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /C++/791. Custom Sort String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string customSortString(string S, string T) { 4 | string res = ""; 5 | vectorv(26); 6 | for(auto c: T) v[c - 'a']++; 7 | for(auto c: S) 8 | while(v[c - 'a']--) res.push_back(c); 9 | for(int i = 0; i < 26; i++) 10 | while(v[i]-- > 0) res.push_back('a' + i); 11 | return res; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /C++/792. Number of Matching Subsequences.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numMatchingSubseq(string S, vector& words) { 4 | int res = 0; 5 | vector>bucket(26); 6 | for(int i = 0; i < S.size(); i++) bucket[S[i] - 'a'].push_back(i); 7 | for(auto s: words){ 8 | int pre = -1, cur = -1, i = 0; 9 | for(;i < s.size(); i++){ 10 | for(auto x: bucket[s[i] - 'a']){ 11 | if(x > pre){ 12 | cur = x; 13 | break; 14 | } 15 | } 16 | if(cur == pre) break; 17 | pre = cur; 18 | } 19 | if(i == s.size()) res++; 20 | } 21 | return res; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /C++/797. All Paths From Source to Target.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> allPathsSourceTarget(vector>& graph) { 4 | vector>res; 5 | dfs(graph, res, {}, 0); 6 | return res; 7 | } 8 | 9 | void dfs(vector>& graph, vector>& res, vector path, int node){ 10 | path.push_back(node); 11 | if(graph[node].size() == 0) res.push_back(path); 12 | for(int neigh: graph[node]) dfs(graph, res, path, neigh); 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /C++/798. Smallest Rotation with Highest Score.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int bestRotation(vector& A) { 4 | int n = A.size(); 5 | vectork(n); 6 | for(int i = 0; i < n; i++){ 7 | for(int j = 0; j <= i - A[i]; j++) k[j]++; 8 | for(int j = i + 1; j <= i + n - A[i] && j < n; j++) k[j]++; 9 | } 10 | return max_element(k.begin(), k.end()) - k.begin(); 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /C++/799. Champagne Tower.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double champagneTower(int poured, int query_row, int query_glass) { 4 | vectortower((1 + 100) * 100 / 2); 5 | tower[0] = poured; 6 | for(int i = 0; i < 99; i++){ 7 | for(int j = 0; j <= i; j++){ 8 | int idx = index(i, j); 9 | if(tower[idx] > 1){ 10 | double remain = tower[idx] - 1; 11 | tower[idx] = 1; 12 | tower[index(i + 1, j)] += remain / 2; 13 | tower[index(i + 1, j + 1)] += remain / 2; 14 | } 15 | } 16 | } 17 | return tower[index(query_row, query_glass)]; 18 | } 19 | 20 | int index(int row, int col){ 21 | return row * (row + 1) / 2 + col; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /C++/804. Unique Morse Code Words.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int uniqueMorseRepresentations(vector& words) { 4 | vectortable{".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."}; 5 | unordered_sets; 6 | for(string x: words){ 7 | string t = ""; 8 | for(char c: x) t += table[c - 'a']; 9 | s.insert(t); 10 | } 11 | return s.size(); 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /C++/805. Split Array With Same Average.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool splitArraySameAverage(vector& A) { 4 | int sum = 0, n = A.size(); 5 | for (int& x: A) { 6 | sum += x; 7 | } 8 | sort(A.rbegin(), A.rend()); 9 | for (int i = 1; i <= n/2; ++i) { 10 | if (sum*i%n == 0 && dfs(A, 0, i, sum*i/n, n)) { 11 | return true; 12 | } 13 | } 14 | return false; 15 | } 16 | 17 | bool dfs(vector& A, int pos, int count, int target, int& n) { 18 | if (count == 0) { 19 | return target == 0; 20 | } 21 | if (pos == n || target > A[pos] * count) { 22 | return false; 23 | } 24 | 25 | for (int i = pos; i < n; ++i) { 26 | if (target >= A[i] && dfs(A, i + 1, count - 1, target - A[i], n)) { 27 | return true; 28 | } 29 | } 30 | return false; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /C++/806. Number of Lines To Write String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector numberOfLines(vector& widths, string S) { 4 | int line = 1, sum = 0; 5 | for(char c: S){ 6 | sum += widths[c - 'a']; 7 | if(sum > 100) sum = widths[c - 'a'], line++; 8 | } 9 | return {line, sum}; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /C++/807. Max Increase to Keep City Skyline.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxIncreaseKeepingSkyline(vector>& grid) { 4 | int m = grid.size(), n = grid[0].size(); 5 | vectorrowMax(m); 6 | vectorcolMax(n); 7 | // Store the maximum value of each row and column 8 | for(int i = 0; i < m; i++) 9 | for(int j = 0; j < n; j++){ 10 | rowMax[i] = max(rowMax[i], grid[i][j]); 11 | colMax[j] = max(colMax[j], grid[i][j]); 12 | } 13 | // Sum up the difference 14 | int sum = 0; 15 | for(int i = 0; i < m; i++) 16 | for(int j = 0; j < n; j++) 17 | sum += min(rowMax[i], colMax[j]) - grid[i][j]; 18 | return sum; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /C++/814. Binary Tree Pruning.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | TreeNode* pruneTree(TreeNode* root) { 13 | if(!root) return NULL; 14 | root->left = pruneTree(root->left); 15 | root->right = pruneTree(root->right); 16 | return (!root->val && !root->left && !root->right) ? NULL : root; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /C++/819. Most Common Word.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string mostCommonWord(string paragraph, vector& banned) { 4 | unordered_mapm; 5 | for(int i = 0; i < paragraph.size();){ 6 | string s = ""; 7 | while(i < paragraph.size() && isalpha(paragraph[i])) s.push_back(tolower(paragraph[i++])); 8 | while(i < paragraph.size() && !isalpha(paragraph[i])) i++; 9 | m[s]++; 10 | } 11 | for(auto x: banned) m[x] = 0; 12 | string res = ""; 13 | int count = 0; 14 | for(auto x: m) 15 | if(x.second > count) res = x.first, count = x.second; 16 | return res; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /C++/821. Shortest Distance to a Character.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector shortestToChar(string S, char C) { 4 | vectorpos, res; 5 | for(int i = 0; i < S.size(); i++) if(S[i] == C) pos.push_back(i); 6 | for(int i = 0, p = 0; i < S.size(); i++){ 7 | if(p < pos.size() && i == pos[p]) p++; 8 | res.push_back(p == 0 ? pos[0] - i : p == pos.size() ? i - pos[p - 1] : min(i - pos[p - 1], pos[p] - i)); 9 | } 10 | return res; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /C++/826. Most Profit Assigning Work.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfitAssignment(vector& difficulty, vector& profit, vector& worker) { 4 | int res = 0; 5 | vector>v; 6 | for(int i = 0; i < difficulty.size(); i++) v.push_back({difficulty[i], profit[i]}); 7 | sort(v.begin(), v.end(), [](vector& v1, vector& v2){ return v1[0] < v2[0]; }); 8 | int maxProfit = 0; 9 | for(auto& x: v){ 10 | maxProfit = max(maxProfit, x[1]); 11 | x[1] = maxProfit; 12 | } 13 | for(auto& x: worker){ 14 | int pos = upper_bound(v.begin(), v.end(), x, [](int v1, vector& v2){ return v1 < v2[0]; }) - v.begin() - 1; 15 | if(pos >= 0) res += v[pos][1]; 16 | } 17 | return res; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /C++/830. Positions of Large Groups.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> largeGroupPositions(string S) { 4 | vector>res; 5 | int l = 0, r = 0, n = S.size(); 6 | while(l < n){ 7 | while(r < n && S[r] == S[l]) r++; 8 | if(r - l >= 3) res.push_back({l, r - 1}); 9 | l = r; 10 | } 11 | return res; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /C++/832. Flipping an Image.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> flipAndInvertImage(vector>& A) { 4 | for(auto& x: A){ 5 | reverse(x.begin(), x.end()); 6 | for(auto& y: x) y ^= 1; 7 | } 8 | return A; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /C++/836. Rectangle Overlap.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isRectangleOverlap(vector& rec1, vector& rec2) { 4 | return (min(rec1[3], rec2[3]) > max(rec1[1], rec2[1])) && (min(rec1[2], rec2[2]) > max(rec1[0], rec2[0])); 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /C++/845. Longest Mountain in Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestMountain(vector& A) { 4 | int l = 0, r = 1, res = 0, n = A.size(); 5 | bool up = true; 6 | while(r < n){ 7 | if(up && r - l > 1 && A[r] < A[r - 1]) up = false; 8 | if(up && (A[r] <= A[r - 1]) || !up && A[r] >= A[r - 1]){ 9 | l = up ? r : --r; 10 | up = true; 11 | } 12 | r++; 13 | if(!up && r - l > 2) res = max(res, r - l); 14 | } 15 | return res; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /C++/846. Hand of Straights.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isNStraightHand(vector& hand, int W) { 4 | int n = hand.size(); 5 | if(n % W) return false; 6 | mapm; 7 | for(int x: hand) m[x]++; 8 | auto l = m.begin(); 9 | for(int i = 0; i < n/W; i++){ 10 | auto r = l, t = m.end(); 11 | advance(r, W - 1); 12 | for(int j = W - 1; j >= 0; j--, r--) 13 | if((*r).second-- <= 0 || ((*r).first - (*l).first != j)) return false; 14 | else if((*r).second > 0) t = r; 15 | if(t != m.end()) l = t; 16 | else advance(l, W); 17 | } 18 | return true; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /C++/848. Shifting Letters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string shiftingLetters(string S, vector& shifts) { 4 | long sum = 0; 5 | for(int i = S.size() - 1; i >= 0; sum += shifts[i--]) S[i] = 'a' + (S[i] - 'a' + sum + shifts[i]) % 26; 6 | return S; 7 | } 8 | }; 9 | -------------------------------------------------------------------------------- /C++/849. Maximize Distance to Closest Person.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxDistToClosest(vector& seats) { 4 | int res = -1, d = 0; 5 | for(auto x: seats) if(x) res = max(res, res == -1 ? d : d/2), d = 1; else d++; 6 | return max(res, d - 1); 7 | } 8 | }; 9 | -------------------------------------------------------------------------------- /C++/852. Peak Index in a Mountain Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int peakIndexInMountainArray(vector& A) { 4 | int n = A.size(); 5 | // O(n) 6 | for (int i = 1; i < n - 1; ++i) { 7 | if (A[i] > A[i - 1] && A[i] > A[i + 1]) { 8 | return i; 9 | } 10 | } 11 | 12 | // O(logn) 13 | int l = 1, r = n - 2, mid; 14 | while (l <= r) { 15 | mid = l + (r - l)/2; 16 | if (A[mid] > A[mid - 1] && A[mid] > A[mid + 1]) { 17 | return mid; 18 | } else if (A[mid] > A[mid - 1]) { 19 | l = mid + 1; 20 | } else { 21 | r = mid - 1; 22 | } 23 | } 24 | return -1; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /C++/853. Car Fleet.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int carFleet(int target, vector& position, vector& speed) { 4 | int n = position.size(); 5 | int res = n; 6 | vector>cars; 7 | for (int i = 0; i < n; ++i) { 8 | cars.push_back({position[i], speed[i]}); 9 | } 10 | sort(cars.begin(), cars.end()); 11 | 12 | vectortime; 13 | for (int i = 0; i < n; ++i) { 14 | time.push_back(((double)target - cars[i][0]) / cars[i][1]); 15 | } 16 | for (int i = n - 2; i >= 0; --i) { 17 | if (time[i] <= time[i + 1]) { 18 | --res; 19 | time[i] = time[i + 1]; 20 | } 21 | } 22 | return res; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /C++/857. Minimum Cost to Hire K Workers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double mincostToHireWorkers(vector& quality, vector& wage, int K) { 4 | double res = INT_MAX; 5 | int n = quality.size(); 6 | vector>workers; 7 | for (int i = 0; i < n; ++i) { 8 | workers.push_back({(double)wage[i]/quality[i], quality[i]}); 9 | } 10 | sort(workers.begin(), workers.end()); 11 | int sum = 0; 12 | priority_queuepq; 13 | for (auto& x: workers) { 14 | sum += x[1]; 15 | pq.push(x[1]); 16 | if (pq.size() > K) { 17 | sum -= pq.top(); 18 | pq.pop(); 19 | } 20 | if (pq.size() == K) { 21 | res = min(res, x[0] * sum); 22 | } 23 | } 24 | return res; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /C++/859. Buddy Strings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool buddyStrings(string A, string B) { 4 | if(A.size() != B.size()) return false; 5 | int n = A.size(), pos = -1; 6 | vectorcount(26); 7 | bool repeat = false, swaped = false; 8 | for(int i = 0; i < n; i++){ 9 | if(A[i] != B[i]){ 10 | if(pos == -1) pos = i; 11 | else if(swaped || A[pos] != B[i] || A[i] != B[pos]) return false; 12 | else swaped = true; 13 | } 14 | if(++count[A[i] - 'a'] > 1) repeat = true; 15 | } 16 | return swaped || repeat; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /C++/872. Leaf-Similar Trees.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool leafSimilar(TreeNode* root1, TreeNode* root2) { 4 | vectorv; 5 | int pos = 0; 6 | dfs(root1, v, pos); 7 | pos = 0; 8 | return dfs(root2, v, pos); 9 | } 10 | 11 | bool dfs(TreeNode* p, vector& v, int& pos){ 12 | if(!p) return true; 13 | if(!p->left && !p->right){ 14 | if(v.size() == pos) v.push_back(p->val); 15 | return v[pos++] == p->val; 16 | } 17 | return dfs(p->left, v, pos) && dfs(p->right, v, pos); 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /C++/876. Middle of the Linked List.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* middleNode(ListNode* head) { 4 | auto a = head, b = head; 5 | while(b && b->next) a = a->next, b = b->next->next; 6 | return a; 7 | } 8 | }; 9 | -------------------------------------------------------------------------------- /C++/884. Uncommon Words from Two Sentences.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector uncommonFromSentences(string A, string B) { 4 | unordered_mapm; 5 | vectorres; 6 | stringstream ss(A + " " + B); 7 | string t; 8 | while(ss>>t) m[t]++; 9 | for(auto& x: m) if(x.second == 1) res.push_back(x.first); 10 | return res; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /C++/888. Fair Candy Swap.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector fairCandySwap(vector& A, vector& B) { 4 | int sumA(0), sumB(0), half; 5 | unordered_sets; 6 | for(auto& x: A) sumA += x; 7 | for(auto& x: B) sumB += x, s.insert(x); 8 | half = (sumA + sumB) / 2; 9 | for(auto& x: A) if(s.count(half - (sumA - x))) return {x, half - (sumA - x)}; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /C++/894. All Possible Full Binary Trees.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | vector allPossibleFBT(int N) { 13 | vector res; 14 | if (N == 1) { 15 | res.push_back(new TreeNode(0)); 16 | return res; 17 | } 18 | --N; 19 | for (int i = 1; i < N; i += 2) { 20 | auto left = allPossibleFBT(i); 21 | auto right = allPossibleFBT(N - i); 22 | for (TreeNode* l: left) { 23 | for (TreeNode* r: right) { 24 | TreeNode* cur = new TreeNode(0); 25 | cur->left = l; 26 | cur->right = r; 27 | res.push_back(cur); 28 | } 29 | } 30 | } 31 | return res; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /C++/896. Monotonic Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isMonotonic(vector& A) { 4 | bool a(true), b(true); 5 | int n = A.size(); 6 | for(int i = 0; i < n - 1 && (a || b); ++i){ 7 | if(A[i] > A[i + 1]) a = false; 8 | if(A[i] < A[i + 1]) b = false; 9 | } 10 | return a || b; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /C++/900. RLE Iterator.cpp: -------------------------------------------------------------------------------- 1 | class RLEIterator { 2 | public: 3 | RLEIterator(vector A) { 4 | for (auto x: A) { 5 | nums.push_back(x); 6 | } 7 | } 8 | 9 | int next(int n) { 10 | while (!nums.empty() && nums.front() < n ) { 11 | n -= nums.front(); 12 | nums.pop_front(); 13 | nums.pop_front(); 14 | } 15 | if (nums.empty()) { 16 | return -1; 17 | } 18 | int count = nums.front(); 19 | nums.pop_front(); 20 | int res = nums.front(); 21 | count -= n; 22 | if (count == 0) {a 23 | nums.pop_front(); 24 | } else { 25 | nums.push_front(count); 26 | } 27 | return res; 28 | } 29 | 30 | private: 31 | dequenums; 32 | }; 33 | 34 | /** 35 | * Your RLEIterator object will be instantiated and called as such: 36 | * RLEIterator obj = new RLEIterator(A); 37 | * int param_1 = obj.next(n); 38 | */ 39 | -------------------------------------------------------------------------------- /C++/904. Fruit Into Baskets.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int totalFruit(vector& tree) { 4 | int i = 0, j = 0, count = 0; 5 | unordered_mapm; 6 | int res = 0; 7 | while (j < tree.size()) { 8 | if (m[tree[j]] == 0) { 9 | ++count; 10 | } 11 | ++m[tree[j++]]; 12 | while (count > 2) { 13 | if (--m[tree[i++]] == 0) { 14 | --count; 15 | } 16 | } 17 | res = max(res, j - i); 18 | } 19 | return res; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /C++/911. Online Election.cpp: -------------------------------------------------------------------------------- 1 | class TopVotedCandidate { 2 | public: 3 | TopVotedCandidate(vector persons, vector times) { 4 | int curLead = -1; 5 | unordered_mapcount; 6 | for (int i = 0; i < times.size(); ++i) { 7 | count[persons[i]]++; 8 | if(count[persons[i]] >= count[curLead]) { 9 | curLead = persons[i]; 10 | } 11 | m[times[i]] = curLead; 12 | } 13 | } 14 | 15 | int q(int t) { 16 | return (--m.upper_bound(t))->second; 17 | } 18 | 19 | private: 20 | 21 | mapm; 22 | }; 23 | 24 | /** 25 | * Your TopVotedCandidate object will be instantiated and called as such: 26 | * TopVotedCandidate obj = new TopVotedCandidate(persons, times); 27 | * int param_1 = obj.q(t); 28 | */ 29 | -------------------------------------------------------------------------------- /C++/914. X of a Kind in a Deck of Cards.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool hasGroupsSizeX(vector& deck) { 4 | unordered_mapm; 5 | int n = deck.size(); 6 | for (int i = 0; i < n; ++i) { 7 | m[deck[i]]++; 8 | } 9 | int base = 0; 10 | for (auto& p: m) { 11 | base = gcd(p.second, base); 12 | } 13 | return base > 1; 14 | } 15 | 16 | int gcd(int a, int b) { 17 | if (b == 0) { 18 | return a; 19 | } 20 | return gcd(b, a % b); 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /C++/925. Long Pressed Name.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isLongPressedName(string name, string typed) { 4 | int a = 0, b = 0, n = name.size(), m = typed.size(); 5 | while (a < n && b < m) { 6 | if (name[a++] != typed[b++]) return false; 7 | while (b > 0 && name[a] != typed[b] && typed[b] == typed[b - 1]) ++b; 8 | } 9 | return a == n && b == m; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /C++/929. Unique Email Addresses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numUniqueEmails(vector& emails) { 4 | unordered_setres; 5 | 6 | for (const string& s: emails) { 7 | string e = filter(s); 8 | res.insert(e); 9 | } 10 | 11 | return res.size(); 12 | } 13 | 14 | string filter(const string& email) { 15 | string res; 16 | int i = 0, n = email.size(); 17 | bool ignore = false; 18 | for (; i < n; ++i) { 19 | if (email[i] == '@') { 20 | break; 21 | } else if (ignore || email[i] == '.') { 22 | continue; 23 | } else if (email[i] == '+') { 24 | ignore = true; 25 | } 26 | res.push_back(email[i]); 27 | } 28 | 29 | for (; i < n; ++i) { 30 | res.push_back(email[i]); 31 | } 32 | return res; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /C++/932. Beautiful Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector beautifulArray(int N) { 4 | vector res; 5 | for (int i = 1; i <= N; ++i) { 6 | res.push_back(i); 7 | } 8 | return beautify(res); 9 | } 10 | 11 | vector beautify(vector& v) { 12 | if (v.size() == 1) { 13 | return v; 14 | } 15 | vector odd, even; 16 | for (int i = 0; i < v.size(); ++i) { 17 | if (i % 2) { 18 | odd.push_back(v[i]); 19 | } else { 20 | even.push_back(v[i]); 21 | } 22 | } 23 | auto L = beautify(odd); 24 | auto R = beautify(even); 25 | for (const auto& x: R) { 26 | L.push_back(x); 27 | } 28 | return L; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /C++/933. Number of Recent Calls.cpp: -------------------------------------------------------------------------------- 1 | class RecentCounter { 2 | public: 3 | RecentCounter() { 4 | 5 | } 6 | 7 | int ping(int t) { 8 | while (!q.empty() && t - q.front() > 3000) { 9 | q.pop_front(); 10 | } 11 | q.push_back(t); 12 | return q.size(); 13 | } 14 | 15 | private: 16 | dequeq; 17 | }; 18 | 19 | /** 20 | * Your RecentCounter object will be instantiated and called as such: 21 | * RecentCounter* obj = new RecentCounter(); 22 | * int param_1 = obj->ping(t); 23 | */ 24 | -------------------------------------------------------------------------------- /C++/938. Range Sum of BST.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | int rangeSumBST(TreeNode* root, int L, int R) { 13 | return !root ? 0 : 14 | root->val < L ? rangeSumBST(root->right, L, R) : 15 | root->val > R ? rangeSumBST(root->left, L, R) : root->val + rangeSumBST(root->right, L, R) + rangeSumBST(root->left, L, R); 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /C++/939. Minimum Area Rectangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minAreaRect(vector>& points) { 4 | int minArea = 0; 5 | set>s; 6 | for (auto& p: points) { 7 | s.insert({p[0], p[1]}); 8 | } 9 | 10 | for (int i = 0; i < points.size(); ++i) { 11 | for (int j = 0; j < points.size(); ++j) { 12 | auto a = points[i]; 13 | auto b = points[j]; 14 | 15 | if (a[0] == b[0] || a[1] == b[1]) { 16 | continue; 17 | } 18 | 19 | pair c = {b[0], a[1]}; 20 | pair d = {a[0], b[1]}; 21 | 22 | if (s.count(c) && s.count(d)) { 23 | int area = abs(a[1] - b[1]) * abs(b[0] - a[0]); 24 | minArea = minArea ? min(minArea, area) : area; 25 | } 26 | } 27 | } 28 | return minArea; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /C++/941. Valid Mountain Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool validMountainArray(vector& A) { 4 | int i = 0, n = A.size(); 5 | if (n < 3) { 6 | return false; 7 | } 8 | while (i < n - 1 && A[i] < A[i + 1]) { 9 | ++i; 10 | } 11 | if (i == 0 || i == n - 1) { 12 | return false; 13 | } 14 | while (i < n - 1 && A[i] > A[i + 1]) { 15 | ++i; 16 | } 17 | return i == n - 1; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /C++/946. Validate Stack Sequences.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool validateStackSequences(vector& pushed, vector& popped) { 4 | stacks1, s2; 5 | int m = pushed.size(), n = popped.size(); 6 | for (int i = n - 1; i >= 0; --i) { 7 | s2.push(popped[i]); 8 | } 9 | 10 | for (int i = 0; i < m; ++i) { 11 | s1.push(pushed[i]); 12 | while (!s1.empty() && !s2.empty() && s1.top() == s2.top()) { 13 | s1.pop(); 14 | s2.pop(); 15 | } 16 | } 17 | return s2.empty(); 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /C++/951. Flip Equivalent Binary Trees.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | bool flipEquiv(TreeNode* root1, TreeNode* root2) { 13 | if (!root1 || !root2) { 14 | return !root1 && !root2; 15 | } 16 | if (root1->val != root2->val) { 17 | return false; 18 | } 19 | return flipEquiv(root1->left, root2->left) && flipEquiv(root1->right, root2->right) 20 | || flipEquiv(root1->left, root2->right) && flipEquiv(root1->right, root2->left); 21 | } 22 | }; 23 | --------------------------------------------------------------------------------