├── 3Sum ├── threeSum.cpp └── threeSum.java ├── 3SumClosest ├── 3SumClosest.cpp └── 3SumClosest.java ├── 4Sum └── fourSum.cpp ├── README.md ├── addBinary └── addBinary.cpp ├── addDigits └── addDigits.cpp ├── addTwoNumbers ├── addTwoNumbers.cpp └── addTwoNumbers.java ├── balancedBinaryTree └── balancedBinaryTree.cpp ├── basicCalculator └── basicCalculator.cpp ├── bestTimeToBuyAndSellStockII └── bestTimeToBuyAndSellStockII.cpp ├── binarySearchTreeIterator └── binarySearchTreeIterator.cpp ├── binaryTreeInorderTraversal └── binaryTreeInorderTraversal.cpp ├── binaryTreeLevelOrderTraversal ├── binaryTreeLevelOrderTraversal.cpp └── binaryTreeLevelOrderTraversalII.cpp ├── binaryTreePaths └── binaryTreePaths.cpp ├── binaryTreePostorderTraversal └── binaryTreePostorderTraversal.cpp ├── binaryTreePreorderTraversal └── binaryTreePreorderTraversal.cpp ├── binaryTreeZigzagLevelOrderTraversal └── binaryTreeZigzagLevelOrderTraversal.cpp ├── bulbSwitcher └── bulbSwitcher.cpp ├── bullsAndCows └── bullsAndCows.cpp ├── climbingStairs └── climbingStairs.cpp ├── combinationSum ├── combinationSum.java └── combinationSumII.java ├── compareVersionNumbers └── compareVersionNumbers.cpp ├── constructBinaryTreeFromInorderAndPostorderTraversal └── constructBinaryTreeFromInorderAndPostorderTraversal.cpp ├── constructBinaryTreeFromPreorderAndInorderTraversal └── constructBinaryTreeFromPreorderAndInorderTraversal.cpp ├── containerWithMostWater ├── containerWithMostWater.cpp └── containerWithMostWater.java ├── containsDuplicate ├── containsDuplicate.cpp └── containsDuplicateII.cpp ├── convertSortedArrayToBinarySearchTree └── convertSortedArrayToBinarySearchTree.cpp ├── copyListWithRandomPointer └── copyListWithRandomPointer.cpp ├── countAndSay └── countAndSay.cpp ├── countPrimes └── countPrimes.cpp ├── deleteNodeInALinkedList └── deleteNodeInALinkedList.cpp ├── divideTwoIntegers └── divideTwoIntegers.java ├── evaluateReversePolishNotation └── evaluateReversePolishNotation.cpp ├── excelSheetColumnNumber └── excelSheetColumnNumber.cpp ├── excelSheetColumnTitle └── excelSheetColumnTitle.cpp ├── factorialTrailingZeroes └── factorialTrailingZeroes.cpp ├── findMinimumInRotatedSortedArray ├── findMinimumInRotatedSortedArray.cpp └── findMinimumInRotatedSortedArrayII.cpp ├── firstMissingPositive └── firstMissingPositive.java ├── flattenBinaryTreeToLinkedList └── flattenBinaryTreeToLinkedList.cpp ├── fractionToRecurringDecimal └── fractionToRecurringDecimal.cpp ├── generateParentheses └── generateParentheses.cpp ├── grayCode └── grayCode.cpp ├── groupAnagrams └── groupAnagrams.cpp ├── h-Index ├── h-Index.cpp ├── h-IndexII.cpp └── h-Index_1.cpp ├── happyNumber └── happyNumber.cpp ├── implementQueueUsingStacks └── implementQueueUsingStacks.cpp ├── implementStackUsingQueues └── implementStackUsingQueues.cpp ├── implementStrStr() └── implementStrStr().cpp ├── insertInterval ├── insertInterval.cpp └── insertInterval_1.cpp ├── insertionSortList └── insertionSortList.cpp ├── integerToEnglishWords └── integerToEnglishWords.cpp ├── integerToRoman ├── integerToRoman.cpp ├── integerToRoman.java └── integerToRoman2.java ├── intersectionOfTwoLinkedLists └── intersectionOfTwoLinkedLists.cpp ├── invertBinaryTree └── invertBinaryTree.cpp ├── isomorphicStrings └── isomorphicStrings.cpp ├── jumpGame ├── jumpGame.java ├── jumpGameII.java └── jumpGame_2.java ├── kthLargestElementInAnArray └── kthLargestElementInAnArray.cpp ├── lRUCache └── lRUCache.cpp ├── largestNumber └── largestNumber.cpp ├── largestRectangleInHistogram └── largestRectangleInHistogram.cpp ├── lengthOfLastWord └── lengthOfLastWord.cpp ├── letterCombinationsOfAPhoneNumber ├── letterCombinationsOfAPhoneNumber.cpp ├── letterCombinationsOfAPhoneNumber.java └── letterCombinationsOfAPhoneNumber2.java ├── linkedListCycle ├── linkedListCycle.cpp └── linkedListCycleII.cpp ├── longestCommonPrefix ├── longestCommonPrefix.cpp └── longestCommonPrefix.java ├── longestPalindromicSubstring └── longestPalindromicSubstring.java ├── longestSubstringWithoutRepeatingCharacters ├── longestSubstringWithoutRepeatingCharacters.cpp └── longestSubstringWithoutRepeatingCharacters.java ├── longestValidParentheses └── longestValidParentheses.java ├── lowestCommonAncestorOfABinarySearchTree └── lowestCommonAncestorOfABinarySearchTree.cpp ├── majorityElement └── majorityElement.cpp ├── maxPointsOnALine └── maxPointsOnALine.cpp ├── maximalRectangle └── maximalRectangle.cpp ├── maximumDepthOfBinaryTree └── maximumDepthOfBinaryTree.cpp ├── maximumGap └── maximumGap.cpp ├── maximumSubarray └── maximumSubarray.cpp ├── medianOfTwoSortedArrays ├── medianOfTwoSortedArrays.cpp └── medianOfTwoSortedArrays.java ├── mergeIntervals ├── mergeIntervals.cpp ├── mergeIntervals_1.cpp └── mergeIntervals_2.cpp ├── mergeKSortedLists └── mergeKSortedLists.cpp ├── mergeSortedArray ├── mergeSortedArray.cpp └── mergeSortedArray_1.cpp ├── mergeTwoSortedLists └── mergeTwoSortedLists.cpp ├── minStack └── minStack.cpp ├── minimumDepthOfBinaryTree └── minimumDepthOfBinaryTree.cpp ├── minimumSizeSubarraySum └── minimumSizeSubarraySum.cpp ├── minimumWindowSubstring └── minimumWindowSubstring.cpp ├── missingNumber └── missingNumber.cpp ├── moveZeroes └── moveZeroes.cpp ├── multiplyStrings └── multiplyStrings.cpp ├── n-Queens └── n-Queens.java ├── nextPermutation └── nextPermutation.java ├── nimGame └── nimGame.cpp ├── numberOf1Bits └── numberOf1Bits.cpp ├── numberOfDigitOne └── numberOfDigitOne.cpp ├── oddEvenLinkedList └── oddEvenLinkedList.cpp ├── palindromeNumber ├── palindromeNumber.cpp └── palindromeNumber.java ├── partitionList └── partitionList.cpp ├── pascalsTriangle ├── pascalsTriangle.cpp └── pascalsTriangleII.cpp ├── pathSum ├── pathSum.cpp └── pathSumII.cpp ├── perfectSquares └── perfectSquares.cpp ├── permutationSequence └── permutationSequence.cpp ├── permutations ├── permutations.cpp └── permutationsII.java ├── plusOne ├── plusOne.cpp └── plusOne.java ├── populatingNextRightPointersInEachNode ├── populatingNextRightPointersInEachNode.cpp └── populatingNextRightPointersInEachNodeII.cpp ├── pow(x,n) └── pow(x,n).cpp ├── powerOfThree └── powerOfThree.cpp ├── powerOfTwo └── powerOfTwo.cpp ├── productOfArrayExceptSelf └── productOfArrayExceptSelf.cpp ├── recoverBinarySearchTree └── recoverBinarySearchTree.cpp ├── rectangleArea └── rectangleArea.cpp ├── regularExpressionMatching └── regularExpressionMatching.java ├── removeDuplicateLetters └── removeDuplicateLetters.cpp ├── removeDuplicatesFromSortedArray ├── removeDuplicatesFromSortedArray.cpp ├── removeDuplicatesFromSortedArray.java ├── removeDuplicatesFromSortedArrayII.cpp └── removeDuplicatesFromSortedArrayII.java ├── removeDuplicatesFromSortedList ├── removeDuplicatesFromSortedList.cpp └── removeDuplicatesFromSortedListII.cpp ├── removeElement └── removeElement.cpp ├── removeNthNodeFromEndOfList └── removeNthNodeFromEndOfList.cpp ├── reorderList └── reorderList.cpp ├── repeatedDNASequences └── repeatedDNASequences.cpp ├── restoreIPAddresses └── restoreIPAddresses.cpp ├── reverseBits └── reverseBits.cpp ├── reverseInteger ├── reverseInteger.cpp └── reverseInteger.java ├── reverseLinkedList ├── reverseLinkedList.cpp ├── reverseLinkedListII.cpp └── reverseLinkedList_1.cpp ├── reverseNodesInKGroup └── reverseNodesInKGroup.cpp ├── reverseWordsInAString └── reverseWordsInAString.cpp ├── romanToInteger ├── romanToInteger.cpp └── romanToInteger.java ├── rotateArray ├── rotateArray_1.cpp ├── rotateArray_2.cpp └── rotateArray_3.cpp ├── rotateImage ├── rotateImage.cpp └── rotateImage_1.cpp ├── rotateList └── rotateList.cpp ├── sameTree └── sameTree.cpp ├── searchA2DMatrix ├── search2DMatrix.java └── searchA2DMatrix.cpp ├── searchForARange ├── searchForARange.java └── searchForARange2.java ├── searchInRotatedSortedArray ├── searchInRotatedSortedArray.cpp ├── searchInRotatedSortedArray.java ├── searchInRotatedSortedArrayII.cpp └── searchInRotatedSortedArrayII.java ├── searchInsertPosition ├── searchInsertPosition.cpp └── searchInsertPosition.java ├── setMatrixZeroes ├── setMatrixZeroes.cpp └── setMatrixZeroes_1.cpp ├── simplifyPath └── simplifyPath.cpp ├── singleNumber ├── singleNumber.cpp └── singleNumberIII.cpp ├── slidingWindowMaximum └── slidingWindowMaximum.cpp ├── sortColors └── sortColors.cpp ├── sortList └── sortList.cpp ├── sqrt(x) └── sqrt(x).cpp ├── stringToInteger ├── stringToInteger.cpp └── stringToInteger.java ├── substringWithConcatenationOfAllWords └── substringWithConcatenationOfAllWords.cpp ├── sudokuSolver └── sudokuSolver.cpp ├── sumRootToLeafNumbers └── sumRootToLeafNumbers.cpp ├── summaryRanges └── summaryRanges.cpp ├── superUglyNumber └── superUglyNumber.cpp ├── swapNodesInPairs └── swapNodesInPairs.cpp ├── symmetricTree ├── symmetricTree.cpp └── symmetricTree_1.cpp ├── trappingRainWater └── trappingRainWater.cpp ├── twoSum ├── twoSum.cpp └── twoSum.java ├── uglyNumber ├── uglyNumber.cpp └── uglyNumberII.cpp ├── uniquePaths ├── uniquePaths.cpp └── uniquePaths_1.cpp ├── validAnagram └── validAnagram.cpp ├── validNumber └── validNumber.cpp ├── validPalindrome └── validPalindrome.cpp ├── validParentheses └── validParentheses.cpp ├── validSudoku └── validSudoku.cpp ├── validateBinarySearchTree └── validateBinarySearchTree.cpp ├── wildcardMatching └── wildcardMatching.java ├── wordPattern └── wordPattern.cpp ├── wordSearch └── wordSearch.cpp └── zigZagConversion ├── zigZagConversion.cpp └── zigZagConversion.java /3SumClosest/3SumClosest.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/3sum-closest/ 2 | // Author : weekend27 3 | // Date : 2016-01-11 4 | 5 | /********************************************************************************** 6 | 7 | Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. 8 | 9 | For example, given array S = {-1 2 1 -4}, and target = 1. 10 | 11 | The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 12 | 13 | **********************************************************************************/ 14 | 15 | // How to do it: 16 | // two pointers 17 | 18 | class Solution { 19 | public: 20 | int threeSumClosest(vector& nums, int target) { 21 | int min = INT_MAX; 22 | int result = 0; 23 | sort(nums.begin(), nums.end()); 24 | for (int i = 0; i < nums.size()-2; i++){ 25 | int j = i + 1; 26 | int k = nums.size() - 1; 27 | while (j < k) { 28 | int sum = nums[i] + nums[j] + nums[k]; 29 | int diff = abs(sum - target); 30 | 31 | if (diff == 0) { 32 | return sum; 33 | } 34 | 35 | if (diff < min) { 36 | min = diff; 37 | result = sum; 38 | } 39 | 40 | if (sum <= target) { 41 | j++; 42 | } else { 43 | k--; 44 | } 45 | } 46 | } 47 | 48 | return result; 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /3SumClosest/3SumClosest.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/3sum-closest/ 2 | // Author : weekend27 3 | // Date : 2016-04-27 4 | 5 | /********************************************************************************** 6 | 7 | Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. 8 | 9 | For example, given array S = {-1 2 1 -4}, and target = 1. 10 | 11 | The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 12 | 13 | **********************************************************************************/ 14 | 15 | // How to do it: 16 | // three pointers like 3Sum 17 | 18 | public class Solution { 19 | public int threeSumClosest(int[] nums, int target) { 20 | if (nums == null || nums.length < 3) return 0; 21 | 22 | int len = nums.length; 23 | int diff = 0; 24 | int res = 0; 25 | int minDiff = Integer.MAX_VALUE; 26 | Arrays.sort(nums); 27 | 28 | for (int i = 0; i < len - 2; ++i) { 29 | int j = i + 1; 30 | int k = len - 1; 31 | while (j < k) { 32 | int sum = nums[i] + nums[j] + nums[k]; 33 | if (sum == target) { 34 | return target; 35 | } else { 36 | diff = Math.abs(sum - target); 37 | if (diff < minDiff) { 38 | minDiff = diff; 39 | res = sum; 40 | } 41 | 42 | if (sum < target) { 43 | j++; 44 | } else { 45 | k--; 46 | } 47 | } 48 | } 49 | } 50 | 51 | return res; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # leetcode 2 | leetcode solutions 3 | -------------------------------------------------------------------------------- /addBinary/addBinary.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/add-binary/ 2 | // Author : weekend27 3 | // Date : 2015-12-16 4 | 5 | /********************************************************************************** 6 | 7 | Given two binary strings, return their sum (also a binary string). 8 | 9 | For example, 10 | a = "11" 11 | b = "1" 12 | Return "100". 13 | 14 | **********************************************************************************/ 15 | 16 | // How to do it: 17 | // reverse a and b, and then plus them one bit by one bit 18 | // note that carry in the end 19 | 20 | 21 | class Solution { 22 | public: 23 | string addBinary(string a, string b) { 24 | string result; 25 | int maxLen = max(a.size(), b.size()); 26 | std::reverse(a.begin(), a.end()); 27 | std::reverse(b.begin(), b.end()); 28 | int carry = 0; 29 | int num = 2; // binary 30 | for (int i = 0; i < maxLen; i++){ 31 | int ai = i < a.size() ? a[i]-'0' : 0; 32 | int bi = i < b.size() ? b[i]-'0' : 0; 33 | int val = (ai + bi + carry) % num; 34 | carry = (ai + bi + carry) / num; 35 | result.insert(result.begin(), val + '0'); 36 | } 37 | if (carry == 1){ 38 | result.insert(result.begin(), '1'); 39 | } 40 | return result; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /addDigits/addDigits.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/add-digits/ 2 | // Author : weekend27 3 | // Date : 2015-12-25 4 | 5 | /********************************************************************************** 6 | 7 | Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 8 | 9 | For example: 10 | 11 | Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. 12 | 13 | Follow up: 14 | Could you do it without any loop/recursion in O(1) runtime? 15 | 16 | Hint: 17 | 18 | A naive implementation of the above process is trivial. Could you come up with other methods? 19 | 20 | **********************************************************************************/ 21 | 22 | // How to do it: 23 | // ref: http://www.cnblogs.com/maples7/p/4734300.html 24 | 25 | class Solution { 26 | public: 27 | int addDigits(int num) { 28 | if (num == 0){ 29 | return 0; 30 | } 31 | else{ 32 | return (num - 1) % 9 + 1; 33 | } 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /addTwoNumbers/addTwoNumbers.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/add-two-numbers/ 2 | // Author : weekend27 3 | // Date : 2015-12-10 4 | 5 | /********************************************************************************** 6 | 7 | You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. 8 | 9 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 10 | Output: 7 -> 0 -> 8 11 | 12 | **********************************************************************************/ 13 | 14 | // How to do it: 15 | // easy! add two numbers one by one 16 | // please note the carry 17 | 18 | 19 | /** 20 | * Definition for singly-linked list. 21 | * struct ListNode { 22 | * int val; 23 | * ListNode *next; 24 | * ListNode(int x) : val(x), next(NULL) {} 25 | * }; 26 | */ 27 | class Solution { 28 | public: 29 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 30 | ListNode dummy(0); 31 | ListNode* p = &dummy; 32 | 33 | int carry = 0; 34 | 35 | while (l1 || l2){ 36 | int val = carry + (l1 ? l1->val : 0) + (l2 ? l2->val : 0); 37 | carry = val / 10; 38 | val = val % 10; 39 | p->next = new ListNode(val); 40 | p = p->next; 41 | if (l1) 42 | l1 = l1->next; 43 | if (l2) 44 | l2 = l2->next; 45 | } 46 | 47 | if (carry != 0){ 48 | p->next = new ListNode(carry); 49 | p = p->next; 50 | } 51 | 52 | return dummy.next; 53 | } 54 | }; 55 | -------------------------------------------------------------------------------- /addTwoNumbers/addTwoNumbers.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/add-two-numbers/ 2 | // Author : weekend27 3 | // Date : 2015-04-11 4 | 5 | /********************************************************************************** 6 | 7 | You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. 8 | 9 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 10 | Output: 7 -> 0 -> 8 11 | 12 | **********************************************************************************/ 13 | 14 | // How to do it: 15 | // ref: https://leetcode.com/discuss/2308/is-this-algorithm-optimal-or-what 16 | 17 | /** 18 | * Definition for singly-linked list. 19 | * public class ListNode { 20 | * int val; 21 | * ListNode next; 22 | * ListNode(int x) { val = x; } 23 | * } 24 | */ 25 | public class Solution { 26 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 27 | ListNode c1 = l1; 28 | ListNode c2 = l2; 29 | ListNode sentinel = new ListNode(0); 30 | ListNode d = sentinel; 31 | int sum = 0; 32 | while (c1 != null || c2 != null) { 33 | sum /= 10; 34 | if (c1 != null) { 35 | sum += c1.val; 36 | c1 = c1.next; 37 | } 38 | if (c2 != null) { 39 | sum += c2.val; 40 | c2 = c2.next; 41 | } 42 | d.next = new ListNode(sum % 10); 43 | d = d.next; 44 | } 45 | if (sum / 10 == 1) { 46 | d.next = new ListNode(1); 47 | } 48 | return sentinel.next; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /balancedBinaryTree/balancedBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/balanced-binary-tree/ 2 | // Author : weekend27 3 | // Date : 2015-12-11 4 | 5 | /********************************************************************************** 6 | 7 | Given a binary tree, determine if it is height-balanced. 8 | 9 | For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 10 | 11 | **********************************************************************************/ 12 | 13 | // How to do it: 14 | // DFS 15 | // time complexity: O(n) 16 | 17 | 18 | 19 | /** 20 | * Definition for a binary tree node. 21 | * struct TreeNode { 22 | * int val; 23 | * TreeNode *left; 24 | * TreeNode *right; 25 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 26 | * }; 27 | */ 28 | class Solution { 29 | public: 30 | bool isBalanced(TreeNode* root) { 31 | // DFS, time complexity O(n) 32 | // corner case check 33 | if (root == NULL) 34 | return true; 35 | int isBalanced = height(root); 36 | if (isBalanced != -1) 37 | return true; 38 | else 39 | return false; 40 | } 41 | 42 | int height(TreeNode* root) 43 | { 44 | if (root == NULL) 45 | return 0; 46 | 47 | int lh = height(root->left); 48 | if (lh == -1) 49 | return -1; 50 | int rh = height(root->right); 51 | if (rh == -1) 52 | return -1; 53 | 54 | int dh = rh > lh ? (rh - lh) : (lh - rh); 55 | if (dh > 1) 56 | return -1; 57 | else 58 | return dh = (rh > lh ? rh : lh) + 1; 59 | } 60 | }; 61 | -------------------------------------------------------------------------------- /bestTimeToBuyAndSellStockII/bestTimeToBuyAndSellStockII.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ 2 | // Author : weekend27 3 | // Date : 2015-12-28 4 | 5 | /********************************************************************************** 6 | 7 | Say you have an array for which the ith element is the price of a given stock on day i. 8 | 9 | Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 10 | 11 | **********************************************************************************/ 12 | 13 | // How to do it: 14 | // look at the code 15 | 16 | 17 | class Solution { 18 | public: 19 | int maxProfit(vector& prices) { 20 | int p = 0; 21 | for (int i = 1; i < prices.size(); i++){ 22 | if (prices[i] - prices[i-1] > 0){ 23 | p += prices[i] - prices[i-1]; 24 | } 25 | } 26 | return p; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /binaryTreeInorderTraversal/binaryTreeInorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/binary-tree-inorder-traversal/ 2 | // Author : weekend27 3 | // Date : 2015-12-14 4 | 5 | /********************************************************************************** 6 | 7 | Given a binary tree, return the inorder traversal of its nodes' values. 8 | 9 | For example: 10 | Given binary tree {1,#,2,3}, 11 | 1 12 | \ 13 | 2 14 | / 15 | 3 16 | return [1,3,2]. 17 | 18 | Note: Recursive solution is trivial, could you do it iteratively? 19 | 20 | **********************************************************************************/ 21 | 22 | // How to do it: 23 | // use a stack to store all root nodes that have been traversed 24 | // left traversal over -> pop root -> start right tree traversal 25 | 26 | /** 27 | * Definition for a binary tree node. 28 | * struct TreeNode { 29 | * int val; 30 | * TreeNode *left; 31 | * TreeNode *right; 32 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 33 | * }; 34 | */ 35 | class Solution { 36 | public: 37 | vector inorderTraversal(TreeNode* root) { 38 | vector values; 39 | if (root == NULL) 40 | return values; 41 | 42 | vector nodes; 43 | TreeNode* n = root; 44 | while (n || !nodes.empty()){ 45 | // traverse left sub-tree, push root node into stack 46 | while (n){ 47 | nodes.push_back(n); 48 | n = n->left; 49 | } 50 | 51 | if (!nodes.empty()){ 52 | n = nodes.back(); 53 | values.push_back(n->val); 54 | 55 | // pop root node, get right sub-tree 56 | nodes.pop_back(); 57 | n = n->right; 58 | } 59 | } 60 | 61 | return values; 62 | } 63 | }; 64 | -------------------------------------------------------------------------------- /binaryTreePreorderTraversal/binaryTreePreorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/binary-tree-preorder-traversal/ 2 | // Author : weekend27 3 | // Date : 2015-12-12 4 | 5 | /********************************************************************************** 6 | 7 | Given a binary tree, return the preorder traversal of its nodes' values. 8 | 9 | For example: 10 | Given binary tree {1,#,2,3}, 11 | 1 12 | \ 13 | 2 14 | / 15 | 3 16 | return [1,2,3]. 17 | 18 | Note: Recursive solution is trivial, could you do it iteratively? 19 | 20 | **********************************************************************************/ 21 | 22 | // How to do it: 23 | // use a stack to save right sub-tree first, and then save left sub-tree 24 | 25 | /** 26 | * Definition for a binary tree node. 27 | * struct TreeNode { 28 | * int val; 29 | * TreeNode *left; 30 | * TreeNode *right; 31 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 32 | * }; 33 | */ 34 | class Solution { 35 | public: 36 | vector preorderTraversal(TreeNode* root) { 37 | vector values; 38 | if (root == NULL) 39 | return values; 40 | 41 | vector nodes; 42 | 43 | // first push root into stack 44 | nodes.push_back(root); 45 | 46 | while (!nodes.empty()){ 47 | TreeNode* n = nodes.back(); 48 | values.push_back(n->val); 49 | 50 | // pop accessed node 51 | nodes.pop_back(); 52 | 53 | // push right child into stack to save 54 | if (n->right) 55 | nodes.push_back(n->right); 56 | 57 | // push left child into stack to save 58 | if (n->left) 59 | nodes.push_back(n->left); 60 | } 61 | return values; 62 | } 63 | }; 64 | -------------------------------------------------------------------------------- /bulbSwitcher/bulbSwitcher.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/bulb-switcher/ 2 | // Author : weekend27 3 | // Date : 2015-12-26 4 | 5 | /********************************************************************************** 6 | 7 | There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the nth round, you only toggle the last bulb. Find how many bulbs are on after n rounds. 8 | 9 | Example: 10 | 11 | Given n = 3. 12 | 13 | At first, the three bulbs are [off, off, off]. 14 | After first round, the three bulbs are [on, on, on]. 15 | After second round, the three bulbs are [on, off, on]. 16 | After third round, the three bulbs are [on, off, off]. 17 | 18 | So you should return 1, because there is only one bulb is on. 19 | 20 | **********************************************************************************/ 21 | 22 | // How to do it: 23 | // ref: http://www.hrwhisper.me/leetcode-bulb-switcher/ 24 | /* 25 | 我们来分析下:对于素数,那么它仅有1和它本身,最后一定是关掉的。 26 | 27 | 对一普通的,一定是关掉的,因子成对出现 28 | 29 | 对于完全平方数,因为有一个倍数不成对出现,所以一定是打开的。比如4 => 1,4 | 2 30 | 31 | 所以本题就是求1~n有几个完全平方数。 32 | 33 | 那么,怎么求呢?从1开始到n,每个数测试一下?时间复杂度O(n),太慢 34 | 35 | 正确的是直接sqrt(n),就可以算出来啦~ 36 | */ 37 | 38 | 39 | class Solution { 40 | public: 41 | int bulbSwitch(int n) { 42 | return (int)sqrt(n); 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /climbingStairs/climbingStairs.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/climbing-stairs/ 2 | // Author : weekend27 3 | // Date : 2016-01-02 4 | 5 | /********************************************************************************** 6 | 7 | You are climbing a stair case. It takes n steps to reach to the top. 8 | 9 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 10 | 11 | **********************************************************************************/ 12 | 13 | // How to do it: 14 | // recursion, dynamic 15 | 16 | class Solution { 17 | public: 18 | int climbStairs(int n) { 19 | vector res(n+1); 20 | res[0] = 1; 21 | res[1] = 1; 22 | for (int i = 2; i <= n; i++) { 23 | res[i] = res[i-1] + res[i-2]; 24 | } 25 | return res[n]; 26 | } 27 | }; -------------------------------------------------------------------------------- /compareVersionNumbers/compareVersionNumbers.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/compare-version-numbers/ 2 | // Author : weekend27 3 | // Date : 2015-12-19 4 | 5 | /********************************************************************************** 6 | 7 | Compare two version numbers version1 and version2. 8 | If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0. 9 | 10 | You may assume that the version strings are non-empty and contain only digits and the . character. 11 | The . character does not represent a decimal point and is used to separate number sequences. 12 | For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision. 13 | 14 | Here is an example of version numbers ordering: 15 | 16 | 0.1 < 1.1 < 1.2 < 13.37 17 | 18 | **********************************************************************************/ 19 | 20 | // How to do it: 21 | // compare two parts: first compare the part before the dot, if they are equal, then compare the part after the dot 22 | 23 | 24 | class Solution { 25 | public: 26 | int compareVersion(string version1, string version2) { 27 | for (int i1 = 0, i2 = 0; i1 < version1.size() || i2 < version2.size(); i1++, i2++){ 28 | 29 | int num1 = 0; 30 | while (version1[i1] != '.' && i1 < version1.size()){ 31 | num1 = num1 * 10 + (version1[i1++] - '0'); 32 | } 33 | 34 | int num2 = 0; 35 | while (version2[i2] != '.' && i2 < version2.size()){ 36 | num2 = num2 * 10 + (version2[i2++] - '0'); 37 | } 38 | 39 | if (num1 < num2) return -1; 40 | if (num1 > num2) return 1; 41 | } 42 | return 0; 43 | 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /constructBinaryTreeFromInorderAndPostorderTraversal/constructBinaryTreeFromInorderAndPostorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/ 2 | // Author : weekend27 3 | // Date : 2015-12-11 4 | 5 | /********************************************************************************** 6 | 7 | Given inorder and postorder traversal of a tree, construct the binary tree. 8 | 9 | Note: 10 | You may assume that duplicates do not exist in the tree. 11 | 12 | **********************************************************************************/ 13 | 14 | // How to do it: 15 | // recursively find the root(mid node) 16 | // for example: inorder [4251637], postorder[4526731], first find the root:1, then do it recursively in the left part and right part. 17 | 18 | /** 19 | * Definition for a binary tree node. 20 | * struct TreeNode { 21 | * int val; 22 | * TreeNode *left; 23 | * TreeNode *right; 24 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 25 | * }; 26 | */ 27 | class Solution { 28 | public: 29 | unordered_map m; 30 | TreeNode* buildTree(vector& inorder, vector& postorder) { 31 | if (postorder.empty()) 32 | return NULL; 33 | 34 | for (int i = 0; i < inorder.size(); i++) 35 | m[inorder[i]] = i; 36 | 37 | return build(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1); 38 | } 39 | 40 | TreeNode* build(vector& inorder, int s0, int e0, vector& postorder, int s1, int e1){ 41 | if (s0 > e0 || s1 > e1) 42 | return NULL; 43 | 44 | TreeNode* root = new TreeNode(postorder[e1]); 45 | int mid = m[postorder[e1]]; 46 | int num = mid - s0; 47 | 48 | root->left = build(inorder, s0, mid - 1, postorder, s1, s1 + num - 1); 49 | root->right = build(inorder, mid + 1, e0, postorder, s1 + num, e1 - 1); 50 | 51 | return root; 52 | } 53 | }; 54 | -------------------------------------------------------------------------------- /constructBinaryTreeFromPreorderAndInorderTraversal/constructBinaryTreeFromPreorderAndInorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ 2 | // Author : weekend27 3 | // Date : 2015-12-11 4 | 5 | /********************************************************************************** 6 | 7 | Given preorder and inorder traversal of a tree, construct the binary tree. 8 | 9 | Note: 10 | You may assume that duplicates do not exist in the tree. 11 | 12 | **********************************************************************************/ 13 | 14 | // How to do it: 15 | // recursively find the root(mid node) 16 | // for example: inorder [4251637], preorder[1234567], first find the root:1, then do it recursively in the left part and right part. 17 | 18 | 19 | /** 20 | * Definition for a binary tree node. 21 | * struct TreeNode { 22 | * int val; 23 | * TreeNode *left; 24 | * TreeNode *right; 25 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 26 | * }; 27 | */ 28 | class Solution { 29 | public: 30 | unordered_map m; 31 | TreeNode* buildTree(vector& preorder, vector& inorder) { 32 | if (preorder.empty()) 33 | return NULL; 34 | 35 | for (int i = 0; i < inorder.size(); i++) 36 | m[inorder[i]] = i; 37 | 38 | return build(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1); 39 | } 40 | 41 | TreeNode* build(vector& preorder, int s0, int e0, vector& inorder, int s1, int e1){ 42 | if (s0 > e0 || s1 > e1) 43 | return NULL; 44 | 45 | int mid = m[preorder[s0]]; 46 | 47 | TreeNode* root = new TreeNode(preorder[s0]); 48 | 49 | int num = mid - s1; 50 | 51 | root->left = build(preorder, s0 + 1, s0 + num, inorder, s1, mid - 1); 52 | root->right = build(preorder, s0 + num + 1, e0, inorder, mid + 1, e1); 53 | 54 | return root; 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /containerWithMostWater/containerWithMostWater.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/container-with-most-water/ 2 | // Author : weekend27 3 | // Date : 2016-01-05 4 | 5 | /********************************************************************************** 6 | 7 | Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. 8 | 9 | Note: You may not slant the container. 10 | 11 | **********************************************************************************/ 12 | 13 | // How to do it: 14 | // ref: http://blog.csdn.net/wzy_1988/article/details/17248209 15 | 16 | class Solution { 17 | public: 18 | int maxArea(vector& height) { 19 | int i, j, lh, rh, area, temp; 20 | int len = height.size(); 21 | 22 | lh = height[0]; 23 | rh = height[len-1]; 24 | area = 0; 25 | i = 0; 26 | j = len - 1; 27 | 28 | while (i < j) { 29 | temp = (lh < rh ? lh : rh) * (j - i); 30 | 31 | if (temp > area) { 32 | area = temp; 33 | } 34 | 35 | if (lh < rh) { 36 | while (i < j && height[i] <= lh) { 37 | i++; 38 | } 39 | if (i < j) { 40 | lh = height[i]; 41 | } 42 | } else { 43 | while (i < j && height[j] <= rh) { 44 | j--; 45 | } 46 | if (i < j){ 47 | rh = height[j]; 48 | } 49 | } 50 | } 51 | 52 | return area; 53 | } 54 | }; 55 | -------------------------------------------------------------------------------- /containerWithMostWater/containerWithMostWater.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/container-with-most-water/ 2 | // Author : weekend27 3 | // Date : 2016-04-26 4 | 5 | /********************************************************************************** 6 | 7 | Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. 8 | 9 | Note: You may not slant the container. 10 | 11 | **********************************************************************************/ 12 | 13 | // How to do it: 14 | // 所谓求容积也就是求面积,长方形面积 = 长 * 宽,所以可以让left = 0, right = height.length - 1,向中间靠拢; 15 | // 在寻找下一个长方形时,移动高度较小的下标即可 16 | // 时间复杂度: O(n) 17 | 18 | public class Solution { 19 | public int maxArea(int[] height) { 20 | int maxArea = 0, area; 21 | int left = 0, right = height.length - 1; 22 | while (left < right) { 23 | area = (right - left) * min(height[left], height[right]); 24 | maxArea = (maxArea > area) ? maxArea : area; 25 | if (height[left] < height[right]) { 26 | ++left; 27 | } else { 28 | --right; 29 | } 30 | } 31 | return maxArea; 32 | } 33 | 34 | public static int min(int a, int b) { 35 | return (a < b) ? a : b; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /containsDuplicate/containsDuplicate.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/contains-duplicate/ 2 | // Author : weekend27 3 | // Date : 2015-11-27 4 | 5 | /********************************************************************************** 6 | 7 | Given an array of integers, find if the array contains any duplicates. 8 | Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. 9 | 10 | **********************************************************************************/ 11 | 12 | // How to do it: 13 | // two steps: sort the vector first, and then check if the adjacent elements are the same 14 | 15 | class Solution { 16 | public: 17 | bool containsDuplicate(vector& nums) { 18 | if (nums.size() <= 1) return false; 19 | vector& array = nums; 20 | std::sort(array.begin(),array.end()); 21 | for(int i = 1; i < array.size(); i++){ 22 | if (array[i] == array[i-1]) return true; 23 | } 24 | return false; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /containsDuplicate/containsDuplicateII.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/contains-duplicate-ii/ 2 | // Author : weekend27 3 | // Date : 2015-12-03 4 | 5 | /********************************************************************************** 6 | 7 | Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array 8 | such that nums[i] = nums[j] and the difference between i and j is at most k. 9 | 10 | **********************************************************************************/ 11 | 12 | // How to do it: 13 | // hash table 14 | 15 | class Solution { 16 | public: 17 | bool containsNearbyDuplicate(vector& nums, int k) { 18 | map int_map; 19 | map::iterator iter; 20 | for (int i = 0; i < nums.size(); i++){ 21 | if((iter = int_map.find(nums[i])) != int_map.end()){ 22 | if (i - iter->second <= k) 23 | return true; 24 | else 25 | int_map.erase(iter); 26 | } 27 | int_map.insert(pair(nums[i], i)); 28 | } 29 | return false; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /convertSortedArrayToBinarySearchTree/convertSortedArrayToBinarySearchTree.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ 2 | // Author : weekend27 3 | // Date : 2015-12-14 4 | 5 | /********************************************************************************** 6 | 7 | Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 8 | 9 | **********************************************************************************/ 10 | 11 | // How to do it: 12 | // find the mid element, left part is left sub-tree, right part is right sub-tree, and then divide and conquer 13 | 14 | 15 | /** 16 | * Definition for a binary tree node. 17 | * struct TreeNode { 18 | * int val; 19 | * TreeNode *left; 20 | * TreeNode *right; 21 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 22 | * }; 23 | */ 24 | class Solution { 25 | public: 26 | TreeNode* sortedArrayToBST(vector& nums) { 27 | return build(nums, 0, nums.size()); 28 | } 29 | 30 | TreeNode* build(vector& nums, int begin, int end){ 31 | if (begin >= end) 32 | return NULL; 33 | 34 | int mid = begin + (end - begin) / 2; 35 | 36 | TreeNode* node = new TreeNode(nums[mid]); 37 | node->left = build(nums, begin, mid); 38 | node->right = build(nums, mid+1, end); 39 | 40 | return node; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /countAndSay/countAndSay.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/count-and-say/ 2 | // Author : weekend27 3 | // Date : 2015-12-16 4 | 5 | /********************************************************************************** 6 | 7 | The count-and-say sequence is the sequence of integers beginning as follows: 8 | 1, 11, 21, 1211, 111221, ... 9 | 10 | 1 is read off as "one 1" or 11. 11 | 11 is read off as "two 1s" or 21. 12 | 21 is read off as "one 2, then one 1" or 1211. 13 | Given an integer n, generate the nth sequence. 14 | 15 | Note: The sequence of integers will be represented as a string. 16 | 17 | **********************************************************************************/ 18 | 19 | // How to do it: 20 | // string-operation. The only trick thing is Line32. seq[seq.size()] always '\0'. It will help to save an "if" statement. 21 | 22 | 23 | class Solution { 24 | public: 25 | string countAndSay(int n) { 26 | string seq = "1"; 27 | int it = 1; 28 | while(it < n){ 29 | stringstream newSeq; 30 | char last = seq[0]; 31 | int cnt = 0; 32 | for (int i = 0; i <= seq.size(); i++){ 33 | if (seq[i] == last){ 34 | cnt++; 35 | continue; 36 | } else { 37 | newSeq << cnt << last; 38 | last = seq[i]; 39 | cnt = 1; 40 | } 41 | } 42 | seq = newSeq.str(); 43 | it++; 44 | } 45 | return seq; 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /deleteNodeInALinkedList/deleteNodeInALinkedList.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/delete-node-in-a-linked-list/ 2 | // Author : weekend27 3 | // Date : 2015-12-28 4 | 5 | /********************************************************************************** 6 | 7 | Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. 8 | 9 | Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function. 10 | 11 | **********************************************************************************/ 12 | 13 | // How to do it: 14 | // look at the code 15 | 16 | /** 17 | * Definition for singly-linked list. 18 | * struct ListNode { 19 | * int val; 20 | * ListNode *next; 21 | * ListNode(int x) : val(x), next(NULL) {} 22 | * }; 23 | */ 24 | class Solution { 25 | public: 26 | void deleteNode(ListNode* node) { 27 | ListNode* temp = node->next; 28 | node->val = temp->val; 29 | node->next = temp->next; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /divideTwoIntegers/divideTwoIntegers.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/divide-two-integers/ 2 | // Author : weekend27 3 | // Date : 2016-04-06 4 | 5 | /********************************************************************************** 6 | 7 | Divide two integers without using multiplication, division and mod operator. 8 | 9 | If it is overflow, return MAX_INT. 10 | 11 | **********************************************************************************/ 12 | 13 | // How to do it: 14 | // ref: http://www.programcreek.com/2014/05/leetcode-divide-two-integers-java/ 15 | /* 16 | This problem can be solved based on the fact that any number can be converted to the format of the following: 17 | 18 | num=a_0*2^0+a_1*2^1+a_2*2^2+...+a_n*2^n 19 | */ 20 | 21 | 22 | public class diviTwoIntegers { 23 | public int divide(int dividend, int divisor) { 24 | // handle special cases 25 | if (divisor == 0) return Integer.MAX_VALUE; 26 | if (divisor == -1 && dividend == Integer.MIN_VALUE) return Integer.MAX_VALUE; 27 | 28 | // get positive values 29 | long pDividend = Math.abs((long)dividend); 30 | long pDivisor = Math.abs((long)divisor); 31 | 32 | int result = 0; 33 | while (pDividend >= pDivisor) { 34 | // calculate number of left shifts 35 | int numShift = 0; 36 | while (pDividend >= (pDivisor << numShift)) { 37 | numShift++; 38 | } 39 | 40 | // dividend minus the largest shifted divisor 41 | result += 1 << (numShift - 1); 42 | pDividend -= (pDivisor << (numShift - 1)); 43 | } 44 | 45 | if ((dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0)) { 46 | return result; 47 | } else { 48 | return -result; 49 | } 50 | 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /evaluateReversePolishNotation/evaluateReversePolishNotation.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/evaluate-reverse-polish-notation/ 2 | // Author : weekend27 3 | // Date : 2015-12-20 4 | 5 | /********************************************************************************** 6 | 7 | Evaluate the value of an arithmetic expression in Reverse Polish Notation. 8 | 9 | Valid operators are +, -, *, /. Each operand may be an integer or another expression. 10 | 11 | Some examples: 12 | ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 13 | ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 14 | 15 | **********************************************************************************/ 16 | 17 | // How to do it: 18 | // use a stack to store numbers and tmp results, when meeting an op, pop two numbers and calculate them, and then put the result into the stack 19 | 20 | class Solution { 21 | public: 22 | int evalRPN(vector& tokens) { 23 | stack s; 24 | for (int i = 0; i < tokens.size(); i++){ 25 | if (isOp(tokens[i])){ 26 | int y = s.top(); 27 | s.pop(); 28 | int x = s.top(); 29 | s.pop(); 30 | s.push(evaluate(x, y, tokens[i])); 31 | } 32 | else { 33 | s.push(stoi(tokens[i], nullptr, 10)); 34 | } 35 | } 36 | return s.top(); 37 | } 38 | 39 | bool isOp(string s){ 40 | if (s == "+" || s == "-" || s == "*" || s == "/"){ 41 | return true; 42 | } 43 | return false; 44 | } 45 | 46 | int evaluate(int x, int y, string op){ 47 | if (op == "+"){ 48 | return x + y; 49 | } 50 | else if (op == "-"){ 51 | return x - y; 52 | } 53 | else if (op == "*"){ 54 | return x * y; 55 | } 56 | else if (op == "/"){ 57 | return x / y; 58 | } 59 | } 60 | }; 61 | -------------------------------------------------------------------------------- /excelSheetColumnNumber/excelSheetColumnNumber.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/excel-sheet-column-number/ 2 | // Author : weekend27 3 | // Date : 2015-12-26 4 | 5 | /********************************************************************************** 6 | 7 | Related to question Excel Sheet Column Title 8 | 9 | Given a column title as appear in an Excel sheet, return its corresponding column number. 10 | 11 | For example: 12 | 13 | A -> 1 14 | B -> 2 15 | C -> 3 16 | ... 17 | Z -> 26 18 | AA -> 27 19 | AB -> 28 20 | 21 | **********************************************************************************/ 22 | 23 | // How to do it: 24 | // look at the code 25 | 26 | class Solution { 27 | public: 28 | int titleToNumber(string s) { 29 | int res = 0; 30 | for (auto c : s){ 31 | res = 26 * res + (c - 'A' + 1); 32 | } 33 | return res; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /excelSheetColumnTitle/excelSheetColumnTitle.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/excel-sheet-column-title/ 2 | // Author : weekend27 3 | // Date : 2015-12-25 4 | 5 | /********************************************************************************** 6 | 7 | Given a positive integer, return its corresponding column title as appear in an Excel sheet. 8 | 9 | For example: 10 | 11 | 1 -> A 12 | 2 -> B 13 | 3 -> C 14 | ... 15 | 26 -> Z 16 | 27 -> AA 17 | 28 -> AB 18 | 19 | **********************************************************************************/ 20 | 21 | // How to do it: 22 | // ref: http://yucoding.blogspot.jp/2015/06/leetcode-question-excel-sheet-column.html 23 | 24 | class Solution { 25 | public: 26 | string convertToTitle(int n) { 27 | string res = ""; 28 | while (n > 0){ 29 | if (n % 26 == 0){ 30 | res = 'Z' + res; 31 | n = n / 26 - 1; 32 | } 33 | else{ 34 | res = char(n%26 - 1 + 'A') + res; 35 | n /= 26; 36 | } 37 | } 38 | return res; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /factorialTrailingZeroes/factorialTrailingZeroes.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/factorial-trailing-zeroes/ 2 | // Author : weekend27 3 | // Date : 2015-12-25 4 | 5 | /********************************************************************************** 6 | 7 | Given an integer n, return the number of trailing zeroes in n!. 8 | 9 | Note: Your solution should be in logarithmic time complexity. 10 | 11 | **********************************************************************************/ 12 | 13 | // How to do it: 14 | // ref: https://leetcode.com/discuss/20691/my-explanation-of-the-log-n-solution 15 | 16 | 17 | class Solution { 18 | public: 19 | int trailingZeroes(int n) { 20 | int cnt = 0; 21 | while(n > 0){ 22 | cnt += n/5; 23 | n /= 5; 24 | } 25 | return cnt; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /findMinimumInRotatedSortedArray/findMinimumInRotatedSortedArray.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ 2 | // Author : weekend27 3 | // Date : 2016-01-16 4 | 5 | /********************************************************************************** 6 | 7 | Suppose a sorted array is rotated at some pivot unknown to you beforehand. 8 | 9 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 10 | 11 | Find the minimum element. 12 | 13 | You may assume no duplicate exists in the array. 14 | 15 | **********************************************************************************/ 16 | 17 | // How to do it: 18 | // binary search 19 | 20 | class Solution { 21 | public: 22 | int findMin(vector& nums) { 23 | int start = 0, end = nums.size() - 1; 24 | while (start < end) { 25 | int mid = start + (end - start) / 2; 26 | if (nums[mid] < nums[end]) { 27 | end = mid; 28 | } else { 29 | start = mid + 1; 30 | } 31 | } 32 | return nums[start]; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /findMinimumInRotatedSortedArray/findMinimumInRotatedSortedArrayII.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/ 2 | // Author : weekend27 3 | // Date : 2016-01-16 4 | 5 | /********************************************************************************** 6 | 7 | Suppose a sorted array is rotated at some pivot unknown to you beforehand. 8 | 9 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 10 | 11 | Find the minimum element. 12 | 13 | The array may contain duplicates. 14 | 15 | **********************************************************************************/ 16 | 17 | // How to do it: 18 | // binary search 19 | // when nums[mid] == nums[end], exclude nums[end] 20 | 21 | class Solution { 22 | public: 23 | int findMin(vector& nums) { 24 | int start = 0, end = nums.size() - 1; 25 | while (start < end) { 26 | int mid = start + (end - start) / 2; 27 | if (nums[mid] < nums[end]) { 28 | end = mid; 29 | } 30 | else if (nums[mid] > nums[end]) { 31 | start = mid + 1; 32 | } 33 | else { 34 | end--; 35 | } 36 | } 37 | return nums[start]; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /firstMissingPositive/firstMissingPositive.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/first-missing-positive/ 2 | // Author : weekend27 3 | // Date : 2016-04-07 4 | 5 | /********************************************************************************** 6 | 7 | Given an unsorted integer array, find the first missing positive integer. 8 | 9 | For example, 10 | Given [1,2,0] return 3, 11 | and [3,4,-1,1] return 2. 12 | 13 | Your algorithm should run in O(n) time and uses constant space. 14 | 15 | **********************************************************************************/ 16 | 17 | // How to do it: 18 | // ref: https://leetcode.com/discuss/28531/o-1-space-java-solution 19 | // ref: http://blog.csdn.net/kenden23/article/details/17099987 20 | // ref: http://www.cnblogs.com/AnnieKim/archive/2013/04/21/3034631.html 21 | 22 | public class Solution { 23 | public int firstMissingPositive(int[] nums) { 24 | int i = 0; 25 | while (i < nums.length) { 26 | if (nums[i] <= 0 || nums[i] > nums.length || nums[i] == i+1) { 27 | i++; 28 | } else if (nums[nums[i]-1] != nums[i]) { 29 | swap(nums, nums[i]-1, i); 30 | } else { 31 | i++; 32 | } 33 | } 34 | i = 0; 35 | while (i < nums.length && nums[i] == i+1) { 36 | i++; 37 | } 38 | return i+1; 39 | } 40 | 41 | private void swap(int[] nums, int i, int j) { 42 | nums[i] = nums[i] ^ nums[j]; 43 | nums[j] = nums[i] ^ nums[j]; 44 | nums[i] = nums[i] ^ nums[j]; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /generateParentheses/generateParentheses.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/generate-parentheses/ 2 | // Author : weekend27 3 | // Date : 2015-12-17 4 | 5 | /********************************************************************************** 6 | 7 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 8 | 9 | For example, given n = 3, a solution set is: 10 | 11 | "((()))", "(()())", "(())()", "()(())", "()()()" 12 | 13 | **********************************************************************************/ 14 | 15 | // How to do it: 16 | // 典型的递归。一步步构造字符串。当左括号出现次数& result, string& sample, int deep, int n, int leftNum, int rightNum){ 22 | if (deep == 2*n){ 23 | result.push_back(sample); 24 | return; 25 | } 26 | if (leftNum < n){ 27 | sample.push_back('('); 28 | combinationPar(result, sample, deep+1, n, leftNum+1, rightNum); 29 | sample.resize(sample.size()-1); 30 | } 31 | if (rightNum < leftNum){ 32 | sample.push_back(')'); 33 | combinationPar(result, sample, deep+1, n, leftNum, rightNum+1); 34 | sample.resize(sample.size()-1); 35 | } 36 | } 37 | vector generateParenthesis(int n) { 38 | vector result; 39 | string sample; 40 | if (n != 0){ 41 | combinationPar(result, sample, 0, n, 0, 0); 42 | } 43 | return result; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /grayCode/grayCode.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/gray-code/ 2 | // Author : weekend27 3 | // Date : 2015-12-28 4 | 5 | /********************************************************************************** 6 | 7 | The gray code is a binary numeral system where two successive values differ in only one bit. 8 | 9 | Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0. 10 | 11 | For example, given n = 2, return [0,1,3,2]. Its gray code sequence is: 12 | 13 | 00 - 0 14 | 01 - 1 15 | 11 - 3 16 | 10 - 2 17 | Note: 18 | For a given n, a gray code sequence is not uniquely defined. 19 | 20 | For example, [0,2,3,1] is also a valid gray code sequence according to the above definition. 21 | 22 | For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that. 23 | 24 | **********************************************************************************/ 25 | 26 | // How to do it: 27 | // ref: http://bangbingsyb.blogspot.jp/2014/11/leetcode-gray-code.html 28 | /* 29 | 例举grey code序列,并找规律 : 30 | n = 0: 0 31 | n = 1: 0, 1 32 | n = 2: 00, 01, 11, 10 (0, 1, 3, 2) 33 | n = 3: 000, 001, 011, 010, 110, 111, 101, 100 (0, 1, 3, 2, 6, 7, 5, 4) 34 | 以n = 3为例,grey code中前4个包括了n = 2的所有gray code。后4个则是前4个逆序后加上2^2。 35 | 36 | 推广:n = i的grey code的前一半包括了n = i-1的所有grey code,而后一半则为前一半逆序后家上2^(i-1)。 37 | */ 38 | 39 | class Solution { 40 | public: 41 | vector grayCode(int n) { 42 | vector grayVec; 43 | if (n < 0){ 44 | return grayVec; 45 | } 46 | grayVec.push_back(0); 47 | int inc = 1; 48 | for (int i = 1; i <= n; i++){ 49 | for (int j = grayVec.size() - 1; j >= 0; j--){ 50 | grayVec.push_back(grayVec[j] + inc); 51 | } 52 | inc = inc << 1; 53 | } 54 | return grayVec; 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /groupAnagrams/groupAnagrams.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/anagrams/ 2 | // Author : weekend27 3 | // Date : 2015-12-16 4 | 5 | /********************************************************************************** 6 | 7 | Given an array of strings, group anagrams together. 8 | 9 | For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], 10 | Return: 11 | 12 | [ 13 | ["ate", "eat","tea"], 14 | ["nat","tan"], 15 | ["bat"] 16 | ] 17 | Note: 18 | For the return value, each inner list's elements must follow the lexicographic order. 19 | All inputs will be in lower-case. 20 | 21 | **********************************************************************************/ 22 | 23 | // How to do it: 24 | // first sort str[i], then hash map, then print the second element of hash map 25 | 26 | 27 | class Solution { 28 | public: 29 | string getCode(string s){ 30 | sort(s.begin(), s.end()); 31 | return s; 32 | } 33 | vector> groupAnagrams(vector& strs) { 34 | 35 | vector> results; 36 | int size = strs.size(); 37 | if(size == 0){ 38 | return results; 39 | } 40 | if(size == 1){ 41 | results.push_back(strs); 42 | return results; 43 | } 44 | 45 | map> head; 46 | 47 | for(int i = 0; i < size; ++i){ 48 | head[getCode(strs[i])].push_back(strs[i]); 49 | } 50 | 51 | map >::iterator itor = head.begin(), end = head.end(); 52 | 53 | for(; itor != end; ++itor){ 54 | sort(itor->second.begin(), itor->second.end()); 55 | results.push_back(itor->second); 56 | } 57 | return results; 58 | } 59 | }; 60 | -------------------------------------------------------------------------------- /h-Index/h-Index.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/h-index/ 2 | // Author : weekend27 3 | // Date : 2015-12-16 4 | 5 | /********************************************************************************** 6 | 7 | Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index. 8 | 9 | According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each." 10 | 11 | For example, given citations = [3, 0, 6, 1, 5], which means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, his h-index is 3. 12 | 13 | Note: If there are several possible values for h, the maximum one is taken as the h-index. 14 | 15 | **********************************************************************************/ 16 | 17 | // How to do it: 18 | // binary search 19 | 20 | 21 | 22 | class Solution { 23 | public: 24 | int hIndex(vector& citations) { 25 | sort(citations.begin(),citations.end()); 26 | int len = citations.size(); 27 | int start = 0; 28 | int end = len; 29 | 30 | while(start < end) 31 | { 32 | int mid = start + (end - start) / 2; 33 | 34 | if(len - mid <= citations[mid]) 35 | { 36 | if(mid == 0 || len - mid + 1 > citations[mid - 1]) 37 | { 38 | return (min((int)len - mid,citations[mid])); 39 | } 40 | 41 | end = mid; 42 | } 43 | 44 | if(len - mid > citations[mid]) 45 | { 46 | start = mid + 1; 47 | } 48 | } 49 | 50 | return 0; 51 | } 52 | }; 53 | -------------------------------------------------------------------------------- /h-Index/h-IndexII.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/h-index-ii/ 2 | // Author : weekend27 3 | // Date : 2015-12-29 4 | 5 | /********************************************************************************** 6 | 7 | Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm? 8 | 9 | Hint: 10 | 11 | Expected runtime complexity is in O(log n) and the input is sorted. 12 | 13 | **********************************************************************************/ 14 | 15 | // How to do it: 16 | // binary search 17 | 18 | 19 | class Solution { 20 | public: 21 | int hIndex(vector& citations) { 22 | int n = citations.size(); 23 | int l = 0, r = n - 1; 24 | while (l <= r){ 25 | int m = l + (r - l) / 2; 26 | if (citations[m] < n - m){ 27 | l = m + 1; 28 | } 29 | else { 30 | r = m - 1; 31 | } 32 | } 33 | return n - l; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /h-Index/h-Index_1.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/h-index/ 2 | // Author : weekend27 3 | // Date : 2015-12-16 4 | 5 | /********************************************************************************** 6 | 7 | Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index. 8 | 9 | According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each." 10 | 11 | For example, given citations = [3, 0, 6, 1, 5], which means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, his h-index is 3. 12 | 13 | Note: If there are several possible values for h, the maximum one is taken as the h-index. 14 | 15 | **********************************************************************************/ 16 | 17 | // How to do it: 18 | // sort, then find the element 19 | 20 | class Solution { 21 | public: 22 | int hIndex(vector& citations) { 23 | if (citations.empty()){ 24 | return 0; 25 | } 26 | sort(citations.begin(),citations.end(), greater()); 27 | int len = citations.size(); 28 | int i = 0; 29 | for (i = 0; i < len; ++i){ 30 | if (i + 1 > citations[i]){ 31 | return i; 32 | } 33 | } 34 | return i; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /happyNumber/happyNumber.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/happy-number/ 2 | // Author : weekend27 3 | // Date : 2015-12-22 4 | 5 | /********************************************************************************** 6 | 7 | Write an algorithm to determine if a number is "happy". 8 | 9 | A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. 10 | 11 | Example: 19 is a happy number 12 | 13 | 12 + 92 = 82 14 | 82 + 22 = 68 15 | 62 + 82 = 100 16 | 12 + 02 + 02 = 1 17 | 18 | **********************************************************************************/ 19 | 20 | // How to do it: 21 | // ref: http://yucoding.blogspot.sg/2015/06/leetcode-question-happy-number.html 22 | /* 23 | This problem is not difficult, just be careful with the terminating condition. 24 | In my answer, I use a set to store the previous numbers in each round. 25 | If current number is in this set, then this number cannot be "happy" since there must have an endless loop. 26 | */ 27 | 28 | class Solution { 29 | public: 30 | bool isHappy(int n) { 31 | int res = 0; 32 | unordered_set hist; 33 | 34 | while (true){ 35 | if (n == 1){ 36 | return true; 37 | } 38 | 39 | while (n > 0){ 40 | res += (n%10) * (n%10); 41 | n /= 10; 42 | } 43 | 44 | if (hist.find(res) != hist.end()){ 45 | return false; 46 | } 47 | else{ 48 | hist.insert(res); 49 | n = res; 50 | res = 0; 51 | } 52 | } 53 | } 54 | }; 55 | -------------------------------------------------------------------------------- /implementStrStr()/implementStrStr().cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/implement-strstr/ 2 | // Author : weekend27 3 | // Date : 2015-12-17 4 | 5 | /********************************************************************************** 6 | 7 | Implement strStr(). 8 | 9 | Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 10 | 11 | **********************************************************************************/ 12 | 13 | // How to do it: 14 | // Brute Force 15 | // time complexity O(n*n) 16 | 17 | 18 | class Solution { 19 | public: 20 | int strStr(string haystack, string needle) { 21 | int m = haystack.length(); 22 | int n = needle.length(); 23 | int i, j; 24 | for (i = 0; i <= m-n; i++){ 25 | for (j = 0; j < n && haystack[i+j] == needle[j]; j++); 26 | if (j == n){ 27 | return i; 28 | } 29 | } 30 | return -1; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /insertionSortList/insertionSortList.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/sort-list/ 2 | // Author : weekend27 3 | // Date : 2015-12-10 4 | 5 | /********************************************************************************** 6 | 7 | 8 | 9 | **********************************************************************************/ 10 | 11 | // How to do it: 12 | // insertion sort 13 | // for the n+1 node, just traverse the previous n nodes and put it in the proper position 14 | 15 | 16 | /** 17 | * Definition for singly-linked list. 18 | * struct ListNode { 19 | * int val; 20 | * ListNode *next; 21 | * ListNode(int x) : val(x), next(NULL) {} 22 | * }; 23 | */ 24 | class Solution { 25 | public: 26 | ListNode* insertionSortList(ListNode* head) { 27 | if (head == NULL || head->next == NULL) 28 | return head; 29 | 30 | ListNode dummy(0); 31 | ListNode* p = &dummy; 32 | ListNode* curr = head; 33 | while (curr){ 34 | p = &dummy; 35 | while (p->next && p->next->val <= curr->val) 36 | p = p->next; 37 | 38 | ListNode* next = p->next; 39 | p->next = curr; 40 | curr = curr->next; 41 | p->next->next = next; 42 | } 43 | 44 | return dummy.next; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /integerToRoman/integerToRoman.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/integer-to-roman/ 2 | // Author : weekend27 3 | // Date : 2015-12-17 4 | 5 | /********************************************************************************** 6 | 7 | Given an integer, convert it to a roman numeral. 8 | 9 | Input is guaranteed to be within the range from 1 to 3999. 10 | 11 | **********************************************************************************/ 12 | 13 | // How to do it: 14 | // process digits according to different intervals 15 | 16 | class Solution { 17 | public: 18 | string intToRoman(int num) { 19 | char symbol[7] = {'I', 'V', 'X', 'L', 'C', 'D', 'M'}; 20 | string roman; 21 | int scale = 1000; 22 | for (int i = 6; i >= 0; i -= 2){ 23 | int digit = num / scale; 24 | if (digit != 0){ 25 | if (digit <= 3){ 26 | roman.append(digit, symbol[i]); 27 | } 28 | else if(digit == 4){ 29 | roman.append(1, symbol[i]); 30 | roman.append(1, symbol[i+1]); 31 | } 32 | else if(digit == 5){ 33 | roman.append(1, symbol[i+1]); 34 | } 35 | else if(digit <= 8){ 36 | roman.append(1, symbol[i+1]); 37 | roman.append(digit-5, symbol[i]); 38 | } 39 | else if(digit == 9){ 40 | roman.append(1, symbol[i]); 41 | roman.append(1, symbol[i+2]); 42 | } 43 | } 44 | num = num % scale; 45 | scale /= 10; 46 | } 47 | return roman; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /integerToRoman/integerToRoman.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/integer-to-roman/ 2 | // Author : weekend27 3 | // Date : 20156-04-26 4 | 5 | /********************************************************************************** 6 | 7 | Given an integer, convert it to a roman numeral. 8 | 9 | Input is guaranteed to be within the range from 1 to 3999. 10 | 11 | **********************************************************************************/ 12 | 13 | 14 | public class Solution { 15 | public String intToRoman(int num) { 16 | String[][] roman = { 17 | {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}, 18 | {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}, 19 | {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}, 20 | {"", "M", "MM", "MMM"} 21 | }; 22 | 23 | StringBuilder ret = new StringBuilder(); 24 | int digit = 0; 25 | while (num > 0) { 26 | int remain = num % 10; // remain part 27 | ret = ret.insert(0, roman[digit][remain]); // insert the remain part in the 0 index 28 | digit++; 29 | num /= 10; 30 | } 31 | String result = ret.toString(); 32 | return result; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /integerToRoman/integerToRoman2.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/integer-to-roman/ 2 | // Author : weekend27 3 | // Date : 20156-04-26 4 | 5 | /********************************************************************************** 6 | 7 | Given an integer, convert it to a roman numeral. 8 | 9 | Input is guaranteed to be within the range from 1 to 3999. 10 | 11 | **********************************************************************************/ 12 | 13 | public class Solution { 14 | public String intToRoman(int num) { 15 | String[] M = {"", "M", "MM", "MMM"}; 16 | String[] C = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; 17 | String[] X = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; 18 | String[] I = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; 19 | 20 | StringBuilder ret = new StringBuilder(); 21 | ret.append(M[num/1000]); 22 | ret.append(C[(num%1000)/100]); 23 | ret.append(X[(num%100)/10]); 24 | ret.append(I[num%10]); 25 | 26 | return ret.toString(); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /invertBinaryTree/invertBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/invert-binary-tree/ 2 | // Author : weekend27 3 | // Date : 2015-12-28 4 | 5 | /********************************************************************************** 6 | 7 | Invert a binary tree. 8 | 9 | 4 10 | / \ 11 | 2 7 12 | / \ / \ 13 | 1 3 6 9 14 | to 15 | 4 16 | / \ 17 | 7 2 18 | / \ / \ 19 | 9 6 3 1 20 | Trivia: 21 | This problem was inspired by this original tweet by Max Howell: 22 | Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off. 23 | 24 | **********************************************************************************/ 25 | 26 | // How to do it: 27 | // use a queue to do BFS 28 | 29 | /** 30 | * Definition for a binary tree node. 31 | * struct TreeNode { 32 | * int val; 33 | * TreeNode *left; 34 | * TreeNode *right; 35 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 36 | * }; 37 | */ 38 | class Solution { 39 | public: 40 | TreeNode* invertTree(TreeNode* root) { 41 | if (root == nullptr){ 42 | return root; 43 | } 44 | 45 | queue myQueue; // use a queue to do BFS 46 | myQueue.push(root); 47 | 48 | while (!myQueue.empty()){ 49 | TreeNode* node = myQueue.front(); 50 | myQueue.pop(); 51 | 52 | if (node->left != nullptr){ 53 | myQueue.push(node->left); 54 | } 55 | 56 | if (node->right != nullptr){ 57 | myQueue.push(node->right); 58 | } 59 | 60 | // invert left and right pointers 61 | TreeNode* tmp = node->left; 62 | node->left = node->right; 63 | node->right = tmp; 64 | } 65 | 66 | return root; 67 | } 68 | }; 69 | -------------------------------------------------------------------------------- /jumpGame/jumpGame.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/jump-game/ 2 | // Author : weekend27 3 | // Date : 2016-04-09 4 | 5 | /********************************************************************************** 6 | 7 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 8 | 9 | Each element in the array represents your maximum jump length at that position. 10 | 11 | Determine if you are able to reach the last index. 12 | 13 | For example: 14 | A = [2,3,1,1,4], return true. 15 | 16 | A = [3,2,1,0,4], return false. 17 | 18 | **********************************************************************************/ 19 | 20 | // How to do it: 21 | // ref: https://leetcode.com/discuss/11422/simplest-o-n-solution-with-constant-space 22 | // Idea is to work backwards from the last index. Keep track of the smallest index that can "jump" to the last index. 23 | // Check whether the current index can jump to this smallest index. 24 | 25 | public class Solution { 26 | public boolean canJump(int[] nums) { 27 | int n = nums.length; 28 | int last = n - 1; 29 | int i, j; 30 | for (i = n - 2; i >= 0; i--) { 31 | if (i + nums[i] >= last) last = i; 32 | } 33 | return last <= 0; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /jumpGame/jumpGameII.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/jump-game-ii/ 2 | // Author : weekend27 3 | // Date : 2016-04-09 4 | 5 | /********************************************************************************** 6 | 7 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 8 | 9 | Each element in the array represents your maximum jump length at that position. 10 | 11 | Your goal is to reach the last index in the minimum number of jumps. 12 | 13 | For example: 14 | Given array A = [2,3,1,1,4] 15 | 16 | The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.) 17 | 18 | Note: 19 | You can assume that you can always reach the last index. 20 | 21 | **********************************************************************************/ 22 | 23 | // How to do it: 24 | // ref: http://www.programcreek.com/2014/06/leetcode-jump-game-ii-java/ 25 | // This is an extension of Jump Game. The solution is similar, but we also track the maximum steps of last jump. 26 | 27 | public class Solution { 28 | public int jump(int[] nums) { 29 | if (nums == null || nums.length == 0) { 30 | return -1; 31 | } 32 | 33 | int lastReach = 0; 34 | int reach = 0; 35 | int step = 0; 36 | 37 | for (int i = 0; i <= reach && i < nums.length; ++i) { 38 | // when last jump can not read current i, increase the step by 1 39 | if (i > lastReach) { 40 | step++; 41 | lastReach = reach; 42 | } 43 | // update the max jump 44 | reach = Math.max(reach, nums[i] + i); 45 | } 46 | 47 | if (reach < nums.length - 1) { 48 | return -1; 49 | } 50 | 51 | return step; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /jumpGame/jumpGame_2.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/jump-game/ 2 | // Author : weekend27 3 | // Date : 2016-04-09 4 | 5 | /********************************************************************************** 6 | 7 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 8 | 9 | Each element in the array represents your maximum jump length at that position. 10 | 11 | Determine if you are able to reach the last index. 12 | 13 | For example: 14 | A = [2,3,1,1,4], return true. 15 | 16 | A = [3,2,1,0,4], return false. 17 | 18 | **********************************************************************************/ 19 | 20 | // How to do it: 21 | // ref: http://www.programcreek.com/2014/03/leetcode-jump-game-java/ 22 | /* We can track the maximum index that can be reached. The key to solve this problem is to find: 23 | * 1) when the current position can not reach next position (return false) , 24 | * 2) when the maximum index can reach the end (return true). 25 | * The largest index that can be reached is: i + A[i]. 26 | */ 27 | 28 | public class Solution { 29 | public boolean canJump(int[] nums) { 30 | if (nums.length < 2) { 31 | return true; 32 | } 33 | 34 | int max = nums[0]; // max stands for the largest index that can be reached 35 | 36 | for (int i = 0; i < nums.length - 1; ++i) { 37 | // if not enough to go to next 38 | if (max <= i && nums[i] == 0) { 39 | return false; 40 | } 41 | 42 | // update max 43 | if (i + nums[i] > max) { 44 | max = i + nums[i]; 45 | } 46 | 47 | // max is enough to go to the end 48 | if (max >= nums.length - 1) { 49 | return true; 50 | } 51 | } 52 | 53 | return false; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /kthLargestElementInAnArray/kthLargestElementInAnArray.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/kth-largest-element-in-an-array/ 2 | // Author : weekend27 3 | // Date : 2015-12-20 4 | 5 | /********************************************************************************** 6 | 7 | Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. 8 | 9 | For example, 10 | Given [3,2,1,5,6,4] and k = 2, return 5. 11 | 12 | Note: 13 | You may assume k is always valid, 1 ≤ k ≤ array's length. 14 | 15 | **********************************************************************************/ 16 | 17 | // How to do it: 18 | // sort, find the one by index 19 | 20 | class Solution { 21 | public: 22 | int findKthLargest(vector& nums, int k) { 23 | int N = nums.size(); 24 | sort(nums.begin(), nums.end()); 25 | return nums[N - k]; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /largestNumber/largestNumber.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/largest-number/ 2 | // Author : weekend27 3 | // Date : 2015-12-15 4 | 5 | /********************************************************************************** 6 | 7 | Given a list of non negative integers, arrange them such that they form the largest number. 8 | 9 | For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. 10 | 11 | Note: The result may be very large, so you need to return a string instead of an integer. 12 | 13 | **********************************************************************************/ 14 | 15 | // How to do it: 16 | // special sort 17 | // 贪心算法 18 | // ref:http://www.w2bc.com/Article/19411 19 | 20 | class Solution { 21 | public: 22 | static bool compare(const string &a, const string &b){ 23 | string ab = a + b; 24 | string ba = b + a; 25 | return ab > ba; 26 | } 27 | string largestNumber(vector& nums) { 28 | int len = nums.size(); 29 | vector vec; 30 | if (len == 0){ 31 | return NULL; 32 | } 33 | 34 | int zeroCount = 0; 35 | for (int i = 0; i < len; i++){ 36 | if (nums[i] == 0){ 37 | zeroCount++; 38 | } 39 | char str[len-1]; 40 | sprintf(str, "%d", nums[i]); 41 | vec.push_back(str); 42 | } 43 | 44 | if (zeroCount == len){ 45 | return "0"; 46 | } 47 | 48 | if (len == 1){ 49 | return vec[0]; 50 | } 51 | 52 | sort(vec.begin(), vec.end(), compare); 53 | 54 | string result; 55 | for (int i = 0; i < len; i++){ 56 | result += vec[i]; 57 | } 58 | return result; 59 | } 60 | }; 61 | -------------------------------------------------------------------------------- /lengthOfLastWord/lengthOfLastWord.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/length-of-last-word/ 2 | // Author : weekend27 3 | // Date : 2015-12-16 4 | 5 | /********************************************************************************** 6 | 7 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. 8 | 9 | If the last word does not exist, return 0. 10 | 11 | Note: A word is defined as a character sequence consists of non-space characters only. 12 | 13 | For example, 14 | Given s = "Hello World", 15 | return 5. 16 | 17 | **********************************************************************************/ 18 | 19 | // How to do it: 20 | // from the end to count, pretty easy 21 | 22 | 23 | class Solution { 24 | public: 25 | int lengthOfLastWord(string s) { 26 | int len = s.size(); 27 | int cnt = 0; 28 | for (int i = len - 1; i >= 0; i--){ 29 | if (s[i] == ' '){ 30 | if (cnt == 0){ 31 | continue; 32 | } else { 33 | return cnt; 34 | } 35 | } 36 | cnt++; 37 | } 38 | return cnt; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /letterCombinationsOfAPhoneNumber/letterCombinationsOfAPhoneNumber.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/letter-combinations-of-a-phone-number/ 2 | // Author : weekend27 3 | // Date : 2016-01-05 4 | 5 | /********************************************************************************** 6 | 7 | Given a digit string, return all possible letter combinations that the number could represent. 8 | 9 | A mapping of digit to letters (just like on the telephone buttons) is given below. 10 | 11 | Input:Digit string "23" 12 | Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. 13 | Note: 14 | Although the above answer is in lexicographical order, your answer could be in any order you want. 15 | 16 | **********************************************************************************/ 17 | 18 | // How to do it: 19 | // ref: http://fisherlei.blogspot.jp/2012/12/leetcode-letter-combinations-of-phone.html 20 | 21 | 22 | class Solution { 23 | public: 24 | vector letterCombinations(string digits) { 25 | vector trans = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; 26 | vector set; 27 | string seq; 28 | if (digits == "") { 29 | return set; 30 | } 31 | generator(trans, digits, 0, seq, set); 32 | return set; 33 | } 34 | 35 | void generator(vector& trans, string& digits, int deep, string& result, vector& set) { 36 | if (deep == digits.size()) { 37 | set.push_back(result); 38 | return; 39 | } 40 | 41 | int curDig = digits[deep] - 48; 42 | for (int i = 0; i < trans[curDig].size(); i++) { 43 | result.push_back(trans[curDig][i]); 44 | generator(trans, digits, deep+1, result, set); 45 | result.resize(result.size() - 1); 46 | } 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /linkedListCycle/linkedListCycle.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/linked-list-cycle/ 2 | // Author : weekend27 3 | // Date : 2015-12-09 4 | 5 | /********************************************************************************** 6 | 7 | Given a linked list, determine if it has a cycle in it. 8 | 9 | Follow up: 10 | Can you solve it without using extra space? 11 | 12 | **********************************************************************************/ 13 | 14 | // How to do it: 15 | // two poiters go, one fast, the other slow, if they meet some time, the list has cycle. 16 | 17 | /** 18 | * Definition for singly-linked list. 19 | * struct ListNode { 20 | * int val; 21 | * ListNode *next; 22 | * ListNode(int x) : val(x), next(NULL) {} 23 | * }; 24 | */ 25 | class Solution { 26 | public: 27 | bool hasCycle(ListNode *head) { 28 | // two pointers go ahead, one fast, the other slow, if they meet some time, then the list has cycle 29 | if(head == NULL || head->next == NULL){ 30 | return false; 31 | } 32 | 33 | ListNode* fast = head; 34 | ListNode* slow = head; 35 | 36 | while(fast->next != NULL && fast->next->next != NULL){ 37 | fast = fast->next->next; 38 | slow = slow->next; 39 | if (slow == fast){ 40 | return true; 41 | } 42 | } 43 | 44 | return false; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /linkedListCycle/linkedListCycleII.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/linked-list-cycle-ii/ 2 | // Author : weekend27 3 | // Date : 2015-12-09 4 | 5 | /********************************************************************************** 6 | 7 | Given a linked list, return the node where the cycle begins. If there is no cycle, return null. 8 | 9 | Note: Do not modify the linked list. 10 | 11 | Follow up: 12 | Can you solve it without using extra space? 13 | 14 | **********************************************************************************/ 15 | 16 | // How to do it: 17 | // two poiters go, one fast, the other slow, if they meet some time, the list has cycle. 18 | // when they meet, let the slow one go back to head, and meet again. 19 | // the analysis is here:https://siddontang.gitbooks.io/leetcode-solution/content/linked_list/linked_list_cycle.html 20 | 21 | /** 22 | * Definition for singly-linked list. 23 | * struct ListNode { 24 | * int val; 25 | * ListNode *next; 26 | * ListNode(int x) : val(x), next(NULL) {} 27 | * }; 28 | */ 29 | class Solution { 30 | public: 31 | ListNode *detectCycle(ListNode *head) { 32 | if (head == NULL || head->next == NULL){ 33 | return NULL; 34 | } 35 | 36 | ListNode* fast = head; 37 | ListNode* slow = head; 38 | 39 | while (fast->next != NULL && fast->next->next != NULL){ 40 | fast = fast->next->next; 41 | slow = slow->next; 42 | if (fast == slow){ 43 | slow = head; 44 | while(slow != fast){ 45 | slow = slow->next; 46 | fast = fast->next; 47 | } 48 | return slow; 49 | } 50 | } 51 | return NULL; 52 | } 53 | }; 54 | -------------------------------------------------------------------------------- /longestCommonPrefix/longestCommonPrefix.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/longest-common-prefix/ 2 | // Author : weekend27 3 | // Date : 2015-12-16 4 | 5 | /********************************************************************************** 6 | 7 | Write a function to find the longest common prefix string amongst an array of strings. 8 | 9 | **********************************************************************************/ 10 | 11 | // How to do it: 12 | // traverse the string array, use the current prefix to map the next string in order to produce a new prefix 13 | 14 | 15 | class Solution { 16 | public: 17 | string longestCommonPrefix(vector& strs) { 18 | string cmp; 19 | if (strs.size() == 0){ 20 | return cmp; 21 | } 22 | cmp = strs[0]; 23 | for (int i = 0; i < strs.size(); i++){ 24 | string prefix; 25 | int k = 0; 26 | while (k < cmp.size() && k < strs[i].size()){ 27 | if (cmp[k] != strs[i][k]){ 28 | break; 29 | } 30 | prefix.append(1, cmp[k]); 31 | k++; 32 | } 33 | cmp.clear(); 34 | cmp.append(prefix.c_str()); 35 | } 36 | return cmp; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /longestCommonPrefix/longestCommonPrefix.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/longest-common-prefix/ 2 | // Author : weekend27 3 | // Date : 2016-04-26 4 | 5 | /********************************************************************************** 6 | 7 | Write a function to find the longest common prefix string amongst an array of strings. 8 | 9 | **********************************************************************************/ 10 | 11 | // How to do it: 12 | // traverse the string array, use the current prefix to map the next string in order to produce a new prefix 13 | 14 | 15 | public class Solution { 16 | public String longestCommonPrefix(String[] strs) { 17 | // case condition 18 | if (strs == null | strs.length == 0) { 19 | return ""; 20 | } 21 | 22 | String pre = strs[0]; 23 | for (int i = 1; i < strs.length; ++i) { 24 | while (!strs[i].startsWith(pre)) { // current string does not have the prefix, so minimize the prefix until it becomes the prefix 25 | pre = pre.substring(0, pre.length() - 1); 26 | } 27 | } 28 | return pre; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /longestPalindromicSubstring/longestPalindromicSubstring.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/longest-palindromic-substring/ 2 | // Author : weekend27 3 | // Date : 2016-04-11 4 | 5 | /********************************************************************************** 6 | 7 | Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring. 8 | 9 | **********************************************************************************/ 10 | 11 | // How to do it: 12 | // see the code 13 | 14 | public class Solution { 15 | private int lo, maxLen; 16 | public String longestPalindrome(String s) { 17 | if (s.length() < 2) { 18 | return s; 19 | } 20 | 21 | for (int i = 0; i < s.length() - 1; ++i) { 22 | extendPalindrome(s, i, i); // assume odd length 23 | extendPalindrome(s, i, i+1); // assume even length 24 | } 25 | return s.substring(lo, lo + maxLen); 26 | } 27 | 28 | private void extendPalindrome(String s, int j, int k) { 29 | while (j >= 0 && k < s.length() && s.charAt(j) == s.charAt(k)) { 30 | j--; 31 | k++; 32 | } 33 | if (maxLen < k - j - 1) { 34 | lo = j + 1; 35 | maxLen = k - j - 1; 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /longestSubstringWithoutRepeatingCharacters/longestSubstringWithoutRepeatingCharacters.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/longest-substring-without-repeating-characters/ 2 | // Author : weekend27 3 | // Date : 2015-12-23 4 | 5 | /********************************************************************************** 6 | 7 | Given a string, find the length of the longest substring without repeating characters. 8 | For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1. 9 | 10 | **********************************************************************************/ 11 | 12 | // How to do it: 13 | // Generate an array to record the last position of current character. 14 | // Count and update the left bound, and calculate the maximum. 15 | // It will just cost constant space. 16 | 17 | class Solution { 18 | public: 19 | int lengthOfLongestSubstring(string s) { 20 | int maxLen = 0, left = 0; 21 | int sl = s.length(); 22 | int prev[300]; 23 | memset(prev, -1, sizeof(prev)); 24 | 25 | for (int i = 0; i < sl; i++){ 26 | if (prev[s[i]] >= left){ 27 | left = prev[s[i]] + 1; 28 | } 29 | prev[s[i]] = i; 30 | maxLen = max(maxLen, i - left + 1); 31 | } 32 | return maxLen; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /longestSubstringWithoutRepeatingCharacters/longestSubstringWithoutRepeatingCharacters.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/longest-substring-without-repeating-characters/ 2 | // Author : weekend27 3 | // Date : 2016-04-11 4 | 5 | /********************************************************************************** 6 | 7 | Given a string, find the length of the longest substring without repeating characters. 8 | For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1. 9 | 10 | **********************************************************************************/ 11 | 12 | // How to do it: 13 | // ref:https://leetcode.com/discuss/23883/11-line-simple-java-solution-o-n-with-explanation 14 | // hashmap, The variable "j" is used to indicate the index of first character of this substring. 15 | // If the repeated character's index is less than j itself, 16 | // which means the repeated character in the hash map is no longer available this time 17 | 18 | 19 | public class Solution { 20 | public int lengthOfLongestSubstring(String s) { 21 | if (s.length() == 0) return 0; 22 | HashMap map = new HashMap(); 23 | int max = 0; 24 | for (int i = 0, j = 0; i < s.length(); ++i) { 25 | if (map.containsKey(s.charAt(i))) { 26 | j = Math.max(j, map.get(s.charAt(i))+1); 27 | } 28 | map.put(s.charAt(i), i); 29 | max = Math.max(max, i-j+1); 30 | } 31 | return max; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /longestValidParentheses/longestValidParentheses.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/longest-valid-parentheses/ 2 | // Author : weekend27 3 | // Date : 2016-04-06 4 | 5 | /********************************************************************************** 6 | 7 | Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. 8 | 9 | For "(()", the longest valid parentheses substring is "()", which has length = 2. 10 | 11 | Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4. 12 | 13 | **********************************************************************************/ 14 | 15 | // How to do it: 16 | // ref: http://www.programcreek.com/2014/06/leetcode-longest-valid-parentheses-java/ 17 | 18 | public class Solution { 19 | public int longestValidParentheses(String s) { 20 | Stack stack = new Stack(); 21 | int result = 0; 22 | 23 | for (int i = 0; i < s.length(); i++) { 24 | char c = s.charAt(i); 25 | if (c == '(') { 26 | int[] a = {i, 0}; 27 | stack.push(a); 28 | } else { 29 | if (stack.empty() || stack.peek()[1] == 1) { 30 | int[] a = {i, 1}; 31 | stack.push(a); 32 | } else { 33 | stack.pop(); 34 | int currentLen = 0; 35 | if (stack.empty()) { 36 | currentLen = i + 1; 37 | } else { 38 | currentLen = i - stack.peek()[0]; 39 | } 40 | result = Math.max(result, currentLen); 41 | } 42 | } 43 | } 44 | 45 | return result; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /majorityElement/majorityElement.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/majority-element/ 2 | // Author : weekend27 3 | // Date : 2015-12-03 4 | 5 | /********************************************************************************** 6 | 7 | Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. 8 | 9 | You may assume that the array is non-empty and the majority element always exist in the array. 10 | 11 | **********************************************************************************/ 12 | 13 | // How to do it: 14 | // when you find two different elements, delete them together. 15 | // http://www.cnblogs.com/ganganloveu/p/4177690.html 16 | 17 | 18 | 19 | class Solution { 20 | public: 21 | int majorityElement(vector& nums) { 22 | int candidate = 0; 23 | int count = 0; 24 | for (int i = 0; i < nums.size(); i++){ 25 | if (count == 0){ 26 | candidate = nums[i]; 27 | count = 1; 28 | }else{ 29 | if (nums[i] == candidate){ 30 | count++; 31 | }else{ 32 | count--; 33 | } 34 | } 35 | } 36 | return candidate; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /maximumDepthOfBinaryTree/maximumDepthOfBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/maximum-depth-of-binary-tree/ 2 | // Author : weekend27 3 | // Date : 2015-12-10 4 | 5 | /********************************************************************************** 6 | 7 | Given a binary tree, find its maximum depth. 8 | 9 | The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 10 | 11 | **********************************************************************************/ 12 | 13 | // How to do it: 14 | // recursively traverse the binary tree, when reaching leaf node , record the depth 15 | 16 | /** 17 | * Definition for a binary tree node. 18 | * struct TreeNode { 19 | * int val; 20 | * TreeNode *left; 21 | * TreeNode *right; 22 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 23 | * }; 24 | */ 25 | class Solution { 26 | public: 27 | int num; 28 | int maxDepth(TreeNode* root) { 29 | if (!root) 30 | return 0; 31 | 32 | // Initialize num to be min 33 | num = numeric_limits::min(); 34 | travel(root, 1); 35 | return num; 36 | } 37 | 38 | void travel(TreeNode* node, int level){ 39 | // if no left child and no right child, it reaches leaf node 40 | if (!node->left && !node->right){ 41 | num = max(num, level); 42 | return; 43 | } 44 | 45 | if (node->left) 46 | travel(node->left, level+1); 47 | 48 | if (node->right) 49 | travel(node->right, level+1); 50 | 51 | } 52 | }; 53 | -------------------------------------------------------------------------------- /maximumGap/maximumGap.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/maximum-gap/ 2 | // Author : weekend27 3 | // Date : 2015-12-15 4 | 5 | /********************************************************************************** 6 | 7 | Given an unsorted array, find the maximum difference between the successive elements in its sorted form. 8 | 9 | Try to solve it in linear time/space. 10 | 11 | Return 0 if the array contains less than 2 elements. 12 | 13 | You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range. 14 | 15 | **********************************************************************************/ 16 | 17 | // How to do it: 18 | // first sort, time O(log(n)), then compare the successive elements 19 | // time over O(n) 20 | // i will make it better in the future 21 | 22 | 23 | 24 | class Solution { 25 | public: 26 | int maximumGap(vector& nums) { 27 | if (nums.empty() || nums.size() == 1){ 28 | return 0; 29 | } 30 | sort(nums.begin(), nums.end()); 31 | int maximum = 0; 32 | for (int i = 1; i < nums.size(); i++){ 33 | if (nums[i] - nums[i-1] > maximum){ 34 | maximum = nums[i] - nums[i-1]; 35 | } 36 | } 37 | return maximum; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /medianOfTwoSortedArrays/medianOfTwoSortedArrays.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/median-of-two-sorted-arrays/ 2 | // Author : weekend27 3 | // Date : 2015-12-20 4 | 5 | /********************************************************************************** 6 | 7 | There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). 8 | 9 | **********************************************************************************/ 10 | 11 | // How to do it: 12 | // merge 13 | // time complexity: O(m+n) 14 | 15 | class Solution { 16 | public: 17 | double findMedianSortedArrays(vector& nums1, vector& nums2) { 18 | int len1 = nums1.size(); 19 | int len2 = nums2.size(); 20 | int pa = 0, pb = 0; 21 | vector tmp; 22 | 23 | while (pa < len1 || pb < len2){ 24 | if (pa == len1){ 25 | tmp.push_back(nums2[pb++]); 26 | continue; 27 | } 28 | if (pb == len2){ 29 | tmp.push_back(nums1[pa++]); 30 | continue; 31 | } 32 | if (nums1[pa] > nums2[pb]){ 33 | tmp.push_back(nums2[pb++]); 34 | } 35 | else{ 36 | tmp.push_back(nums1[pa++]); 37 | } 38 | } 39 | 40 | int len = tmp.size(); 41 | if (len % 2 == 1){ 42 | return tmp[len/2]; 43 | } 44 | else { 45 | return (tmp[len/2] + tmp[len/2 - 1]) / 2.0; 46 | } 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /medianOfTwoSortedArrays/medianOfTwoSortedArrays.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/median-of-two-sorted-arrays/ 2 | // Author : weekend27 3 | // Date : 2016-04-11 4 | 5 | /********************************************************************************** 6 | 7 | There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). 8 | 9 | **********************************************************************************/ 10 | 11 | // How to do it: 12 | // The key point of this problem is to ignore 1/4 part of A and B each step recursively by comparing the median of remaining A and B: 13 | // if (aMid < bMid) Keep [aRight + b] 14 | // else Keep [bRight + a] 15 | 16 | 17 | public class Solution { 18 | public double findMedianSortedArrays(int[] nums1, int[] nums2) { 19 | int len1 = nums1.length; 20 | int len2 = nums2.length; 21 | int l = (len1 + len2 + 1) >> 1; 22 | int r = (len1 + len2 + 2) >> 1; 23 | return (getkth(nums1, 0, nums2, 0, l) + getkth(nums1, 0, nums2, 0, r)) / 2.0; 24 | } 25 | 26 | private int getkth(int[] A, int aStart, int[] B, int bStart, int k) { 27 | if (aStart > A.length - 1) return B[bStart + k - 1]; 28 | if (bStart > B.length - 1) return A[aStart + k - 1]; 29 | if (k == 1) return Math.min(A[aStart], B[bStart]); 30 | 31 | int aMid = Integer.MAX_VALUE, bMid = Integer.MAX_VALUE; 32 | if (aStart + k/2 - 1 < A.length) aMid = A[aStart + k/2 - 1]; 33 | if (bStart + k/2 - 1 < B.length) bMid = B[bStart + k/2 - 1]; 34 | 35 | if (aMid < bMid) 36 | return getkth(A, aStart + k/2, B, bStart, k - k/2); // Check: aRight + bLeft 37 | else 38 | return getkth(A, aStart, B, bStart + k/2, k - k/2); // Check: bRight + aLeft 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /mergeIntervals/mergeIntervals.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/merge-intervals/ 2 | // Author : weekend27 3 | // Date : 2015-12-15 4 | 5 | /********************************************************************************** 6 | 7 | Given a collection of intervals, merge all overlapping intervals. 8 | 9 | For example, 10 | Given [1,3],[2,6],[8,10],[15,18], 11 | return [1,6],[8,10],[15,18]. 12 | 13 | **********************************************************************************/ 14 | 15 | // How to do it: 16 | // first sort the start, then check the corner 17 | 18 | 19 | /** 20 | * Definition for an interval. 21 | * struct Interval { 22 | * int start; 23 | * int end; 24 | * Interval() : start(0), end(0) {} 25 | * Interval(int s, int e) : start(s), end(e) {} 26 | * }; 27 | */ 28 | class Solution { 29 | public: 30 | static bool compareInterval(const Interval& a, const Interval& b){ 31 | return a.start < b.start; 32 | } 33 | vector merge(vector& intervals) { 34 | vector result; 35 | if (intervals.size() > 0){ 36 | sort(intervals.begin(), intervals.end(), Solution::compareInterval); 37 | Interval tmp = intervals.at(0); 38 | for (int i = 1; i < intervals.size(); i++){ 39 | if (intervals.at(i).end < tmp.start || intervals.at(i).start > tmp.end){ // no intervals 40 | result.push_back(tmp); 41 | tmp = intervals.at(i); 42 | } else { 43 | tmp.start = min(tmp.start, intervals.at(i).start); 44 | tmp.end = max(tmp.end, intervals.at(i).end); 45 | } 46 | } 47 | result.push_back(tmp); 48 | } 49 | return result; 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /mergeIntervals/mergeIntervals_1.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/merge-intervals/ 2 | // Author : weekend27 3 | // Date : 2016-03-22 4 | 5 | /********************************************************************************** 6 | 7 | Given a collection of intervals, merge all overlapping intervals. 8 | 9 | For example, 10 | Given [1,3],[2,6],[8,10],[15,18], 11 | return [1,6],[8,10],[15,18]. 12 | 13 | **********************************************************************************/ 14 | 15 | // How to do it: 16 | // ref: https://leetcode.com/discuss/50164/my-c-o-nlogn-solution-580ms 17 | /* 18 | Just copy the input to res and do sorting (in ascending order of start). 19 | Then try to merge the sorted interval: cur is the last processed interval and i is the current to-be-processed interval. 20 | If cur is ahead of i and no overlapping, just copy i to cur+1, and update cur to cur+1, otherwise, merge interval cur and i and move to i+1. 21 | At last, we need to resize res to remove the redundent intervals. 22 | */ 23 | 24 | 25 | /** 26 | * Definition for an interval. 27 | * struct Interval { 28 | * int start; 29 | * int end; 30 | * Interval() : start(0), end(0) {} 31 | * Interval(int s, int e) : start(s), end(e) {} 32 | * }; 33 | */ 34 | class Solution { 35 | public: 36 | vector merge(vector& intervals) { 37 | vector res(intervals); 38 | int cur, i; 39 | if (intervals.size() > 1) { 40 | std::sort(res.begin(), res.end(), [](Interval a, Interval b){return a.start < b.start;}); 41 | for (cur = 0, i = 1; i < intervals.size(); ++i) { 42 | if (res[cur].end < res[i].start) res[++cur] = res[i]; // no overlapping, copy to cur+1 43 | else res[cur].end = max(res[cur].end, res[i].end); 44 | } 45 | res.resize(cur+1); // resize to remove redundant intervals 46 | } 47 | return res; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /mergeIntervals/mergeIntervals_2.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/merge-intervals/ 2 | // Author : weekend27 3 | // Date : 2015-12-15 4 | 5 | /********************************************************************************** 6 | 7 | Given a collection of intervals, merge all overlapping intervals. 8 | 9 | For example, 10 | Given [1,3],[2,6],[8,10],[15,18], 11 | return [1,6],[8,10],[15,18]. 12 | 13 | **********************************************************************************/ 14 | 15 | // How to do it: 16 | // first sort the start, then check the corner 17 | 18 | 19 | /** 20 | * Definition for an interval. 21 | * struct Interval { 22 | * int start; 23 | * int end; 24 | * Interval() : start(0), end(0) {} 25 | * Interval(int s, int e) : start(s), end(e) {} 26 | * }; 27 | */ 28 | class Solution { 29 | public: 30 | vector merge(vector& intervals) { 31 | if (intervals.empty()) return vector{}; 32 | vector res; 33 | sort(intervals.begin(), intervals.end(), [](Interval a, Interval b){return a.start < b.start;}); 34 | res.push_back(intervals[0]); 35 | for (int i = 0; i < intervals.size(); ++i) { 36 | if (res.back().end < intervals[i].start) { 37 | res.push_back(intervals[i]); 38 | } 39 | else { 40 | res.back().end = max(res.back().end, intervals[i].end); 41 | } 42 | } 43 | 44 | return res; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /mergeSortedArray/mergeSortedArray.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/merge-sorted-array/ 2 | // Author : weekend27 3 | // Date : 2015-12-02 4 | 5 | /********************************************************************************** 6 | 7 | Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 8 | 9 | Note: 10 | You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. 11 | The number of elements initialized in nums1 and nums2 are m and n respectively. 12 | 13 | **********************************************************************************/ 14 | 15 | // How to do it: 16 | // compare from the end to the start, and then put the larger one to the array nums1 17 | // time O(n+m) 18 | 19 | 20 | class Solution { 21 | public: 22 | void merge(vector& nums1, int m, vector& nums2, int n){ 23 | int index = m + n -1; 24 | int index1 = m - 1; 25 | int index2 = n - 1; 26 | while(0 <= index1 && 0 <= index2){ // two vectors traverse not done 27 | if(nums2[index2] > nums1[index1]) 28 | nums1[index--] = nums2[index2--]; 29 | else 30 | nums1[index--] = nums1[index1--]; 31 | } 32 | while(0 <= index1){ //only vector nums1 traverse not done 33 | nums1[index--] = nums1[index1--]; 34 | } 35 | while(0 <= index2){ //only vector nums2 traverse not done 36 | nums1[index--] = nums2[index2--]; 37 | } 38 | } 39 | 40 | }; 41 | -------------------------------------------------------------------------------- /mergeSortedArray/mergeSortedArray_1.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/merge-sorted-array/ 2 | // Author : weekend27 3 | // Date : 2015-12-02 4 | 5 | /********************************************************************************** 6 | 7 | Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 8 | 9 | Note: 10 | You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. 11 | The number of elements initialized in nums1 and nums2 are m and n respectively. 12 | 13 | **********************************************************************************/ 14 | 15 | // How to do it: 16 | // move nums1[0~m-1] to nums1[n~n+m-1], merge nums1 and nums2 to nums1 17 | // time O(n+m) 18 | 19 | 20 | class Solution { 21 | public: 22 | void merge(vector& nums1, int m, vector& nums2, int n){ 23 | // move nums1[0~m-1] to nums1[n~n+m-1] 24 | for (int i = m - 1; i >= 0; i--) 25 | nums1[n + i] = nums1[i]; 26 | 27 | // merge 28 | int pa = n, pb = 0, cnt = 0; 29 | while (pa < n + m && pb < n){ 30 | if (nums1[pa] < nums2[pb]) 31 | nums1[cnt++] = nums1[pa++]; 32 | else 33 | nums1[cnt++] = nums2[pb++]; 34 | } 35 | while (pb < n) 36 | nums1[cnt++] = nums2[pb++]; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /mergeTwoSortedLists/mergeTwoSortedLists.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/merge-two-sorted-lists/ 2 | // Author : weekend27 3 | // Date : 2015-12-09 4 | 5 | /********************************************************************************** 6 | 7 | Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 8 | 9 | **********************************************************************************/ 10 | 11 | // How to do it: 12 | // compare two values, put the smaller one to dummy, and then move to the next node 13 | 14 | /** 15 | * Definition for singly-linked list. 16 | * struct ListNode { 17 | * int val; 18 | * ListNode *next; 19 | * ListNode(int x) : val(x), next(NULL) {} 20 | * }; 21 | */ 22 | class Solution { 23 | public: 24 | ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 25 | ListNode dummy(0); 26 | ListNode* p = &dummy; 27 | 28 | while (l1 && l2){ 29 | int val1 = l1->val; 30 | int val2 = l2->val; 31 | // compare two values, put the smaller one to dummy, and then move to the next node 32 | if (val1 < val2){ 33 | p->next = l1; 34 | p = l1; 35 | l1 = l1->next; 36 | } else { 37 | p->next = l2; 38 | p = l2; 39 | l2 = l2->next; 40 | } 41 | } 42 | 43 | // some nodes that are not processed 44 | if (l1){ 45 | p->next = l1; 46 | } else if (l2){ 47 | p->next = l2; 48 | } 49 | 50 | return dummy.next; 51 | } 52 | }; 53 | -------------------------------------------------------------------------------- /minStack/minStack.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/min-stack/ 2 | // Author : weekend27 3 | // Date : 2015-12-19 4 | 5 | /********************************************************************************** 6 | 7 | Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. 8 | 9 | push(x) -- Push element x onto stack. 10 | pop() -- Removes the element on top of the stack. 11 | top() -- Get the top element. 12 | getMin() -- Retrieve the minimum element in the stack. 13 | 14 | **********************************************************************************/ 15 | 16 | // How to do it: 17 | // ref: http://bangbingsyb.blogspot.sg/2014/11/leetcode-min-stack.html 18 | 19 | class MinStack { 20 | stack s; 21 | stack sMin; 22 | public: 23 | void push(int x) { 24 | s.push(x); 25 | if (sMin.empty() || x <= sMin.top()){ 26 | sMin.push(x); 27 | } 28 | } 29 | 30 | void pop() { 31 | if (s.top() <= sMin.top()){ 32 | sMin.pop(); 33 | } 34 | s.pop(); 35 | } 36 | 37 | int top() { 38 | return s.top(); 39 | } 40 | 41 | int getMin() { 42 | return sMin.top(); 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /minimumDepthOfBinaryTree/minimumDepthOfBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/minimum-depth-of-binary-tree/ 2 | // Author : weekend27 3 | // Date : 2015-12-10 4 | 5 | /********************************************************************************** 6 | 7 | Given a binary tree, find its minimum depth. 8 | 9 | The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 10 | 11 | **********************************************************************************/ 12 | 13 | // How to do it: 14 | // recursively traverse the binary tree, when reaching leaf node , record the depth 15 | 16 | 17 | /** 18 | * Definition for a binary tree node. 19 | * struct TreeNode { 20 | * int val; 21 | * TreeNode *left; 22 | * TreeNode *right; 23 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 24 | * }; 25 | */ 26 | class Solution { 27 | public: 28 | int n; 29 | int minDepth(TreeNode* root) { 30 | if (!root) 31 | return 0; 32 | 33 | // initialize n to be max 34 | n = numeric_limits::max(); 35 | int d = 1; 36 | 37 | depth(root, d); 38 | return n; 39 | } 40 | 41 | void depth(TreeNode* node, int& d){ 42 | // leaf node, compare 43 | if (!node->left && !node->right){ 44 | n = min(n, d); 45 | return; 46 | } 47 | 48 | if (node->left){ 49 | d++; 50 | depth(node->left, d); 51 | d--; 52 | } 53 | 54 | if (node->right){ 55 | d++; 56 | depth(node->right, d); 57 | d--; 58 | } 59 | } 60 | }; 61 | -------------------------------------------------------------------------------- /minimumSizeSubarraySum/minimumSizeSubarraySum.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/minimum-size-subarray-sum/ 2 | // Author : weekend27 3 | // Date : 2015-12-03 4 | 5 | /********************************************************************************** 6 | 7 | Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the sum ≥ s. If there isn't one, return 0 instead. 8 | 9 | For example, given the array [2,3,1,2,4,3] and s = 7, 10 | the subarray [4,3] has the minimal length under the problem constraint. 11 | 12 | **********************************************************************************/ 13 | 14 | // How to do it: 15 | // two pointers, sliding window 16 | 17 | 18 | class Solution { 19 | public: 20 | int minSubArrayLen(int s, vector& nums) { 21 | int len = nums.size(); 22 | if (len == 0) 23 | return 0; 24 | int minLen = len + 1; 25 | int start = 0, end = 0, sum = 0; 26 | while(end < len){ 27 | while(sum < s && end < len){ 28 | sum += nums[end]; 29 | end++; 30 | } 31 | 32 | while(sum >= s && start < len){ 33 | minLen = min(minLen, end-start); 34 | if (minLen == 1) 35 | return minLen; 36 | sum -= nums[start]; 37 | start++; 38 | } 39 | 40 | if (sum >= s) 41 | minLen = min(minLen, end-start); 42 | } 43 | 44 | return minLen == (len + 1) ? 0 : minLen; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /minimumWindowSubstring/minimumWindowSubstring.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/minimum-window-substring/ 2 | // Author : weekend27 3 | // Date : 2015-12-23 4 | 5 | /********************************************************************************** 6 | 7 | Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). 8 | 9 | For example, 10 | S = "ADOBECODEBANC" 11 | T = "ABC" 12 | Minimum window is "BANC". 13 | 14 | Note: 15 | If there is no such window in S that covers all characters in T, return the empty string "". 16 | 17 | If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S. 18 | 19 | **********************************************************************************/ 20 | 21 | // How to do it: 22 | // 双指针,动态维护一个区间。尾指针不断往后扫,当扫到有一个窗口包含了所有T的字符后,然后再收缩头指针,直到不能再收缩为止。最后记录所有可能的情况中窗口最小的。 23 | 24 | 25 | Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). 26 | 27 | For example, 28 | S = "ADOBECODEBANC" 29 | T = "ABC" 30 | Minimum window is "BANC". 31 | 32 | Note: 33 | If there is no such window in S that covers all characters in T, return the empty string "". 34 | 35 | If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S. 36 | -------------------------------------------------------------------------------- /missingNumber/missingNumber.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/missing-number/ 2 | // Author : weekend27 3 | // Date : 2015-12-06 4 | 5 | /********************************************************************************** 6 | 7 | Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. 8 | 9 | For example, 10 | Given nums = [0, 1, 3] return 2. 11 | 12 | Note: 13 | Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity? 14 | 15 | **********************************************************************************/ 16 | 17 | // How to do it: 18 | // use the arithmetic sequence to sum up the array, and then minus the elements to find the missing one. 19 | 20 | class Solution { 21 | public: 22 | int missingNumber(vector& nums) { 23 | int n = nums.size(); 24 | int expect = (n + 1) * n / 2; 25 | for (int i = 0; i < n; i++) 26 | expect -= nums[i]; 27 | return expect; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /moveZeroes/moveZeroes.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/move-zeroes/ 2 | // Author : weekend27 3 | // Date : 2015-12-02 4 | 5 | /********************************************************************************** 6 | 7 | Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. 8 | 9 | For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. 10 | 11 | Note: 12 | You must do this in-place without making a copy of the array. 13 | Minimize the total number of operations. 14 | 15 | **********************************************************************************/ 16 | 17 | // How to do it: 18 | // Two pointers, 19 | // Traversal, when it meets zero, move left, and put the zero element to the end. 20 | // At the same time, narrow the range. 21 | // Don't remember to i--. 22 | 23 | class Solution { 24 | public: 25 | void moveZeroes(vector& nums) { 26 | int n = nums.size(); 27 | for (int i = 0; i < n; i++){ 28 | if(nums[i] == 0){ 29 | for (int j = i; j < n - 1; j++){ 30 | nums[j] = nums[j+1]; 31 | } 32 | nums[n-1] = 0; 33 | n--; 34 | i--; 35 | } 36 | } 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /multiplyStrings/multiplyStrings.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/multiply-strings/ 2 | // Author : weekend27 3 | // Date : 2015-12-17 4 | 5 | /********************************************************************************** 6 | 7 | Given two numbers represented as strings, return multiplication of the numbers as a string. 8 | 9 | Note: The numbers can be arbitrarily large and are non-negative. 10 | 11 | **********************************************************************************/ 12 | 13 | // How to do it: 14 | // ref: http://bangbingsyb.blogspot.jp/2014/11/leetcode-multiply-strings.html 15 | 16 | 17 | class Solution { 18 | public: 19 | string multiply(string num1, string num2) { 20 | if (num1.empty() || num2.empty()){ 21 | return ""; 22 | } 23 | reverse(num1.begin(), num1.end()); 24 | reverse(num2.begin(), num2.end()); 25 | string ret(num1.size() + num2.size(), '0'); 26 | 27 | for (int j = 0; j < num2.size(); j++){ 28 | int carry = 0; 29 | int val = num2[j] - '0'; 30 | for (int i = 0; i < num1.size(); i++){ 31 | carry += ((num1[i] - '0') * val + (ret[i+j] - '0')); 32 | ret[i+j] = carry % 10 + '0'; 33 | carry /= 10; 34 | } 35 | if (carry != 0){ 36 | ret[num1.size() + j] = carry + '0'; 37 | } 38 | } 39 | reverse(ret.begin(), ret.end()); 40 | 41 | int cnt = 0; 42 | while (cnt < ret.size() - 1 && ret[cnt] == '0'){ 43 | cnt++; 44 | } 45 | ret.erase(0, cnt); 46 | return ret; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /nimGame/nimGame.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/nim-game/ 2 | // Author : weekend27 3 | // Date : 2015-12-26 4 | 5 | /********************************************************************************** 6 | 7 | You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones. 8 | 9 | Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap. 10 | 11 | For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend. 12 | 13 | Hint: 14 | 15 | If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner? 16 | 17 | **********************************************************************************/ 18 | 19 | // How to do it: 20 | // look at the code 21 | 22 | 23 | class Solution { 24 | public: 25 | bool canWinNim(int n) { 26 | return n % 4 != 0; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /numberOf1Bits/numberOf1Bits.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/number-of-1-bits/ 2 | // Author : weekend27 3 | // Date : 2015-12-28 4 | 5 | /********************************************************************************** 6 | 7 | Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight). 8 | 9 | For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3. 10 | 11 | **********************************************************************************/ 12 | 13 | // How to do it: 14 | // & 15 | 16 | class Solution { 17 | public: 18 | int hammingWeight(uint32_t n) { 19 | int cnt = 0; 20 | for (int i = 1; i < 33; i++){ 21 | if (getOne(n, i) == true){ 22 | cnt++; 23 | } 24 | } 25 | return cnt; 26 | } 27 | 28 | bool getOne(uint32_t n, int i){ 29 | return (n & (1 << i)) != 0; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /numberOfDigitOne/numberOfDigitOne.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/number-of-digit-one/ 2 | // Author : weekend27 3 | // Date : 2015-12-25 4 | 5 | /********************************************************************************** 6 | 7 | Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n. 8 | 9 | For example: 10 | Given n = 13, 11 | Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13. 12 | 13 | Hint: 14 | 15 | Beware of overflow. 16 | 17 | **********************************************************************************/ 18 | 19 | // How to do it: 20 | // ref: http://www.cnblogs.com/grandyang/p/4629032.html 21 | 22 | 23 | class Solution { 24 | public: 25 | int countDigitOne(int n) { 26 | int res = 0, a = 1, b = 1; 27 | while (n > 0){ 28 | res += (n + 8) / 10 * a + (n % 10 == 1) * b; 29 | b += n % 10 * a; 30 | a *= 10; 31 | n /= 10; 32 | } 33 | return res; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /oddEvenLinkedList/oddEvenLinkedList.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/odd-even-linked-list/ 2 | // Author : weekend27 3 | // Date : 2016-01-16 4 | 5 | /********************************************************************************** 6 | 7 | Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. 8 | 9 | You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity. 10 | 11 | Example: 12 | Given 1->2->3->4->5->NULL, 13 | return 1->3->5->2->4->NULL. 14 | 15 | Note: 16 | The relative order inside both the even and odd groups should remain as it was in the input. 17 | The first node is considered odd, the second node even and so on ... 18 | 19 | **********************************************************************************/ 20 | 21 | // How to do it: 22 | // ref: http://www.hrwhisper.me/leetcode-odd-even-linked-list/ 23 | // 很简单的,用两个指针即可,一个指针p指向当前遍历的奇数节点的最后一个位置,另一个指针q指向待提取的奇数节点的前一个位置。然后把q.next 的节点删除,插入到p.next的位置即可 24 | 25 | /** 26 | * Definition for singly-linked list. 27 | * struct ListNode { 28 | * int val; 29 | * ListNode *next; 30 | * ListNode(int x) : val(x), next(NULL) {} 31 | * }; 32 | */ 33 | class Solution { 34 | public: 35 | ListNode* oddEvenList(ListNode* head) { 36 | if (!head) { return head; } 37 | ListNode* p = head; 38 | ListNode* q = head; 39 | while (q) { 40 | q = q->next; 41 | if (!q || !q->next) { break; } 42 | ListNode* next_p = p->next; 43 | ListNode* next_q = q->next; 44 | q->next = next_q->next; 45 | p->next = next_q; 46 | next_q->next = next_p; 47 | p = p->next; 48 | } 49 | return head; 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /palindromeNumber/palindromeNumber.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/palindrome-number/ 2 | // Author : weekend27 3 | // Date : 2015-12-25 4 | 5 | /********************************************************************************** 6 | 7 | Determine whether an integer is a palindrome. Do this without extra space. 8 | 9 | click to show spoilers. 10 | 11 | Some hints: 12 | Could negative integers be palindromes? (ie, -1) 13 | 14 | If you are thinking of converting the integer to string, note the restriction of using extra space. 15 | 16 | You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case? 17 | 18 | There is a more generic way of solving this problem. 19 | 20 | **********************************************************************************/ 21 | 22 | // How to do it: 23 | // 不断地取第一位和最后一位(10进制下)进行比较,相等则取第二位和倒数第二位,直到完成比较或者中途找到了不一致的位。 24 | 25 | 26 | class Solution { 27 | public: 28 | bool isPalindrome(int x) { 29 | if (x < 0){ 30 | return false; 31 | } 32 | int div = 1; 33 | while (x/div >= 10){ 34 | div *= 10; 35 | } 36 | while (x > 0){ 37 | int l = x / div; 38 | int r = x % 10; 39 | if (l != r){ 40 | return false; 41 | } 42 | x = x % div / 10; 43 | div /= 100; 44 | } 45 | return true; 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /palindromeNumber/palindromeNumber.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/palindrome-number/ 2 | // Author : weekend27 3 | // Date : 2016-04-12 4 | 5 | /********************************************************************************** 6 | 7 | Determine whether an integer is a palindrome. Do this without extra space. 8 | 9 | click to show spoilers. 10 | 11 | Some hints: 12 | Could negative integers be palindromes? (ie, -1) 13 | 14 | If you are thinking of converting the integer to string, note the restriction of using extra space. 15 | 16 | You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case? 17 | 18 | There is a more generic way of solving this problem. 19 | 20 | **********************************************************************************/ 21 | 22 | // How to do it: 23 | // ref: https://leetcode.com/discuss/23563/line-accepted-java-code-without-the-need-handling-overflow 24 | // excellent! 25 | // compare half of the digits in x, so don't need to deal with overflow. 26 | 27 | public class Solution { 28 | public boolean isPalindrome(int x) { 29 | if (x < 0 || (x != 0 && x % 10 == 0)) return false; 30 | int rev = 0; 31 | while (x > rev) { 32 | rev = rev * 10 + x % 10; 33 | x /= 10; 34 | } 35 | return (x == rev || x == rev / 10); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /partitionList/partitionList.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/partition-list/ 2 | // Author : weekend27 3 | // Date : 2015-12-10 4 | 5 | /********************************************************************************** 6 | 7 | Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. 8 | 9 | You should preserve the original relative order of the nodes in each of the two partitions. 10 | 11 | For example, 12 | Given 1->4->3->2->5->2 and x = 3, 13 | return 1->2->2->4->3->5. 14 | 15 | **********************************************************************************/ 16 | 17 | // How to do it: 18 | // put the numbers which are smaller than x to a linked list, and others to another linked list 19 | // join together finally 20 | 21 | 22 | /** 23 | * Definition for singly-linked list. 24 | * struct ListNode { 25 | * int val; 26 | * ListNode *next; 27 | * ListNode(int x) : val(x), next(NULL) {} 28 | * }; 29 | */ 30 | class Solution { 31 | public: 32 | ListNode* partition(ListNode* head, int x) { 33 | ListNode dummy1(0), dummy2(0); 34 | ListNode* p1 = &dummy1; 35 | ListNode* p2 = &dummy2; 36 | 37 | ListNode* p = head; 38 | while(p){ 39 | if (p->val < x){ 40 | p1->next = p; 41 | p1 = p1->next; 42 | } else { 43 | p2->next = p; 44 | p2 = p2->next; 45 | } 46 | p = p->next; 47 | } 48 | 49 | p2->next = NULL; 50 | p1->next = dummy2.next; 51 | return dummy1.next; 52 | } 53 | }; 54 | -------------------------------------------------------------------------------- /pascalsTriangle/pascalsTriangle.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/pascals-triangle/ 2 | // Author : weekend27 3 | // Date : 2015-12-02 4 | 5 | /********************************************************************************** 6 | 7 | Given numRows, generate the first numRows of Pascal's triangle. 8 | 9 | For example, given numRows = 5, 10 | Return 11 | 12 | [ 13 | [1], 14 | [1,1], 15 | [1,2,1], 16 | [1,3,3,1], 17 | [1,4,6,4,1] 18 | ] 19 | 20 | **********************************************************************************/ 21 | 22 | // How to do it: 23 | // add every vector sequently 24 | 25 | class Solution { 26 | public: 27 | vector> generate(int numRows) { 28 | vector> rVec; 29 | for (int i = 0; i < numRows; i++){ 30 | vector cur; 31 | if (i == 0) // initial assignment 32 | cur.push_back(1); 33 | else{ 34 | for (int j = 0; j <= i; j++){ 35 | if (j == 0 || j == i) // the left and right boundaries 36 | cur.push_back(1); 37 | else 38 | cur.push_back(rVec[i-1][j] + rVec[i-1][j-1]); // normal situation 39 | } 40 | } 41 | rVec.push_back(cur); 42 | } 43 | 44 | return rVec; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /pascalsTriangle/pascalsTriangleII.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/pascals-triangle-ii/ 2 | // Author : weekend27 3 | // Date : 2015-12-02 4 | 5 | /********************************************************************************** 6 | 7 | Given an index k, return the kth row of the Pascal's triangle. 8 | 9 | For example, given k = 3, 10 | Return [1,3,3,1]. 11 | 12 | Note: 13 | Could you optimize your algorithm to use only O(k) extra space? 14 | 15 | **********************************************************************************/ 16 | 17 | // How to do it: 18 | // two pointers 19 | // from the end to the start, fresh your vector 20 | // space O(k) 21 | 22 | class Solution { 23 | public: 24 | vector getRow(int rowIndex) { 25 | vector vec(rowIndex + 1); 26 | 27 | vec[0] = 1; 28 | for (int i = 1; i <= rowIndex; i++) 29 | for (int j = i; j >= 0; j--) 30 | if (j == i) 31 | vec[j] = vec[j-1]; 32 | else if (j == 0) 33 | vec[j] = vec[j]; 34 | else 35 | vec[j] = vec[j-1] + vec[j]; 36 | 37 | return vec; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /pathSum/pathSum.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/path-sum/ 2 | // Author : weekend27 3 | // Date : 2015-12-11 4 | 5 | /********************************************************************************** 6 | 7 | Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. 8 | 9 | For example: 10 | Given the below binary tree and sum = 22, 11 | 5 12 | / \ 13 | 4 8 14 | / / \ 15 | 11 13 4 16 | / \ \ 17 | 7 2 1 18 | return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. 19 | 20 | **********************************************************************************/ 21 | 22 | // How to do it: 23 | // DFS 24 | // time complexity: O(n) 25 | 26 | 27 | /** 28 | * Definition for a binary tree node. 29 | * struct TreeNode { 30 | * int val; 31 | * TreeNode *left; 32 | * TreeNode *right; 33 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 34 | * }; 35 | */ 36 | class Solution { 37 | public: 38 | bool hasPathSum(TreeNode* root, int sum) { 39 | if (root == NULL) 40 | return false; 41 | 42 | return DFS(sum, root, 0); 43 | } 44 | 45 | bool DFS(int target, TreeNode* root, int sum){ 46 | if (root == NULL) 47 | return false; 48 | 49 | sum += root->val; 50 | if (root->left == NULL && root->right == NULL){ 51 | if (sum == target) 52 | return true; 53 | else 54 | return false; 55 | } 56 | 57 | bool ls = DFS(target, root->left, sum); 58 | bool rs = DFS(target, root->right, sum); 59 | return ls || rs; 60 | } 61 | }; 62 | -------------------------------------------------------------------------------- /pathSum/pathSumII.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/path-sum-ii/ 2 | // Author : weekend27 3 | // Date : 2015-12-14 4 | 5 | /********************************************************************************** 6 | 7 | Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. 8 | 9 | For example: 10 | Given the below binary tree and sum = 22, 11 | 5 12 | / \ 13 | 4 8 14 | / / \ 15 | 11 13 4 16 | / \ / \ 17 | 7 2 5 1 18 | return 19 | [ 20 | [5,4,11,2], 21 | [5,8,4,5] 22 | ] 23 | 24 | **********************************************************************************/ 25 | 26 | // How to do it: 27 | // really like pathSum.cpp 28 | // differences are just arguments for the function 29 | 30 | 31 | /** 32 | * Definition for a binary tree node. 33 | * struct TreeNode { 34 | * int val; 35 | * TreeNode *left; 36 | * TreeNode *right; 37 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 38 | * }; 39 | */ 40 | class Solution { 41 | public: 42 | vector> pathSum(TreeNode* root, int sum) { 43 | vector> path; 44 | if (root == NULL) 45 | return path; 46 | vector curr; 47 | DFS(path, curr, sum, 0, root); 48 | return path; 49 | } 50 | 51 | void DFS(vector>& path, vector curr, int sum, int tmp, TreeNode* root){ 52 | if (root == NULL) 53 | return; 54 | tmp += root->val; 55 | curr.push_back(root->val); 56 | if (tmp == sum){ 57 | if (root->left == NULL && root->right == NULL){ 58 | path.push_back(curr); 59 | return; 60 | } 61 | } 62 | DFS(path,curr,sum,tmp,root->left); 63 | DFS(path,curr,sum,tmp,root->right); 64 | } 65 | }; 66 | -------------------------------------------------------------------------------- /perfectSquares/perfectSquares.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/perfect-squares/ 2 | // Author : weekend27 3 | // Date : 2015-12-25 4 | 5 | /********************************************************************************** 6 | 7 | Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. 8 | 9 | For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9. 10 | 11 | **********************************************************************************/ 12 | 13 | // How to do it: 14 | // ref: http://www.cnblogs.com/grandyang/p/4800552.html 15 | /* 16 | 这道题是考察四平方和定理 17 | 根据四平方和定理,任意一个正整数均可表示为4个整数的平方和,其实是可以表示为4个以内的平方数之和,那么就是说返回结果只有1,2,3或4其中的一个, 18 | 首先我们将数字化简一下,由于一个数如果含有因子4,那么我们可以把4都去掉,并不影响结果,比如2和8,3和12等等,返回的结果都相同,读者可自行举更多的栗子。 19 | 还有一个可以化简的地方就是,如果一个数除以8余7的话,那么肯定是由4个完全平方数组成,这里就不证明了,因为我也不会证明,读者可自行举例验证。 20 | 那么做完两步后,一个很大的数有可能就会变得很小了,大大减少了运算时间,下面我们就来尝试的将其拆为两个平方数之和,如果拆成功了那么就会返回1或2,因为其中一个平方数可能为0. 21 | (注:由于输入的n是正整数,所以不存在两个平方数均为0的情况)。注意下面的!!a + !!b这个表达式,可能很多人不太理解这个的意思, 22 | 其实很简单,感叹号!表示逻辑取反,那么一个正整数逻辑取反为0,再取反为1,所以用两个感叹号!!的作用就是看a和b是否为正整数,都为正整数的话返回2,只有一个是正整数的话返回1. 23 | */ 24 | 25 | class Solution { 26 | public: 27 | int numSquares(int n) { 28 | while (n % 4 == 0){ 29 | n /= 4; 30 | } 31 | if (n % 8 == 7){ 32 | return 4; 33 | } 34 | for (int a = 0; a * a <= n; ++a){ 35 | int b = sqrt(n - a * a); 36 | if (a * a + b * b == n){ 37 | return !!a + !!b; // return 1 or 2 38 | } 39 | } 40 | return 3; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /permutationSequence/permutationSequence.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/permutation-sequence/ 2 | // Author : weekend27 3 | // Date : 2015-12-24 4 | 5 | /********************************************************************************** 6 | 7 | The set [1,2,3,…,n] contains a total of n! unique permutations. 8 | 9 | By listing and labeling all of the permutations in order, 10 | We get the following sequence (ie, for n = 3): 11 | 12 | "123" 13 | "132" 14 | "213" 15 | "231" 16 | "312" 17 | "321" 18 | Given n and k, return the kth permutation sequence. 19 | 20 | Note: Given n will be between 1 and 9 inclusive. 21 | 22 | **********************************************************************************/ 23 | 24 | // How to do it: 25 | // ref: http://bangbingsyb.blogspot.sg/2014/11/leetcode-permutation-sequence.html 26 | 27 | class Solution { 28 | public: 29 | string getPermutation(int n, int k) { 30 | string res; 31 | vector factorial(n, 1); 32 | vector num(n, 1); 33 | 34 | for (int i = 1; i < n; i++){ 35 | factorial[i] = factorial[i-1] * i; 36 | } 37 | 38 | for (int i = 0; i < n; i++){ 39 | num[i] = (i+1) + '0'; 40 | } 41 | 42 | k--; 43 | for (int i = n; i >= 1; i--){ 44 | int j = k / factorial[i-1]; 45 | k %= factorial[i-1]; 46 | res.push_back(num[j]); 47 | num.erase(num.begin()+j); 48 | } 49 | 50 | return res; 51 | } 52 | }; 53 | -------------------------------------------------------------------------------- /permutations/permutations.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/permutations/ 2 | // Author : weekend27 3 | // Date : 2015-12-30 4 | 5 | /********************************************************************************** 6 | 7 | Given a collection of distinct numbers, return all possible permutations. 8 | 9 | For example, 10 | [1,2,3] have the following permutations: 11 | [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1]. 12 | 13 | **********************************************************************************/ 14 | 15 | // How to do it: 16 | // ref: http://bangbingsyb.blogspot.jp/2014/11/leetcode-permutations-i-ii.html 17 | // insert method 18 | 19 | 20 | class Solution { 21 | public: 22 | vector> permute(vector& nums) { 23 | vector> allPer; 24 | if (nums.empty()){ 25 | return allPer; 26 | } 27 | allPer.push_back(vector(1, nums[0])); 28 | 29 | for (int i = 1; i < nums.size(); i++){ 30 | int n = allPer.size(); 31 | for (int j = 0; j < n; j++){ 32 | for (int k = 0; k < allPer[j].size(); k++){ 33 | vector per = allPer[j]; 34 | per.insert(per.begin() + k, nums[i]); 35 | allPer.push_back(per); 36 | } 37 | allPer[j].push_back(nums[i]); 38 | } 39 | } 40 | return allPer; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /plusOne/plusOne.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/plus-one/ 2 | // Author : weekend27 3 | // Date : 2015-12-02 4 | 5 | /********************************************************************************** 6 | 7 | Given a non-negative number represented as an array of digits, plus one to the number. 8 | 9 | The digits are stored such that the most significant digit is at the head of the list. 10 | 11 | **********************************************************************************/ 12 | 13 | // How to do it: 14 | // from the rbegin to the rend, ensure iterator and carry through % and / 15 | 16 | class Solution { 17 | public: 18 | vector plusOne(vector& digits) { 19 | add(digits, 1); 20 | return digits; 21 | } 22 | private: 23 | void add(vector& num, int digit){ 24 | int c = digit; // carry 25 | for(auto it = num.rbegin(); it != num.rend(); it++){ 26 | *it += c; 27 | c = *it / 10; 28 | *it %= 10; 29 | } 30 | if (c != 0) 31 | num.insert(num.begin(), 1); 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /plusOne/plusOne.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] plusOne(int[] digits) { 3 | int c = 1; 4 | for(int i = digits.length - 1; i >= 0; i--) { 5 | digits[i] = digits[i] + c; 6 | c = digits[i] / 10; 7 | digits[i] = digits[i] % 10; 8 | } 9 | if (c != 0) { 10 | int[] result = new int[digits.length + 1]; 11 | result[0] = c; 12 | for (int i = 1; i < result.length; i++) { 13 | result[i] = digits[i - 1]; 14 | } 15 | return result; 16 | } 17 | return digits; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /pow(x,n)/pow(x,n).cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/powx-n/ 2 | // Author : weekend27 3 | // Date : 2015-12-24 4 | 5 | /********************************************************************************** 6 | 7 | Implement pow(x, n). 8 | 9 | **********************************************************************************/ 10 | 11 | // How to do it: 12 | // divide and conquer 13 | 14 | class Solution { 15 | public: 16 | double power(double x, int n) { 17 | if (n == 0) 18 | { 19 | return 1; 20 | } 21 | 22 | double v = power(x, n/2); 23 | if (n % 2 == 0) 24 | { 25 | return v * v; 26 | } 27 | else 28 | { 29 | return v * v * x; 30 | } 31 | } 32 | 33 | double myPow(double x, int n) { 34 | if (n < 0) 35 | { 36 | return 1.0 / power(x, -n); 37 | } 38 | else 39 | { 40 | return power(x, n); 41 | } 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /powerOfThree/powerOfThree.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/power-of-three/ 2 | // Author : weekend27 3 | // Date : 2016-01-14 4 | 5 | /********************************************************************************** 6 | 7 | Given an integer, write a function to determine if it is a power of three. 8 | 9 | Follow up: 10 | Could you do it without using any loop / recursion? 11 | 12 | **********************************************************************************/ 13 | 14 | // How to do it: 15 | // just look at code, while loop 16 | 17 | class Solution { 18 | public: 19 | bool isPowerOfThree(int n) { 20 | if (n == 0) { 21 | return false; 22 | } 23 | if (n == 1) { 24 | return true; 25 | } 26 | while (n % 3 == 0) { 27 | n /= 3; 28 | } 29 | return n == 1; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /powerOfTwo/powerOfTwo.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/power-of-two/ 2 | // Author : weekend27 3 | // Date : 2015-12-24 4 | 5 | /********************************************************************************** 6 | 7 | Given an integer, write a function to determine if it is a power of two. 8 | 9 | **********************************************************************************/ 10 | 11 | // How to do it: 12 | // ref: http://www.cnblogs.com/grandyang/p/4623394.html 13 | /* 14 | 如果一个数是2的次方数的话,根据上面分析,那么它的二进数必然是最高位为1,其它都为0, 15 | 那么如果此时我们减1的话,则最高位会降一位,其余为0的位现在都为变为1,那么我们把两数相与,就会得到0 16 | */ 17 | 18 | class Solution { 19 | public: 20 | bool isPowerOfTwo(int n) { 21 | return (n > 0) && (!(n & (n - 1))); 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /productOfArrayExceptSelf/productOfArrayExceptSelf.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/product-of-array-except-self/ 2 | // Author : weekend27 3 | // Date : 2015-12-28 4 | 5 | /********************************************************************************** 6 | 7 | Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. 8 | 9 | Solve it without division and in O(n). 10 | 11 | For example, given [1,2,3,4], return [24,12,8,6]. 12 | 13 | Follow up: 14 | Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.) 15 | 16 | **********************************************************************************/ 17 | 18 | // How to do it: 19 | // ref: https://leetcode.com/discuss/46104/simple-java-solution-in-o-n-without-extra-space 20 | // two traverses 21 | 22 | class Solution { 23 | public: 24 | vector productExceptSelf(vector& nums) { 25 | int n = nums.size(); 26 | vector prod(n, 1); 27 | for (int i = 1; i < n; i++){ 28 | prod[i] = prod[i - 1] * nums[i - 1]; 29 | } 30 | for (int i = n - 1, r = 1; i >= 0; r *= nums[i--]){ 31 | prod[i] *= r; 32 | } 33 | return prod; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /recoverBinarySearchTree/recoverBinarySearchTree.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/recover-binary-search-tree/ 2 | // Author : weekend27 3 | // Date : 2015-12-14 4 | 5 | /********************************************************************************** 6 | 7 | Two elements of a binary search tree (BST) are swapped by mistake. 8 | 9 | Recover the tree without changing its structure. 10 | 11 | Note: 12 | A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? 13 | 14 | **********************************************************************************/ 15 | 16 | // How to do it: 17 | // InOrderTraversal 18 | // space O(n) 19 | 20 | 21 | /** 22 | * Definition for a binary tree node. 23 | * struct TreeNode { 24 | * int val; 25 | * TreeNode *left; 26 | * TreeNode *right; 27 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 28 | * }; 29 | */ 30 | class Solution { 31 | public: 32 | void recoverTree(TreeNode* root) { 33 | vector list; 34 | vector values; 35 | InOrderTraversal(root, list, values); 36 | sort(values.begin(), values.end()); 37 | for (int i = 0; i < list.size(); i++) 38 | list[i]->val = values[i]; 39 | } 40 | 41 | void InOrderTraversal(TreeNode* node, vector& list, vector& values){ 42 | if (node == NULL) 43 | return; 44 | InOrderTraversal(node->left, list, values); 45 | list.push_back(node); 46 | values.push_back(node->val); 47 | InOrderTraversal(node->right, list, values); 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /rectangleArea/rectangleArea.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/rectangle-area/ 2 | // Author : weekend27 3 | // Date : 2015-12-24 4 | 5 | /********************************************************************************** 6 | 7 | Find the total area covered by two rectilinear rectangles in a 2D plane. 8 | 9 | Each rectangle is defined by its bottom left corner and top right corner as shown in the figure. 10 | 11 | Assume that the total area is never beyond the maximum possible value of int. 12 | 13 | **********************************************************************************/ 14 | 15 | // How to do it: 16 | // ref: http://bookshadow.com/weblog/2015/06/08/leetcode-rectangle-area/ 17 | /* 18 | 题目大意: 19 | 计算二维平面上两个直线矩形的覆盖面积。 20 | 21 | 矩形通过其左下角和右上角的坐标进行定义。 22 | 23 | 假设总面积不会超过int的最大值。 24 | 25 | 解题思路: 26 | 简单计算几何。根据容斥原理:S(M ∪ N) = S(M) + S(N) - S(M ∩ N) 27 | 28 | 题目可以转化为计算矩形相交部分的面积 29 | 30 | S(M) = (C - A) * (D - B) 31 | 32 | S(N) = (G - E) * (H - F) 33 | 34 | S(M ∩ N) = max(min(C, G) - max(A, E), 0) * max(min(D, H) - max(B, F), 0) 35 | */ 36 | 37 | class Solution { 38 | public: 39 | int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { 40 | int area = (D - B) * (C - A) + (H - F) * (G - E); 41 | if (A >= G || B >= H || C <= E || D <= F) 42 | { 43 | return area; 44 | } 45 | 46 | int top = min(D, H); 47 | int right = min(C, G); 48 | int bottom = max(B, F); 49 | int left = max(A, E); 50 | 51 | return area - (top - bottom) * (right - left); 52 | } 53 | }; 54 | -------------------------------------------------------------------------------- /removeDuplicatesFromSortedArray/removeDuplicatesFromSortedArray.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/remove-duplicates-from-sorted-array/ 2 | // Author : weekend27 3 | // Date : 2015-11-18 4 | 5 | /********************************************************************************** 6 | 7 | Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. 8 | 9 | Do not allocate extra space for another array, you must do this in place with constant memory. 10 | 11 | For example, 12 | 13 | Given input array nums = [1,1,2], 14 | 15 | Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length. 16 | 17 | **********************************************************************************/ 18 | 19 | // How to do it: 20 | // Two pointers: when one index meets duplicates, another one will stay and not increase. 21 | 22 | class Solution { 23 | public: 24 | int removeDuplicates(vector& nums) { 25 | int index = 0; 26 | int len = nums.size(); 27 | 28 | if (len == 0){ 29 | return 0; 30 | } 31 | 32 | for (int i = 1; i < len; i++){ 33 | if (nums[index] != nums[i]) 34 | nums[++index] = nums[i]; 35 | } 36 | return index + 1; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /removeDuplicatesFromSortedArray/removeDuplicatesFromSortedArray.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int removeDuplicates(int[] nums) { 3 | if (nums == null || nums.length == 0) return 0; 4 | int index = 0; 5 | for (int i = 1; i < nums.length; i++) { 6 | if (nums[index] != nums[i]) { 7 | nums[++index] = nums[i]; 8 | } 9 | } 10 | return index + 1; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /removeDuplicatesFromSortedArray/removeDuplicatesFromSortedArrayII.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ 2 | // Author : weekend27 3 | // Date : 2015-11-18 4 | 5 | /********************************************************************************** 6 | 7 | Follow up for "Remove Duplicates": 8 | What if duplicates are allowed at most twice? 9 | 10 | For example, 11 | Given sorted array nums = [1,1,1,2,2,3], 12 | 13 | Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length. 14 | 15 | **********************************************************************************/ 16 | 17 | // How to do it: 18 | // Two pointers: add one variable to record the times that elements appear. 19 | 20 | class Solution { 21 | public: 22 | int removeDuplicates(vector& nums) { 23 | int len = nums.size(); 24 | int index = 2; 25 | 26 | if (len <= 2) return len; 27 | 28 | for (int i = 2; i < len; i++){ 29 | if (nums[index-2] != nums[i]) 30 | nums[index++] = nums[i]; 31 | } 32 | 33 | return index; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /removeDuplicatesFromSortedArray/removeDuplicatesFromSortedArrayII.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int removeDuplicates(int[] nums) { 3 | if (nums == null || nums.length == 0) return 0; 4 | 5 | int index = 2; 6 | for (int i = 2; i < nums.length; i++) { 7 | if (nums[i] != nums[index - 2]) { 8 | nums[index++] = nums[i]; 9 | } 10 | } 11 | 12 | return index; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /removeDuplicatesFromSortedList/removeDuplicatesFromSortedList.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/remove-duplicates-from-sorted-list/ 2 | // Author : weekend27 3 | // Date : 2015-12-09 4 | 5 | /********************************************************************************** 6 | 7 | Given a sorted linked list, delete all duplicates such that each element appear only once. 8 | 9 | For example, 10 | Given 1->1->2, return 1->2. 11 | Given 1->1->2->3->3, return 1->2->3. 12 | 13 | **********************************************************************************/ 14 | 15 | // How to do it: 16 | // two pointers, one follows another, if vals are equal, skip it. 17 | // p->next = p->next->next; 18 | 19 | /** 20 | * Definition for singly-linked list. 21 | * struct ListNode { 22 | * int val; 23 | * ListNode *next; 24 | * ListNode(int x) : val(x), next(NULL) {} 25 | * }; 26 | */ 27 | class Solution { 28 | public: 29 | ListNode* deleteDuplicates(ListNode* head) { 30 | if (!head){ 31 | return head; 32 | } 33 | 34 | int val = head->val; 35 | ListNode* p = head; 36 | while (p && p->next){ 37 | if (p->next->val != val){ 38 | val = p->next->val; 39 | p = p->next; 40 | } else { 41 | // delete next 42 | ListNode* n = p->next->next; 43 | p->next = n; 44 | } 45 | } 46 | return head; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /removeElement/removeElement.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/remove-element/ 2 | // Author : weekend27 3 | // Date : 2015-12-02 4 | 5 | /********************************************************************************** 6 | 7 | Given an array and a value, remove all instances of that value in place and return the new length. 8 | 9 | The order of elements can be changed. It doesn't matter what you leave beyond the new length. 10 | 11 | **********************************************************************************/ 12 | 13 | // How to do it: 14 | // two pointers 15 | 16 | class Solution { 17 | public: 18 | int removeElement(vector& nums, int val){ 19 | int startPosition = 0; 20 | for (int i = 0; i < nums.size(); i++){ 21 | if (nums[i] != val){ 22 | nums[startPosition] = nums[i]; 23 | startPosition++; 24 | } 25 | } 26 | return startPosition; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /removeNthNodeFromEndOfList/removeNthNodeFromEndOfList.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/remove-nth-node-from-end-of-list/ 2 | // Author : weekend27 3 | // Date : 2015-12-31 4 | 5 | /********************************************************************************** 6 | 7 | Given a linked list, remove the nth node from the end of list and return its head. 8 | 9 | For example, 10 | 11 | Given linked list: 1->2->3->4->5, and n = 2. 12 | 13 | After removing the second node from the end, the linked list becomes 1->2->3->5. 14 | Note: 15 | Given n will always be valid. 16 | Try to do this in one pass. 17 | 18 | **********************************************************************************/ 19 | 20 | // How to do it: 21 | // ref: http://fisherlei.blogspot.jp/2012/12/leetcode-remove-nth-node-from-end-of.html 22 | // 经典题。双指针,一个指针先走n步,然后两个同步走,直到第一个走到终点,第二个指针就是需要删除的节点。唯一要注意的就是头节点的处理,比如,1->2->NULL, n =2; 这时,要删除的就是头节点。 23 | 24 | /** 25 | * Definition for singly-linked list. 26 | * struct ListNode { 27 | * int val; 28 | * ListNode *next; 29 | * ListNode(int x) : val(x), next(NULL) {} 30 | * }; 31 | */ 32 | class Solution { 33 | public: 34 | ListNode* removeNthFromEnd(ListNode* head, int n) { 35 | assert(head); 36 | ListNode* pre; 37 | ListNode* cur; 38 | pre = head; 39 | cur = head; 40 | int step = 0; 41 | while (step < n && cur != NULL){ 42 | cur = cur->next; 43 | step++; 44 | } 45 | if (step == n && cur == NULL){ 46 | head = head->next; 47 | delete pre; 48 | return head; 49 | } 50 | while (cur->next != NULL){ 51 | pre = pre->next; 52 | cur = cur->next; 53 | } 54 | ListNode* tmp = pre->next; 55 | pre->next = tmp->next; 56 | delete tmp; 57 | return head; 58 | } 59 | }; 60 | -------------------------------------------------------------------------------- /reverseBits/reverseBits.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/reverse-bits/ 2 | // Author : weekend27 3 | // Date : 2016-01-07 4 | 5 | /********************************************************************************** 6 | 7 | Reverse bits of a given 32 bits unsigned integer. 8 | 9 | For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000). 10 | 11 | Follow up: 12 | If this function is called many times, how would you optimize it? 13 | 14 | Related problem: Reverse Integer 15 | 16 | **********************************************************************************/ 17 | 18 | // How to do it: 19 | // ref:http://yucoding.blogspot.com/2015/05/leetcode-questions-reverse-bits.html 20 | 21 | 22 | class Solution { 23 | public: 24 | uint32_t reverseBits(uint32_t n) { 25 | uint32_t res = 0; 26 | uint32_t mask = 1; 27 | for (int i = 0; i < 32; i++) { 28 | if (n & mask) {res = res + 1;} 29 | if (i != 31) res <<= 1; 30 | mask <<= 1; 31 | } 32 | return res; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /reverseInteger/reverseInteger.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/reverse-integer/ 2 | // Author : weekend27 3 | // Date : 2015-12-10 4 | 5 | /********************************************************************************** 6 | 7 | Reverse digits of an integer. 8 | 9 | Example1: x = 123, return 321 10 | Example2: x = -123, return -321 11 | 12 | click to show spoilers. 13 | 14 | Have you thought about this? 15 | Here are some good questions to ask before coding. Bonus points for you if you have already thought through this! 16 | 17 | If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100. 18 | 19 | Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases? 20 | 21 | For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. 22 | 23 | Update (2014-11-10): 24 | Test cases had been added to test the overflow behavior. 25 | 26 | **********************************************************************************/ 27 | 28 | // How to do it: 29 | // a succinct solution from http://www.programcreek.com/2012/12/leetcode-reverse-integer/ 30 | 31 | #define INT_MIN (-2147483647 - 1) 32 | #define INT_MAX 2147483647 33 | class Solution { 34 | public: 35 | int reverse(int x) { 36 | if (x == 0) 37 | return x; 38 | 39 | long long rev = 0; 40 | while (x != 0){ 41 | rev = rev * 10 + x % 10; 42 | x /= 10; 43 | } 44 | 45 | if (rev > INT_MAX || rev < INT_MIN) 46 | return 0; 47 | 48 | return rev; 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /reverseInteger/reverseInteger.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/reverse-integer/ 2 | // Author : weekend27 3 | // Date : 2016-04-12 4 | 5 | /********************************************************************************** 6 | 7 | Reverse digits of an integer. 8 | 9 | Example1: x = 123, return 321 10 | Example2: x = -123, return -321 11 | 12 | click to show spoilers. 13 | 14 | Have you thought about this? 15 | Here are some good questions to ask before coding. Bonus points for you if you have already thought through this! 16 | 17 | If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100. 18 | 19 | Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases? 20 | 21 | For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. 22 | 23 | Update (2014-11-10): 24 | Test cases had been added to test the overflow behavior. 25 | 26 | **********************************************************************************/ 27 | 28 | // How to do it: 29 | // a succinct solution from http://www.programcreek.com/2012/12/leetcode-reverse-integer/ 30 | 31 | 32 | public class Solution { 33 | public int reverse(int x) { 34 | 35 | if (x == 0) { 36 | return x; 37 | } 38 | 39 | long rev = 0; 40 | while (x != 0) { 41 | rev = rev * 10 + x % 10; 42 | x /= 10; 43 | } 44 | 45 | if (rev > Integer.MAX_VALUE || rev < Integer.MIN_VALUE) { 46 | return 0; 47 | } 48 | 49 | return (int)rev; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /reverseLinkedList/reverseLinkedList.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/reverse-linked-list/ 2 | // Author : weekend27 3 | // Date : 2015-12-07 4 | 5 | /********************************************************************************** 6 | 7 | Reverse a singly linked list. 8 | 9 | click to show more hints. 10 | 11 | Hint: 12 | A linked list can be reversed either iteratively or recursively. Could you implement both? 13 | 14 | **********************************************************************************/ 15 | 16 | // How to do it: 17 | // recursion 18 | 19 | 20 | 21 | /** 22 | * Definition for singly-linked list. 23 | * struct ListNode { 24 | * int val; 25 | * ListNode *next; 26 | * ListNode(int x) : val(x), next(NULL) {} 27 | * }; 28 | */ 29 | class Solution { 30 | public: 31 | ListNode* reverseList(ListNode* head) { 32 | // recursion 33 | if (head == NULL || head->next == NULL) 34 | return head; 35 | 36 | ListNode* p = head->next; 37 | ListNode* n = reverseList(p); 38 | 39 | head->next = NULL; 40 | p->next = head; 41 | return n; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /reverseLinkedList/reverseLinkedListII.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/reverse-linked-list-ii/ 2 | // Author : weekend27 3 | // Date : 2015-12-08 4 | 5 | /********************************************************************************** 6 | 7 | Reverse a linked list from position m to n. Do it in-place and in one-pass. 8 | 9 | For example: 10 | Given 1->2->3->4->5->NULL, m = 2 and n = 4, 11 | 12 | return 1->4->3->2->5->NULL. 13 | 14 | Note: 15 | Given m, n satisfy the following condition: 16 | 1 ≤ m ≤ n ≤ length of list. 17 | 18 | **********************************************************************************/ 19 | 20 | // How to do it: 21 | // recursion 22 | 23 | /** 24 | * Definition for singly-linked list. 25 | * struct ListNode { 26 | * int val; 27 | * ListNode *next; 28 | * ListNode(int x) : val(x), next(NULL) {} 29 | * }; 30 | */ 31 | class Solution { 32 | public: 33 | ListNode* reverseBetween(ListNode* head, int m, int n) { 34 | if (!head){ 35 | return head; 36 | } 37 | 38 | ListNode dummy(0); 39 | dummy.next = head; 40 | 41 | ListNode* p = &dummy; 42 | for (int i = 1; i < m; i++){ 43 | p = p->next; 44 | } 45 | 46 | // p is now the pre-node of pm 47 | ListNode* pm = p->next; 48 | 49 | for (int i = m; i < n; i++){ 50 | ListNode* n = pm->next; 51 | pm->next = n->next; 52 | n->next = p->next; 53 | p->next = n; 54 | } 55 | 56 | return dummy.next; 57 | } 58 | }; 59 | -------------------------------------------------------------------------------- /reverseLinkedList/reverseLinkedList_1.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/reverse-linked-list/ 2 | // Author : weekend27 3 | // Date : 2015-12-07 4 | 5 | /********************************************************************************** 6 | 7 | Reverse a singly linked list. 8 | 9 | click to show more hints. 10 | 11 | Hint: 12 | A linked list can be reversed either iteratively or recursively. Could you implement both? 13 | 14 | **********************************************************************************/ 15 | 16 | // How to do it: 17 | // iteration 18 | 19 | 20 | /** 21 | * Definition for singly-linked list. 22 | * struct ListNode { 23 | * int val; 24 | * ListNode *next; 25 | * ListNode(int x) : val(x), next(NULL) {} 26 | * }; 27 | */ 28 | class Solution { 29 | public: 30 | ListNode* reverseList(ListNode* head) { 31 | // iteration 32 | if (head == NULL || head->next == NULL) 33 | return head; 34 | 35 | ListNode* pre = head; 36 | ListNode* next = head->next; 37 | ListNode* nextnext = head->next->next; 38 | pre->next = NULL; 39 | while(next){ 40 | nextnext = next->next; 41 | next->next = pre; 42 | pre = next; 43 | next = nextnext; 44 | } 45 | return pre; 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /romanToInteger/romanToInteger.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/roman-to-integer/ 2 | // Author : weekend27 3 | // Date : 2015-12-17 4 | 5 | /********************************************************************************** 6 | 7 | Given a roman numeral, convert it to an integer. 8 | 9 | Input is guaranteed to be within the range from 1 to 3999. 10 | 11 | **********************************************************************************/ 12 | 13 | // How to do it: 14 | // ref: http://blog.csdn.net/wzy_1988/article/details/17057929 15 | /* 16 | 计数规则: 17 | 1. 相同的数字连写,所表示的数等于这些数字相加得到的数,例如:III = 3 18 | 2. 小的数字在大的数字右边,所表示的数等于这些数字相加得到的数,例如:VIII = 8 19 | 3. 小的数字,限于(I、X和C)在大的数字左边,所表示的数等于大数减去小数所得的数,例如:IV = 4 20 | 4. 正常使用时,连续的数字重复不得超过三次 21 | 5. 在一个数的上面画横线,表示这个数扩大1000倍(本题只考虑3999以内的数,所以用不到这条规则) 22 | */ 23 | // 从前向后遍历罗马数字,如果某个数比前一个数小,则加上该数。反之,减去前一个数的两倍然后加上该数 24 | 25 | 26 | class Solution { 27 | public: 28 | inline int c2n(char c){ 29 | switch(c){ 30 | case 'I': return 1; 31 | case 'V': return 5; 32 | case 'X': return 10; 33 | case 'L': return 50; 34 | case 'C': return 100; 35 | case 'D': return 500; 36 | case 'M': return 1000; 37 | default : return 0; 38 | } 39 | } 40 | int romanToInt(string s) { 41 | int result = 0; 42 | for (int i = 0; i < s.size(); i++){ 43 | if (i > 0 && c2n(s[i]) > c2n(s[i-1])){ 44 | result += (c2n(s[i]) - 2*c2n(s[i-1])); 45 | } 46 | else { 47 | result += c2n(s[i]); 48 | } 49 | } 50 | return result; 51 | } 52 | }; 53 | -------------------------------------------------------------------------------- /rotateArray/rotateArray_1.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/rotate-array/ 2 | // Author : weekend27 3 | // Date : 2015-12-02 4 | 5 | /********************************************************************************** 6 | 7 | Rotate an array of n elements to the right by k steps. 8 | 9 | For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. 10 | 11 | Note: 12 | Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. 13 | 14 | **********************************************************************************/ 15 | 16 | // How to do it: 17 | // use two arrays to put the elements from two parts, and then put them back to the original array. 18 | // space O(n) 19 | 20 | class Solution { 21 | public: 22 | void rotate(vector& nums, int k) { 23 | int len = nums.size(); 24 | k = k % len; 25 | if(k == 0) 26 | return; 27 | vector p, q; 28 | for (int i = 0; i < len - k; i++) 29 | p.push_back(nums[i]); 30 | for (int i = len - k; i < len; i++) 31 | q.push_back(nums[i]); 32 | for (int i = 0; i < k; i++) 33 | nums[i] = q[i]; 34 | for (int i = k; i < len; i++) 35 | nums[i] = p[i-k]; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /rotateArray/rotateArray_2.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/rotate-array/ 2 | // Author : weekend27 3 | // Date : 2015-12-02 4 | 5 | /********************************************************************************** 6 | 7 | Rotate an array of n elements to the right by k steps. 8 | 9 | For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. 10 | 11 | Note: 12 | Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. 13 | 14 | **********************************************************************************/ 15 | 16 | // How to do it: 17 | // three reverses:(1)the whole; (2)the front part; (3)the end part. 18 | 19 | class Solution { 20 | public: 21 | void rotate(vector& nums, int k) { 22 | int len = nums.size(); 23 | k = k % len; 24 | reverse(nums.begin(), nums.end()); 25 | reverse(nums.begin(), nums.begin()+k); 26 | reverse(nums.begin()+k, nums.end()); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /rotateArray/rotateArray_3.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/rotate-array/ 2 | // Author : weekend27 3 | // Date : 2015-12-02 4 | 5 | /********************************************************************************** 6 | 7 | Rotate an array of n elements to the right by k steps. 8 | 9 | For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. 10 | 11 | Note: 12 | Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. 13 | 14 | **********************************************************************************/ 15 | 16 | // How to do it: 17 | // use a new array:numsCopy, nums[(i+k)%len] = numsCopy[i]; 18 | 19 | class Solution { 20 | public: 21 | void rotate(vector& nums, int k) { 22 | // time O(n) 23 | int len = nums.size(); 24 | if (k == 0) 25 | return; 26 | k = k % len; 27 | vector numsCopy(len); 28 | for (int i = 0; i < len; i++) 29 | numsCopy[i] = nums[i]; 30 | 31 | for (int i = 0; i < len; i++) 32 | nums[(i+k)%len] = numsCopy[i]; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /rotateImage/rotateImage.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/rotate-image/ 2 | // Author : weekend27 3 | // Date : 2015-12-07 4 | 5 | /********************************************************************************** 6 | 7 | You are given an n x n 2D matrix representing an image. 8 | 9 | Rotate the image by 90 degrees (clockwise). 10 | 11 | Follow up: 12 | Could you do this in-place? 13 | 14 | **********************************************************************************/ 15 | 16 | // How to do it: 17 | // use another matrix 18 | // space O(n*n) 19 | 20 | class Solution { 21 | public: 22 | void rotate(vector>& matrix) { 23 | int n = matrix.size(); 24 | vector> tmp(n, vector(n)); 25 | 26 | for (int i = 0; i < n; i++) 27 | for (int j = 0; j < n; j++) 28 | tmp[i][j] = matrix[i][j]; 29 | 30 | for (int i = 0; i < n; i++) 31 | for (int j = 0; j < n; j++) 32 | matrix[j][n - 1 - i] = tmp[i][j]; 33 | 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /rotateImage/rotateImage_1.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/rotate-image/ 2 | // Author : weekend27 3 | // Date : 2015-12-07 4 | 5 | /********************************************************************************** 6 | 7 | You are given an n x n 2D matrix representing an image. 8 | 9 | Rotate the image by 90 degrees (clockwise). 10 | 11 | Follow up: 12 | Could you do this in-place? 13 | 14 | **********************************************************************************/ 15 | 16 | // How to do it: 17 | // the piece of paper folded up and down along 18 | // and then fold diagonally 19 | 20 | class Solution { 21 | public: 22 | void rotate(vector>& matrix) { 23 | int n = matrix.size(); 24 | int tmp; 25 | 26 | // the piece of paper folded up and down along 27 | for (int i = 0; i < n / 2; i++){ 28 | for (int j = 0; j < n; j++){ 29 | tmp = matrix[i][j]; 30 | matrix[i][j] = matrix[n-1-i][j]; 31 | matrix[n-1-i][j] = tmp; 32 | } 33 | } 34 | 35 | // and then fold diagonally 36 | for (int i = 0; i < n; i++){ 37 | for (int j = 0; j < i; j++){ 38 | tmp = matrix[i][j]; 39 | matrix[i][j] = matrix[j][i]; 40 | matrix[j][i] = tmp; 41 | } 42 | } 43 | 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /rotateList/rotateList.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/rotate-list/ 2 | // Author : weekend27 3 | // Date : 2015-12-10 4 | 5 | /********************************************************************************** 6 | 7 | Given a list, rotate the list to the right by k places, where k is non-negative. 8 | 9 | For example: 10 | Given 1->2->3->4->5->NULL and k = 2, 11 | return 4->5->1->2->3->NULL. 12 | 13 | **********************************************************************************/ 14 | 15 | // How to do it: 16 | // connect the head and the tail to a loop 17 | // find the break-point position 18 | // break up and return 19 | 20 | 21 | /** 22 | * Definition for singly-linked list. 23 | * struct ListNode { 24 | * int val; 25 | * ListNode *next; 26 | * ListNode(int x) : val(x), next(NULL) {} 27 | * }; 28 | */ 29 | class Solution { 30 | public: 31 | ListNode* rotateRight(ListNode* head, int k) { 32 | if (!head || k == 0) 33 | return head; 34 | 35 | // get the len of list 36 | int len = 1; 37 | ListNode* p = head; 38 | while(p->next){ 39 | p = p->next; 40 | len++; 41 | } 42 | 43 | k = len - k % len; 44 | 45 | // connect the head and the tail to a loop 46 | p->next = head; 47 | 48 | for (int i = 0; i < k; i++){ 49 | p = p->next; 50 | } 51 | 52 | // get new head and break up the loop 53 | head = p->next; 54 | p->next = NULL; 55 | return head; 56 | } 57 | }; 58 | -------------------------------------------------------------------------------- /sameTree/sameTree.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/same-tree/ 2 | // Author : weekend27 3 | // Date : 2015-12-11 4 | 5 | /********************************************************************************** 6 | 7 | Given two binary trees, write a function to check if they are equal or not. 8 | 9 | Two binary trees are considered equal if they are structurally identical and the nodes have the same value. 10 | 11 | **********************************************************************************/ 12 | 13 | // How to do it: 14 | // DFS 15 | // time complexity: O(n) 16 | 17 | 18 | /** 19 | * Definition for a binary tree node. 20 | * struct TreeNode { 21 | * int val; 22 | * TreeNode *left; 23 | * TreeNode *right; 24 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 25 | * }; 26 | */ 27 | class Solution { 28 | public: 29 | bool isSameTree(TreeNode* p, TreeNode* q) { 30 | // DFS, time complexity O(n) 31 | if (p == NULL && q == NULL) 32 | return true; 33 | else if (p == NULL || q == NULL) 34 | return false; 35 | if (p->val == q->val) 36 | { 37 | bool left = isSameTree(p->left, q->left); 38 | bool right = isSameTree(p->right, q->right); 39 | return left && right; 40 | } 41 | 42 | return false; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /searchA2DMatrix/search2DMatrix.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean searchMatrix(int[][] matrix, int target) { 3 | if (matrix == null || matrix.length == 0) return false; 4 | 5 | int i = 0; 6 | int j = matrix[0].length - 1; 7 | while (i < matrix.length && j > -1) { 8 | if (matrix[i][j] == target) { 9 | return true; 10 | } else if (matrix[i][j] > target) { 11 | j--; 12 | } else { 13 | i++; 14 | } 15 | } 16 | return false; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /searchA2DMatrix/searchA2DMatrix.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/search-a-2d-matrix/ 2 | // Author : weekend27 3 | // Date : 2015-12-07 4 | 5 | /********************************************************************************** 6 | 7 | Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 8 | 9 | Integers in each row are sorted from left to right. 10 | The first integer of each row is greater than the last integer of the previous row. 11 | For example, 12 | 13 | Consider the following matrix: 14 | 15 | [ 16 | [1, 3, 5, 7], 17 | [10, 11, 16, 20], 18 | [23, 30, 34, 50] 19 | ] 20 | Given target = 3, return true. 21 | 22 | **********************************************************************************/ 23 | 24 | // How to do it: 25 | // special "binary search" 26 | 27 | 28 | 29 | class Solution { 30 | public: 31 | bool searchMatrix(vector>& matrix, int target) { 32 | int i = 0, j = matrix[0].size() - 1; 33 | 34 | while (i < matrix.size() && j >= 0){ 35 | if (matrix[i][j] == target) 36 | return true; 37 | else if (matrix[i][j] > target) 38 | j--; 39 | else 40 | i++; 41 | } 42 | 43 | return false; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /searchForARange/searchForARange2.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] searchRange(int[] nums, int target) { 3 | int[] result = {-1, -1}; 4 | if (nums == null || nums.length == 0) { 5 | return result; 6 | } 7 | 8 | int left = 0; 9 | int right = nums.length - 1; 10 | while (left <= right) { 11 | int mid = left + (right - left) / 2; 12 | if (nums[mid] == target) { 13 | int rl = mid; 14 | for (int i = mid; i > -1; i--) { 15 | if (nums[i] == nums[mid]) { 16 | rl = i; 17 | } else { 18 | break; 19 | } 20 | } 21 | int rr = mid; 22 | for (int i = mid; i < nums.length; i++) { 23 | if (nums[i] == nums[mid]) { 24 | rr = i; 25 | } else { 26 | break; 27 | } 28 | } 29 | result[0] = rl; 30 | result[1] = rr; 31 | return result; 32 | } else if (nums[mid] < target) { 33 | left = mid + 1; 34 | } else { 35 | right = mid - 1; 36 | } 37 | } 38 | return result; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /searchInRotatedSortedArray/searchInRotatedSortedArray.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/search-in-rotated-sorted-array/ 2 | // Author : weekend27 3 | // Date : 2015-11-19 4 | 5 | /********************************************************************************** 6 | 7 | Suppose a sorted array is rotated at some pivot unknown to you beforehand. 8 | 9 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 10 | 11 | You are given a target value to search. If found in the array return its index, otherwise return -1. 12 | 13 | You may assume no duplicate exists in the array. 14 | 15 | **********************************************************************************/ 16 | 17 | // How to do it: 18 | // binary search, the difficulty is determining the left and right boundaries. 19 | 20 | class Solution { 21 | public: 22 | int search(vector& nums, int target) { 23 | int len = nums.size(); 24 | int low = 0, high = len; 25 | 26 | while(low != high){ // error:low <= high, example:[1] search:0 wrong answer:0 expected answer:-1 27 | const int mid = low + (high - low) / 2; // mid = (low + high) / 2 may encounter overflow 28 | if (nums[mid] == target) 29 | return mid; 30 | if (nums[low] <= nums[mid]){ 31 | if (nums[low] <= target && target < nums[mid]){ 32 | high = mid; 33 | } 34 | else{ 35 | low = mid + 1; 36 | } 37 | } 38 | else{ 39 | if (nums[mid] < target && target <= nums[high - 1]){ // error:nums[high] 40 | low = mid + 1; 41 | } 42 | else{ 43 | high = mid; 44 | } 45 | } 46 | } 47 | return -1; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /searchInRotatedSortedArray/searchInRotatedSortedArray.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int search(int[] nums, int target) { 3 | if (nums.length == 0) return -1; 4 | 5 | int left = 0; 6 | int right = nums.length - 1; 7 | 8 | while (left <= right) { 9 | int mid = left + (right - left) / 2; 10 | 11 | if (nums[mid] == target) { 12 | return mid; 13 | } 14 | if (nums[mid] >= nums[left]) { 15 | if (target >= nums[left] && target < nums[mid]) { 16 | right = mid; 17 | } else { 18 | left = mid + 1; 19 | } 20 | } else { 21 | if (target > nums[mid] && target <= nums[right]) { 22 | left = mid; 23 | } else { 24 | right = mid - 1; 25 | } 26 | } 27 | } 28 | 29 | return -1; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /searchInRotatedSortedArray/searchInRotatedSortedArrayII.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean search(int[] nums, int target) { 3 | if (nums == null || nums.length == 0) return false; 4 | 5 | int left = 0; 6 | int right = nums.length - 1; 7 | while (left <= right) { 8 | int mid = left + (right - left) / 2; 9 | if (nums[mid] == target) { 10 | return true; 11 | } 12 | if (nums[mid] > nums[left]) { 13 | if (target >= nums[left] && target < nums[mid]) { 14 | right = mid; 15 | } else { 16 | left = mid + 1; 17 | } 18 | } else if (nums[mid] < nums[left]) { 19 | if (target > nums[mid] && target <= nums[right]) { 20 | left = mid + 1; 21 | } else { 22 | right = mid; 23 | } 24 | } else { 25 | left++; 26 | } 27 | } 28 | return false; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /searchInsertPosition/searchInsertPosition.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/search-insert-position/ 2 | // Author : weekend27 3 | // Date : 2015-12-06 4 | 5 | /********************************************************************************** 6 | 7 | Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. 8 | 9 | You may assume no duplicates in the array. 10 | 11 | Here are few examples. 12 | [1,3,5,6], 5 → 2 13 | [1,3,5,6], 2 → 1 14 | [1,3,5,6], 7 → 4 15 | [1,3,5,6], 0 → 0 16 | 17 | **********************************************************************************/ 18 | 19 | // How to do it: 20 | // binary search 21 | 22 | class Solution { 23 | public: 24 | int searchInsert(vector& nums, int target) { 25 | int n = nums.size(); 26 | if (n == 0) 27 | return 0; 28 | 29 | int l = 0, r = n - 1, m = 0; 30 | while (l <= r){ 31 | m = l + (r - l) / 2; 32 | if (nums[m] == target) 33 | return m; 34 | else if (nums[m] > target) 35 | r = m - 1; 36 | else 37 | l = m + 1; 38 | } 39 | 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /searchInsertPosition/searchInsertPosition.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int searchInsert(int[] nums, int target) { 3 | if (nums == null || nums.length == 0) { 4 | return 0; 5 | } 6 | 7 | if (target < nums[0]) { 8 | return 0; 9 | } 10 | else if (target > nums[nums.length - 1]) { 11 | return nums.length; 12 | } 13 | else { 14 | int left = 0; 15 | int right = nums.length - 1; 16 | while (left <= right) { 17 | int mid = left + (right - left) / 2; 18 | 19 | if (nums[mid] == target) { 20 | return mid; 21 | } else if (target > nums[left] && target < nums[right] && (left == right - 1)) { 22 | return right; 23 | } else if (nums[left] == target) { 24 | return left; 25 | } else if (nums[right] == target) { 26 | return right; 27 | } else if (nums[mid] > target) { 28 | right = mid - 1; 29 | } else { 30 | left = mid + 1; 31 | } 32 | } 33 | } 34 | 35 | return -1; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /setMatrixZeroes/setMatrixZeroes_1.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/set-matrix-zeroes/ 2 | // Author : weekend27 3 | // Date : 2015-12-07 4 | 5 | /********************************************************************************** 6 | 7 | Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. 8 | 9 | **********************************************************************************/ 10 | 11 | // How to do it: 12 | // use another array to record the zero position 13 | // and then set the original row and col to zero 14 | // space O(m+n) 15 | 16 | 17 | class Solution { 18 | public: 19 | void setZeroes(vector>& matrix) { 20 | int row = matrix.size(); 21 | if (row == 0) 22 | return; 23 | int col = matrix[0].size(); 24 | if (col == 0) 25 | return; 26 | 27 | bool* flag = new bool[row+col]; 28 | memset(flag, false, row+col); 29 | 30 | // record the zero position 31 | for (int i = 0; i < row; i++){ 32 | for (int j = 0; j < col; j++){ 33 | if (matrix[i][j] == 0){ 34 | flag[i] = 1; 35 | flag[row+j] = 1; 36 | } 37 | } 38 | } 39 | 40 | // set the col to zero 41 | for (int i = 0; i < row; i++){ 42 | if (flag[i]){ 43 | for (int j = 0; j < col; j++) 44 | matrix[i][j] = 0; 45 | } 46 | } 47 | 48 | // set the row to zero 49 | for (int j = row; j < row+col; j++){ 50 | if (flag[j]){ 51 | for (int i = 0; i < row; i++) 52 | matrix[i][j-row] = 0; 53 | } 54 | } 55 | 56 | 57 | } 58 | }; 59 | -------------------------------------------------------------------------------- /singleNumber/singleNumber.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/single-number/ 2 | // Author : weekend27 3 | // Date : 2015-12-22 4 | 5 | /********************************************************************************** 6 | 7 | Given an array of integers, every element appears twice except for one. Find that single one. 8 | 9 | Note: 10 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 11 | 12 | **********************************************************************************/ 13 | 14 | // How to do it: 15 | // ref: http://bangbingsyb.blogspot.sg/2014/11/leetcode-single-number-i-ii.html 16 | /* 17 | 和find duplicate正好相反,但是仍然可以用排序或hash table解决。排序以后,对每个坐标i,查找A[i-1], A[i+1]中是否有等于A[i]的,没有则为要找的数。 18 | 或者用hash table/set来记录扫描过的数字。如果A[i]不在hash table中,则插入,如果已经在,则在hash table中删除,最后table中剩下的就是要找的数。 19 | 但排序法事件复杂度是O(nlogn),而hash table尽管是O(n)事件复杂度,需要o(n)的extra memory。 20 | 21 | 这题的终极解法是利用位运算中的异或:x^x = 0, x^0 = x。并且异或有交换律:1^1^0 = 0 = 1^0^1。 22 | 所以如果将全部数字进行异或运算,所有重复元素都会被消除,最后的结果便是那个唯一的数。 23 | */ 24 | 25 | class Solution { 26 | public: 27 | int singleNumber(vector& nums) { 28 | int res = 0; 29 | for (int i = 0; i < nums.size(); i++){ 30 | res ^= nums[i]; 31 | } 32 | return res; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /singleNumber/singleNumberIII.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/single-number-iii/ 2 | // Author : weekend27 3 | // Date : 2015-12-28 4 | 5 | /********************************************************************************** 6 | 7 | Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. 8 | 9 | For example: 10 | 11 | Given nums = [1, 2, 1, 3, 2, 5], return [3, 5]. 12 | 13 | Note: 14 | The order of the result is not important. So in the above example, [5, 3] is also correct. 15 | Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity? 16 | 17 | **********************************************************************************/ 18 | 19 | // How to do it: 20 | // using sort 21 | 22 | class Solution { 23 | public: 24 | vector singleNumber(vector& nums) { 25 | vector res; 26 | sort(nums.begin(), nums.end()); 27 | if (nums.size() == 2 && nums[0] != nums[1]){ 28 | return nums; 29 | } 30 | for (int i = 0; i < nums.size();){ 31 | if (nums[i] != nums[i+1]){ 32 | res.push_back(nums[i]); 33 | i++; 34 | } 35 | else{ 36 | i += 2; 37 | } 38 | } 39 | return res; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /slidingWindowMaximum/slidingWindowMaximum.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/sliding-window-maximum/ 2 | // Author : weekend27 3 | // Date : 2016-01-15 4 | 5 | /********************************************************************************** 6 | 7 | Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. 8 | 9 | For example, 10 | Given nums = [1,3,-1,-3,5,3,6,7], and k = 3. 11 | 12 | Window position Max 13 | --------------- ----- 14 | [1 3 -1] -3 5 3 6 7 3 15 | 1 [3 -1 -3] 5 3 6 7 3 16 | 1 3 [-1 -3 5] 3 6 7 5 17 | 1 3 -1 [-3 5 3] 6 7 5 18 | 1 3 -1 -3 [5 3 6] 7 6 19 | 1 3 -1 -3 5 [3 6 7] 7 20 | Therefore, return the max sliding window as [3,3,5,5,6,7]. 21 | 22 | Note: 23 | You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for non-empty array. 24 | 25 | Follow up: 26 | Could you solve it in linear time? 27 | 28 | Hint: 29 | 30 | How about using a data structure such as deque (double-ended queue)? 31 | 32 | **********************************************************************************/ 33 | 34 | // How to do it: 35 | // use a deque to store temp max 36 | 37 | class Solution { 38 | public: 39 | vector maxSlidingWindow(vector& nums, int k) { 40 | vector ret; 41 | deque max; 42 | for (int i = 0; i < nums.size(); ++i) { 43 | while (!max.empty() && nums[i] > max.back()) { 44 | max.pop_back(); 45 | } 46 | max.push_back(nums[i]); 47 | if (i >= k - 1) { 48 | ret.push_back(max.front()); 49 | if (nums[i - k + 1] == max.front()) { 50 | max.pop_front(); 51 | } 52 | } 53 | } 54 | return ret; 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /sortColors/sortColors.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/sort-colors/ 2 | // Author : weekend27 3 | // Date : 2015-12-05 4 | 5 | /********************************************************************************** 6 | 7 | Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. 8 | 9 | Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. 10 | 11 | Note: 12 | You are not suppose to use the library's sort function for this problem. 13 | 14 | click to show follow up. 15 | 16 | Follow up: 17 | A rather straight forward solution is a two-pass algorithm using counting sort. 18 | First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's. 19 | 20 | Could you come up with an one-pass algorithm using only constant space? 21 | 22 | **********************************************************************************/ 23 | 24 | // How to do it: 25 | // just do it as "Follow up" 26 | // a low algorithom 27 | 28 | 29 | class Solution { 30 | public: 31 | void sortColors(vector& nums) { 32 | int cntRed = 0; 33 | int cntWhite = 0; 34 | int cntBlue = 0; 35 | 36 | for (int i = 0; i < nums.size(); i++){ 37 | if (nums[i] == 0) 38 | cntRed++; 39 | else if (nums[i] == 1) 40 | cntWhite++; 41 | else 42 | cntBlue++; 43 | } 44 | 45 | for (int i = 0; i < cntRed; i++) 46 | nums[i] = 0; 47 | for (int i = cntRed; i < cntRed + cntWhite; i++) 48 | nums[i] = 1; 49 | for (int i = cntRed + cntWhite; i < nums.size(); i++) 50 | nums[i] = 2; 51 | } 52 | }; 53 | -------------------------------------------------------------------------------- /sqrt(x)/sqrt(x).cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/sqrtx/ 2 | // Author : weekend27 3 | // Date : 2015-12-24 4 | 5 | /********************************************************************************** 6 | 7 | Implement int sqrt(int x). 8 | 9 | Compute and return the square root of x. 10 | 11 | **********************************************************************************/ 12 | 13 | // How to do it: 14 | // binary search 15 | // note that the final return number 16 | 17 | class Solution { 18 | public: 19 | int mySqrt(int x) { 20 | long long l = 0; 21 | long long r = x / 2 + 1; 22 | while (l <= r) 23 | { 24 | long long mid = l + (r - l) / 2; 25 | long long sq = mid * mid; 26 | if (sq == x) 27 | { 28 | return mid; 29 | } 30 | else if (sq < x) 31 | { 32 | l = mid + 1; 33 | } 34 | else 35 | { 36 | r = mid - 1; 37 | } 38 | } 39 | return r; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /summaryRanges/summaryRanges.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/summary-ranges/ 2 | // Author : weekend27 3 | // Date : 2015-12-02 4 | 5 | /********************************************************************************** 6 | 7 | Given a sorted integer array without duplicates, return the summary of its ranges. 8 | 9 | For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"]. 10 | 11 | **********************************************************************************/ 12 | 13 | // How to do it: 14 | // two pointers 15 | 16 | class Solution { 17 | public: 18 | vector summaryRanges(vector& nums){ 19 | vector srVec; 20 | if (nums.size()<1) 21 | return srVec; 22 | int start = 0; 23 | int end = 0; 24 | char temp[256]; 25 | while (end < nums.size()){ 26 | if (end + 1 < nums.size() && nums[end+1] == nums[end]+1){ 27 | end++; 28 | } else{ 29 | if (start == end){ 30 | sprintf(temp, "%d", nums[start]); 31 | } else{ 32 | sprintf(temp, "%d->%d", nums[start], nums[end]); 33 | } 34 | srVec.push_back(temp); 35 | end++; 36 | start = end; 37 | } 38 | } 39 | return srVec; 40 | } 41 | 42 | }; 43 | -------------------------------------------------------------------------------- /superUglyNumber/superUglyNumber.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/super-ugly-number/ 2 | // Author : weekend27 3 | // Date : 2015-12-24 4 | 5 | /********************************************************************************** 6 | 7 | Write a program to find the nth super ugly number. 8 | 9 | Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k. For example, [1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32] is the sequence of the first 12 super ugly numbers given primes = [2, 7, 13, 19] of size 4. 10 | 11 | Note: 12 | (1) 1 is a super ugly number for any given primes. 13 | (2) The given numbers in primes are in ascending order. 14 | (3) 0 < k ≤ 100, 0 < n ≤ 106, 0 < primes[i] < 1000. 15 | 16 | **********************************************************************************/ 17 | 18 | // How to do it: 19 | // look at the code 20 | 21 | 22 | class Solution { 23 | public: 24 | int nthSuperUglyNumber(int n, vector& primes) { 25 | vector superUglyNumbers; 26 | superUglyNumbers.push_back(1); 27 | int numPrimes = primes.size(); 28 | vector index(numPrimes, 0); 29 | // add super ugly number up to nth 30 | while (superUglyNumbers.size() < n) 31 | { 32 | int nextSuperUglyNumber = superUglyNumbers[index[0]] * primes[0]; 33 | for (int i = 0; i < numPrimes; i++) 34 | { 35 | nextSuperUglyNumber = min(nextSuperUglyNumber, superUglyNumbers[index[i]] * primes[i]); 36 | } 37 | for (int i = 0; i < numPrimes; i++) 38 | { 39 | if (nextSuperUglyNumber == superUglyNumbers[index[i]] * primes[i]) 40 | { 41 | index[i]++; 42 | } 43 | } 44 | superUglyNumbers.push_back(nextSuperUglyNumber); 45 | } 46 | 47 | return superUglyNumbers[n-1]; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /swapNodesInPairs/swapNodesInPairs.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/swap-nodes-in-pairs/ 2 | // Author : weekend27 3 | // Date : 2015-12-10 4 | 5 | /********************************************************************************** 6 | 7 | Given a linked list, swap every two adjacent nodes and return its head. 8 | 9 | For example, 10 | Given 1->2->3->4, you should return the list as 2->1->4->3. 11 | 12 | Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. 13 | 14 | **********************************************************************************/ 15 | 16 | // How to do it: 17 | // a pointer problem 18 | // swap two adjacent nodes and then move on 19 | 20 | /** 21 | * Definition for singly-linked list. 22 | * struct ListNode { 23 | * int val; 24 | * ListNode *next; 25 | * ListNode(int x) : val(x), next(NULL) {} 26 | * }; 27 | */ 28 | class Solution { 29 | public: 30 | ListNode* swapPairs(ListNode* head) { 31 | if (!head || !head->next){ 32 | return head; 33 | } 34 | 35 | ListNode* p = new ListNode(0); 36 | p->next = head; 37 | head = p; 38 | while(true){ 39 | if (p->next == NULL) {break;} 40 | if (p->next->next == NULL) {break;} 41 | ListNode* p1 = p->next; 42 | ListNode* p2 = p1->next; 43 | p1->next = p2->next; 44 | p2->next = p1; 45 | p->next = p2; 46 | p = p1; 47 | } 48 | return head->next; 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /symmetricTree/symmetricTree.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/symmetric-tree/ 2 | // Author : weekend27 3 | // Date : 2015-12-11 4 | 5 | /********************************************************************************** 6 | 7 | Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). 8 | 9 | For example, this binary tree is symmetric: 10 | 11 | 1 12 | / \ 13 | 2 2 14 | / \ / \ 15 | 3 4 4 3 16 | But the following is not: 17 | 1 18 | / \ 19 | 2 2 20 | \ \ 21 | 3 3 22 | Note: 23 | Bonus points if you could solve it both recursively and iteratively. 24 | 25 | **********************************************************************************/ 26 | 27 | // How to do it: 28 | // 3 features: 29 | // 1. left->val == right->val 30 | // 2. left->left, right->right 31 | // 3. left->right, right->left 32 | 33 | 34 | /** 35 | * Definition for a binary tree node. 36 | * struct TreeNode { 37 | * int val; 38 | * TreeNode *left; 39 | * TreeNode *right; 40 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 41 | * }; 42 | */ 43 | class Solution { 44 | public: 45 | bool isSymmetric(TreeNode* root) { 46 | // recursion 47 | if (root == NULL) 48 | return true; 49 | return mirror(root->left, root->right); 50 | } 51 | 52 | bool mirror(TreeNode* left, TreeNode* right){ 53 | if (left == NULL && right == NULL) 54 | return true; 55 | else if (left == NULL || right == NULL) 56 | return false; 57 | 58 | bool mirr1 = left->val == right->val; 59 | bool mirr2 = mirror(left->left, right->right); 60 | bool mirr3 = mirror(left->right, right->left); 61 | 62 | return mirr1 && mirr2 && mirr3; 63 | } 64 | }; 65 | -------------------------------------------------------------------------------- /trappingRainWater/trappingRainWater.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/trapping-rain-water/ 2 | // Author : weekend27 3 | // Date : 2015-12-19 4 | 5 | /********************************************************************************** 6 | 7 | Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. 8 | 9 | For example, 10 | Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. 11 | 12 | **********************************************************************************/ 13 | 14 | // How to do it: 15 | // ref: comments from 李瑞远 on http://fisherlei.blogspot.sg/2013/01/leetcode-trapping-rain-water.html 16 | 17 | class Solution { 18 | public: 19 | int trap(vector& height) { 20 | int len = height.size(); 21 | if (len < 3){ 22 | return 0; 23 | } 24 | int start = 0, end = len - 1; 25 | int result = 0, minH = 0; 26 | 27 | minH = min(height[start], height[end]); 28 | result = minH * (end - start - 1); 29 | 30 | while (start < end - 1){ 31 | if (height[start] < height[end]){ 32 | start++; 33 | result = result - min(minH, height[start]); 34 | } 35 | else { 36 | end--; 37 | result = result - min(minH, height[end]); 38 | } 39 | if (height[start] > minH && height[end] > minH){ 40 | result += min(height[start] - minH, height[end] - minH) * (end -start - 1); // add overflow part 41 | minH = min(height[start], height[end]); 42 | } 43 | } 44 | return result; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /twoSum/twoSum.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/two-sum/ 2 | // Author : weekend27 3 | // Date : 2015-12-03 4 | 5 | /********************************************************************************** 6 | 7 | Given an array of integers, find two numbers such that they add up to a specific target number. 8 | 9 | The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. 10 | 11 | You may assume that each input would have exactly one solution. 12 | 13 | Input: numbers={2, 7, 11, 15}, target=9 14 | Output: index1=1, index2=2 15 | 16 | **********************************************************************************/ 17 | 18 | // How to do it: 19 | // two steps: 20 | // (1) two pointers from the start and the end to match the target, and then break 21 | // (2) traverse the original array to find the two index 22 | 23 | class Solution { 24 | public: 25 | vector twoSum(vector& nums, int target) { 26 | vector v(nums); 27 | sort(v.begin(), v.end()); 28 | 29 | int l = 0, r = v.size() - 1; 30 | while(l < r){ 31 | if (v[l] + v[r] == target) 32 | break; 33 | else if (v[l] + v[r] > target) 34 | r--; 35 | else 36 | l++; 37 | } 38 | 39 | vector index; 40 | for (int i = 0, n = 2; i < nums.size(); i++){ 41 | if(v[l] == nums[i] || v[r] == nums[i]){ 42 | index.push_back(i + 1); 43 | if(--n == 0) 44 | break; 45 | } 46 | } 47 | return index; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /twoSum/twoSum.java: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/two-sum/ 2 | // Author : weekend27 3 | // Date : 2015-04-11 4 | 5 | /********************************************************************************** 6 | 7 | Given an array of integers, find two numbers such that they add up to a specific target number. 8 | 9 | The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. 10 | 11 | You may assume that each input would have exactly one solution. 12 | 13 | Example: 14 | Given nums = [2, 7, 11, 15], target = 9, 15 | 16 | Because nums[0] + nums[1] = 2 + 7 = 9, 17 | return [0, 1]. 18 | UPDATE (2016/2/13): 19 | The return format had been changed to zero-based indices. Please read the above updated description carefully. 20 | 21 | **********************************************************************************/ 22 | 23 | // How to do it: 24 | // ref: https://leetcode.com/discuss/8150/accepted-java-o-n-solution 25 | // hashmap to store the value and index 26 | // just O(n) time complexity, traverse just once! 27 | 28 | public class Solution { 29 | public int[] twoSum(int[] nums, int target) { 30 | int[] result = new int[2]; 31 | Map map = new HashMap(); 32 | for (int i = 0; i < nums.length; ++i) { 33 | if (map.containsKey(target - nums[i])) { 34 | result[1] = i; 35 | result[0] = map.get(target - nums[i]); 36 | return result; 37 | } 38 | map.put(nums[i], i); 39 | } 40 | return result; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /uglyNumber/uglyNumber.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/ugly-number/ 2 | // Author : weekend27 3 | // Date : 2015-12-24 4 | 5 | /********************************************************************************** 6 | 7 | Write a program to check whether a given number is an ugly number. 8 | 9 | Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. 10 | 11 | Note that 1 is typically treated as an ugly number. 12 | 13 | **********************************************************************************/ 14 | 15 | // How to do it: 16 | // look at the code 17 | 18 | 19 | class Solution { 20 | public: 21 | bool isUgly(int num) { 22 | while (num >= 2){ 23 | if (num % 2 == 0){ 24 | num /= 2; 25 | } 26 | else if (num % 3 == 0){ 27 | num /= 3; 28 | } 29 | else if (num % 5 == 0){ 30 | num /= 5; 31 | } 32 | else { 33 | return false; 34 | } 35 | } 36 | return num == 1; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /uglyNumber/uglyNumberII.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/ugly-number-ii/ 2 | // Author : weekend27 3 | // Date : 2015-12-24 4 | 5 | /********************************************************************************** 6 | 7 | Write a program to find the n-th ugly number. 8 | 9 | Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers. 10 | 11 | Note that 1 is typically treated as an ugly number. 12 | 13 | Hint: 14 | 15 | The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones. 16 | An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number. 17 | The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3. 18 | Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5). 19 | 20 | **********************************************************************************/ 21 | 22 | // How to do it: 23 | // ref: http://www.cnblogs.com/grandyang/p/4743837.html 24 | /* 25 | 根据提示中的信息,我们知道丑陋数序列可以拆分为下面3个子列表: 26 | 27 | (1) 1×2, 2×2, 3×2, 4×2, 5×2, … 28 | (2) 1×3, 2×3, 3×3, 4×3, 5×3, … 29 | (3) 1×5, 2×5, 3×5, 4×5, 5×5, … 30 | 31 | 仔细观察上述三个列表,我们可以发现每个子列表都是一个丑陋数乘以2,3,5,而这些丑陋数的值就是从已经生成的序列中取出来的,我们每次都从三个列表中取出当前最小的那个加入序列. 32 | */ 33 | 34 | class Solution { 35 | public: 36 | int nthUglyNumber(int n) { 37 | vector res(1, 1); 38 | int i2 = 0, i3 = 0, i5 = 0; 39 | while (res.size() < n){ 40 | int m2 = res[i2] * 2, m3 = res[i3] * 3, m5 = res[i5] * 5; 41 | int mn = min(m2, min(m3, m5)); 42 | if (mn == m2) {++i2;} 43 | if (mn == m3) {++i3;} 44 | if (mn == m5) {++i5;} 45 | res.push_back(mn); 46 | } 47 | return res.back(); 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /uniquePaths/uniquePaths.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/unique-paths/ 2 | // Author : weekend27 3 | // Date : 2015-12-03 4 | 5 | /********************************************************************************** 6 | 7 | A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). 8 | 9 | The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). 10 | 11 | How many possible unique paths are there? 12 | 13 | Above is a 3 x 7 grid. How many possible unique paths are there? 14 | 15 | Note: m and n will be at most 100. 16 | 17 | **********************************************************************************/ 18 | 19 | // How to do it: 20 | // dynamic programming 21 | 22 | 23 | class Solution { 24 | public: 25 | int uniquePaths(int m, int n) { 26 | vector> v(m, vector(n, 1)); 27 | for (int i = 1; i < m; i++) 28 | for (int j = 1; j < n; j++) 29 | v[i][j] = v[i-1][j] + v[i][j-1]; 30 | 31 | return v[m-1][n-1]; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /uniquePaths/uniquePaths_1.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/unique-paths/ 2 | // Author : weekend27 3 | // Date : 2015-12-03 4 | 5 | /********************************************************************************** 6 | 7 | A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). 8 | 9 | The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). 10 | 11 | How many possible unique paths are there? 12 | 13 | Above is a 3 x 7 grid. How many possible unique paths are there? 14 | 15 | Note: m and n will be at most 100. 16 | 17 | **********************************************************************************/ 18 | 19 | // How to do it: 20 | // dynamic programming 21 | 22 | 23 | class Solution { 24 | public: 25 | int uniquePaths(int m, int n) { 26 | vector v(n, 1); 27 | for (int i = 1; i < m; i++) 28 | for (int j = 1; j < n; j++) 29 | v[j] += v[j-1]; 30 | 31 | return v[n-1]; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /validAnagram/validAnagram.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/valid-anagram/ 2 | // Author : weekend27 3 | // Date : 2015-12-15 4 | 5 | /********************************************************************************** 6 | 7 | Given two strings s and t, write a function to determine if t is an anagram of s. 8 | 9 | For example, 10 | s = "anagram", t = "nagaram", return true. 11 | s = "rat", t = "car", return false. 12 | 13 | Note: 14 | You may assume the string contains only lowercase alphabets. 15 | 16 | Follow up: 17 | What if the inputs contain unicode characters? How would you adapt your solution to such case? 18 | 19 | **********************************************************************************/ 20 | 21 | // How to do it: 22 | // first sort, then check if they are equal 23 | 24 | class Solution { 25 | public: 26 | bool isAnagram(string s, string t) { 27 | sort(s.begin(), s.end()); 28 | sort(t.begin(), t.end()); 29 | return s == t; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /validPalindrome/validPalindrome.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/valid-palindrome/ 2 | // Author : weekend27 3 | // Date : 2015-12-17 4 | 5 | /********************************************************************************** 6 | 7 | Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 8 | 9 | For example, 10 | "A man, a plan, a canal: Panama" is a palindrome. 11 | "race a car" is not a palindrome. 12 | 13 | Note: 14 | Have you consider that the string might be empty? This is a good question to ask during an interview. 15 | 16 | For the purpose of this problem, we define empty string as valid palindrome. 17 | 18 | **********************************************************************************/ 19 | 20 | // How to do it: 21 | // two pointers, meet at the middle pos 22 | 23 | class Solution { 24 | public: 25 | bool isPalindrome(string s) { 26 | int begin = 0; 27 | int end = s.size() - 1; 28 | std::transform(s.begin(), s.end(), s.begin(), ::tolower); 29 | while (begin < end){ 30 | while (begin < end && !isAlpha(s[begin])) begin++; // filter non-alpha char 31 | while (begin < end && !isAlpha(s[end])) end--; // filter non-alpha char 32 | if (s[begin] != s[end]){ 33 | break; 34 | } 35 | begin++; 36 | end--; 37 | } 38 | if (begin >= end){ 39 | return true; 40 | } else { 41 | return false; 42 | } 43 | } 44 | 45 | bool isAlpha(char c){ 46 | if (c >= 'a' && c <= 'z') return true; 47 | if (c >= '0' && c <= '9') return true; 48 | return false; 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /validParentheses/validParentheses.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/valid-parentheses/ 2 | // Author : weekend27 3 | // Date : 2015-12-16 4 | 5 | /********************************************************************************** 6 | 7 | Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 8 | 9 | The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. 10 | 11 | **********************************************************************************/ 12 | 13 | // How to do it: 14 | // use a stack to map 15 | 16 | class Solution { 17 | public: 18 | bool isValid(string s) { 19 | vector stack; 20 | if (s.size() == 0){ 21 | return false; 22 | } 23 | stack.push_back(s[0]); 24 | for (int i = 1; i < s.size(); i++){ 25 | if (s[i] == '(' || s[i] == '[' || s[i] == '{'){ 26 | stack.push_back(s[i]); 27 | continue; 28 | } 29 | char curr = stack.back(); 30 | if (s[i] == ')' && curr != '('){ 31 | return false; 32 | } 33 | if (s[i] == ']' && curr != '['){ 34 | return false; 35 | } 36 | if (s[i] == '}' && curr != '{'){ 37 | return false; 38 | } 39 | stack.pop_back(); 40 | } 41 | if (stack.size() != 0){ 42 | return false; 43 | } 44 | return true; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /validateBinarySearchTree/validateBinarySearchTree.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/validate-binary-search-tree/ 2 | // Author : weekend27 3 | // Date : 2015-12-14 4 | 5 | /********************************************************************************** 6 | 7 | Given a binary tree, determine if it is a valid binary search tree (BST). 8 | 9 | Assume a BST is defined as follows: 10 | 11 | The left subtree of a node contains only nodes with keys less than the node's key. 12 | The right subtree of a node contains only nodes with keys greater than the node's key. 13 | Both the left and right subtrees must also be binary search trees. 14 | 15 | **********************************************************************************/ 16 | 17 | // How to do it: 18 | // ref: http://fisherlei.blogspot.jp/2013/01/leetcode-validate-binary-search-tree.html 19 | /* 20 | 对于每一个子树,限制它的最大,最小值,如果超过则返回false。 21 | 对于根节点,最大最小都不限制; 22 | 每一层节点,左子树限制最大值小于根,右子树最小值大于根; 23 | 但是比较有趣的是,在递归的过程中还得不断带入祖父节点的值。 24 | */ 25 | 26 | 27 | /** 28 | * Definition for a binary tree node. 29 | * struct TreeNode { 30 | * int val; 31 | * TreeNode *left; 32 | * TreeNode *right; 33 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 34 | * }; 35 | */ 36 | class Solution { 37 | public: 38 | bool isValidBST(TreeNode* root) { 39 | return verifyBST(root, false, false, 0, 0); 40 | } 41 | 42 | bool verifyBST(TreeNode* root, bool left, bool right, int lmax, int rmin){ 43 | if (root == NULL) 44 | return true; 45 | 46 | if (left && root->val >= lmax) 47 | return false; 48 | if (right && root->val <= rmin) 49 | return false; 50 | 51 | bool leftValid = verifyBST(root->left, true, right, root->val, rmin); 52 | bool rightValid = verifyBST(root->right, left, true, lmax, root->val); 53 | 54 | return leftValid && rightValid; 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /zigZagConversion/zigZagConversion.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/zigzag-conversion/ 2 | // Author : weekend27 3 | // Date : 2015-12-16 4 | 5 | /********************************************************************************** 6 | 7 | The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) 8 | 9 | P A H N 10 | A P L S I I G 11 | Y I R 12 | And then read line by line: "PAHNAPLSIIGYIR" 13 | Write the code that will take a string and make this conversion given a number of rows: 14 | 15 | string convert(string text, int nRows); 16 | convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". 17 | 18 | **********************************************************************************/ 19 | 20 | // How to do it: 21 | // find the step, and process the zigzag from three parts 22 | // *********** I am back *********** 23 | 24 | 25 | class Solution { 26 | public: 27 | string convert(string s, int numRows) { 28 | if (numRows <= 1){ 29 | return s; 30 | } 31 | string result = ""; 32 | int step = numRows * 2 - 2; 33 | int len = s.length(); 34 | // first row 35 | for (int i = 0; i < len; i += step){ 36 | result += s[i]; 37 | } 38 | // middle zigzag part 39 | for (int i = 1; i < numRows - 1; i++){ 40 | for (int j = i; j < len; j += step){ 41 | result += s[j]; 42 | if (j + (step - i * 2) < len){ 43 | result += s[j + (step - i * 2)]; 44 | } 45 | } 46 | } 47 | // last row 48 | for (int i = numRows - 1; i < len; i += step){ 49 | result += s[i]; 50 | } 51 | 52 | return result; 53 | } 54 | }; 55 | --------------------------------------------------------------------------------