├── .gitignore
├── algorithms
├── java
│ ├── junit-4.7.jar
│ ├── src
│ │ ├── maximumDepthOfBinaryTree
│ │ │ ├── TreeNode.java
│ │ │ ├── maximumDepthOfBinaryTreeTest.java
│ │ │ └── maximumDepthOfBinaryTree.java
│ │ ├── lowestCommonAncestorOfABinaryTree
│ │ │ ├── TreeNode.java
│ │ │ └── lowestCommonAncestorOfABinaryTreeTest.java
│ │ ├── binaryTreeBFSTraversal
│ │ │ ├── TreeNode.java
│ │ │ ├── binaryTreeBFSTraversal.java
│ │ │ └── binaryTreeBFSTraversalTest.java
│ │ ├── inorderSuccessorInBST
│ │ │ ├── TreeNode.java
│ │ │ ├── inorderSuccessorInBSTTest.java
│ │ │ └── inorderSuccessorInBST.java
│ │ ├── binaryTreeMaximumPathSum
│ │ │ └── TreeNode.java
│ │ ├── binaryTreePreorderTraversal
│ │ │ ├── TreeNode.java
│ │ │ ├── binaryTreePreorderTraversal.java
│ │ │ └── binaryTreePreorderTraversalTest.java
│ │ ├── binaryTreeLevelOrderTraversal
│ │ │ └── TreeNode.java
│ │ ├── searchRangeInBinarySearchTree
│ │ │ ├── TreeNode.java
│ │ │ ├── searchRangeInBinarySearchTreeTest.java
│ │ │ └── searchRangeInBinarySearchTree.java
│ │ ├── validateBinarySearchTree
│ │ │ ├── TreeNode.java
│ │ │ └── validateBinarySearchTreeTest.java
│ │ ├── balancedBinaryTree
│ │ │ ├── TreeNode.java
│ │ │ ├── balancedBinaryTreeTest.java
│ │ │ └── balancedBinaryTree.java
│ │ ├── binarySearchTreeIterator
│ │ │ ├── TreeNode.java
│ │ │ └── binarySearchTreeIteratorTest.java
│ │ ├── firstBadVersion
│ │ │ ├── VersionControl.java
│ │ │ ├── firstBadVersionTest.java
│ │ │ └── firstBadVersion.java
│ │ ├── dynamicProgramming
│ │ │ ├── climbStairs
│ │ │ │ ├── climbStairsTest.java
│ │ │ │ └── climbStairs.java
│ │ │ ├── uniquePaths
│ │ │ │ ├── uniquePathsTest.java
│ │ │ │ └── uniquePathsIITest.java
│ │ │ ├── minimumPathSum
│ │ │ │ ├── minimumPathSumTest.java
│ │ │ │ └── minimumPathSum.java
│ │ │ └── triangle
│ │ │ │ └── triangleTest.java
│ │ ├── strStr
│ │ │ ├── strStrTest.java
│ │ │ └── strStr.java
│ │ ├── searchForRange
│ │ │ ├── searchForRangeTest.java
│ │ │ └── searchForRange.java
│ │ ├── findPeakElement
│ │ │ ├── findPeakElementTest.java
│ │ │ └── findPeakElement.java
│ │ ├── searchInsertPosition
│ │ │ └── searchInsertPositionTest.java
│ │ ├── search2DMatrix
│ │ │ └── search2DMatrixTest.java
│ │ ├── findMinimumInRotatedSortedArray
│ │ │ ├── findMinimumInRotatedSortedArrayTest.java
│ │ │ └── findMinimumInRotatedSortedArray.java
│ │ ├── searchInRotatedSortedArray
│ │ │ └── searchInRotatedSortedArrayTest.java
│ │ ├── searchInABigSortedArray
│ │ │ └── searchInABigSortedArrayTest.java
│ │ └── lruCache
│ │ │ ├── LRUCacheTest.java
│ │ │ └── LRUCache.java
│ └── algorithms-java.iml
└── cpp
│ ├── reverseString
│ └── ReverseString.cpp
│ ├── containsDuplicate
│ ├── ContainsDuplicate.cpp
│ ├── ContainsDuplicate.II.cpp
│ └── ContainsDuplicate.III.cpp
│ ├── numberOf1Bits
│ └── numberOf1Bits.cpp
│ ├── climbStairs
│ └── climbStairs.cpp
│ ├── singleNumber
│ └── singleNumber.cpp
│ ├── h-Index
│ └── h-Index.II.cpp
│ ├── reverseBits
│ └── reverseBits.cpp
│ ├── removeDuplicatesFromSortedArray
│ └── removeDuplicatesFromSortedArray.cpp
│ ├── linkedListCycle
│ ├── linkedListCycle.cpp
│ └── linkedListCycle.II.cpp
│ ├── deleteNodeInALinkedList
│ └── DeleteNodeInALinkedList.cpp
│ ├── removeElement
│ └── removeElement.cpp
│ ├── powerOfFour
│ └── PowerOfFour.cpp
│ ├── integerToRoman
│ └── integerToRoman.cpp
│ ├── maximumDepthOfBinaryTree
│ └── maximumDepthOfBinaryTree.cpp
│ ├── uglyNumber
│ └── UglyNumber.cpp
│ ├── longestCommonPrefix
│ └── longestCommonPrefix.cpp
│ ├── pascalTriangle
│ ├── pascalTriangle.II.cpp
│ └── pascalTriangle.cpp
│ ├── jumpGame
│ └── jumpGame.cpp
│ ├── minimumDepthOfBinaryTree
│ └── minimumDepthOfBinaryTree.cpp
│ ├── removeLinkedListElements
│ └── RemoveLinkedListElements.cpp
│ ├── powerOfTwo
│ └── PowerOfTwo.cpp
│ ├── plusOne
│ └── plusOne.cpp
│ ├── intersectionOfTwoArrays
│ └── intersectionOfTwoArrays.cpp
│ ├── validPalindrome
│ └── validPalindrome.cpp
│ ├── twoSum
│ ├── twoSum.III.cpp
│ └── twoSum.II.cpp
│ ├── addBinary
│ └── addBinary.cpp
│ ├── productOfArrayExceptSelf
│ └── ProductOfArrayExceptSelf.cpp
│ ├── sqrt
│ └── sqrt.cpp
│ ├── reverseLinkedList
│ └── reverseLinkedList.cpp
│ ├── rotateList
│ └── rotateList.cpp
│ ├── validParentheses
│ └── validParentheses.cpp
│ ├── largestNumber
│ └── largestNumber.cpp
│ ├── lengthOfLastWord
│ └── lengthOfLastWord.cpp
│ ├── searchInsertPosition
│ └── searchInsertPosition.cpp
│ ├── gasStation
│ └── gasStation.cpp
│ ├── reverseVowelsOfAString
│ └── reverseVowelsOfAString.cpp
│ ├── removeNthNodeFromEndOfList
│ └── removeNthNodeFromEndOfList.cpp
│ ├── increasingTripletSubsequence
│ └── increasingTripletSubsequence.cpp
│ ├── palindromeLinkedList
│ └── PalindromeLinkedList.cpp
│ ├── integerBreak
│ └── IntegerBreak.cpp
│ ├── minimumPathSum
│ └── minimumPathSum.cpp
│ ├── convertSortedArrayToBinarySearchTree
│ └── convertSortedArrayToBinarySearchTree.cpp
│ ├── generateParentheses
│ └── generateParentheses.cpp
│ ├── rangeSumQuery-Immutable
│ └── rangeSumQuery-Immutable.cpp
│ ├── zigZagConversion
│ └── zigZagConversion.cpp
│ ├── firstBadVersion
│ └── FirstBadVersion.cpp
│ ├── isomorphicStrings
│ └── IsomorphicStrings.cpp
│ ├── pow
│ └── pow.cpp
│ ├── reverseWordsInAString
│ └── reverseWordsInAString.II.cpp
│ ├── binarySearchTreeIterator
│ └── binarySearchTreeIterator.cpp
│ ├── anagrams
│ └── ValidAnagram.cpp
│ ├── countCompleteTreeNodes
│ └── CountCompleteTreeNodes.cpp
│ ├── oddEvenLinkedList
│ └── OddEvenLinkedList.cpp
│ ├── uniquePaths
│ └── uniquePaths.II.cpp
│ ├── addTwoNumbers
│ └── addTwoNumbers.cpp
│ ├── removeDuplicatesFromSortedList
│ └── removeDuplicatesFromSortedList.cpp
│ ├── uniqueBinarySearchTrees
│ └── uniqueBinarySearchTrees.cpp
│ ├── bestTimeToBuyAndSellStock
│ ├── bestTimeToBuyAndSellStock.II.cpp
│ └── bestTimeToBuyAndSellStock.cpp
│ ├── excelSheetColumnTitle
│ └── excelSheetColumnTitle.cpp
│ ├── minimumSizeSubarraySum
│ └── MinimumSizeSubarraySum.cpp
│ ├── longestValidParentheses
│ └── longestValidParentheses.cpp
│ ├── excelSheetColumnNumber
│ └── excelSheetColumnNumber.cpp
│ ├── findTheDuplicateNumber
│ └── findTheDuplicateNumber.cpp
│ ├── romanToInteger
│ └── romanToInteger.cpp
│ ├── summaryRanges
│ └── SummaryRanges.cpp
│ ├── sumRootToLeafNumber
│ └── sumRootToLeafNumber.cpp
│ ├── happyNumber
│ └── HappyNumber.cpp
│ ├── regularExpressionMatching
│ └── regularExpressionMatching.cpp
│ ├── bitwiseANDOfNumbersRange
│ └── BitwiseAndOfNumbersRange.cpp
│ ├── maximumSubArray
│ └── maximumSubArray.cpp
│ ├── wordBreak
│ └── wordBreak.cpp
│ ├── rotateImage
│ └── rotateImage.cpp
│ ├── missingNumber
│ └── MissingNumber.cpp
│ ├── validSudoku
│ └── validSudoku.cpp
│ ├── pathSum
│ └── pathSum.II.cpp
│ ├── flattenBinaryTreeToLinkedList
│ └── flattenBinaryTreeToLinkedList.cpp
│ ├── longestSubstringWithAtMostTwoDistinctCharacters
│ └── longestSubstringWithAtMostTwoDistinctCharacters.cpp
│ ├── lowestCommonAncestorOfABinarySearchTree
│ └── LowestCommonAncestorOfABinarySearchTree.cpp
│ ├── implementQueueUsingStacks
│ └── ImplementQueueUsingStacks.cpp
│ ├── sameTree
│ └── sameTree.cpp
│ ├── binaryTreeInorderTraversal
│ └── binaryTreeInorderTraversal.cpp
│ ├── majorityElement
│ └── majorityElement.cpp
│ ├── containerWithMostWater
│ └── containerWithMostWater.cpp
│ ├── sortColors
│ └── sortColors.cpp
│ ├── binaryTreeMaximumPathSum
│ └── binaryTreeMaximumPathSum.cpp
│ └── powerOfThree
│ └── PowerOfThree.cpp
└── shell
├── README.md
├── TenthLine.sh
├── TransposeFile.sh
├── ValidPhoneNumbers.sh
└── WordFrequency.sh
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
2 | algorithms-java/out
3 | *.class
4 |
--------------------------------------------------------------------------------
/algorithms/java/junit-4.7.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hy0kl/leetcode/master/algorithms/java/junit-4.7.jar
--------------------------------------------------------------------------------
/algorithms/java/src/maximumDepthOfBinaryTree/TreeNode.java:
--------------------------------------------------------------------------------
1 | package maximumDepthOfBinaryTree;
2 |
3 | public class TreeNode {
4 | int val;
5 | TreeNode left;
6 | TreeNode right;
7 | TreeNode(int x) { val = x; }
8 | }
9 |
--------------------------------------------------------------------------------
/algorithms/java/src/lowestCommonAncestorOfABinaryTree/TreeNode.java:
--------------------------------------------------------------------------------
1 | package lowestCommonAncestorOfABinaryTree;
2 |
3 | public class TreeNode {
4 | int val;
5 | TreeNode left;
6 | TreeNode right;
7 | TreeNode(int x) { val = x; }
8 | }
9 |
--------------------------------------------------------------------------------
/algorithms/java/src/binaryTreeBFSTraversal/TreeNode.java:
--------------------------------------------------------------------------------
1 | package binaryTreeBFSTraversal;
2 |
3 | /**
4 | * Created by leicao on 5/10/15.
5 | */
6 | public class TreeNode {
7 | int val;
8 | TreeNode left;
9 | TreeNode right;
10 | TreeNode(int x) { val = x; }
11 | }
12 |
--------------------------------------------------------------------------------
/algorithms/java/src/inorderSuccessorInBST/TreeNode.java:
--------------------------------------------------------------------------------
1 | package inorderSuccessorInBST;
2 |
3 | /**
4 | * Created by leicao on 5/10/15.
5 | */
6 | public class TreeNode {
7 | int val;
8 | TreeNode left;
9 | TreeNode right;
10 | TreeNode(int x) { val = x; }
11 | }
12 |
--------------------------------------------------------------------------------
/algorithms/java/src/binaryTreeMaximumPathSum/TreeNode.java:
--------------------------------------------------------------------------------
1 | package binaryTreeMaximumPathSum;
2 |
3 | /**
4 | * Created by leicao on 5/10/15.
5 | */
6 | public class TreeNode {
7 | int val;
8 | TreeNode left;
9 | TreeNode right;
10 | TreeNode(int x) { val = x; }
11 | }
12 |
--------------------------------------------------------------------------------
/algorithms/java/src/binaryTreePreorderTraversal/TreeNode.java:
--------------------------------------------------------------------------------
1 | package binaryTreePreorderTraversal;
2 |
3 | /**
4 | * Created by leicao on 5/10/15.
5 | */
6 | public class TreeNode {
7 | int val;
8 | TreeNode left;
9 | TreeNode right;
10 | TreeNode(int x) { val = x; }
11 | }
12 |
--------------------------------------------------------------------------------
/algorithms/java/src/binaryTreeLevelOrderTraversal/TreeNode.java:
--------------------------------------------------------------------------------
1 | package binaryTreeLevelOrderTraversal;
2 |
3 | /**
4 | * Created by leicao on 5/10/15.
5 | */
6 | public class TreeNode {
7 | int val;
8 | TreeNode left;
9 | TreeNode right;
10 | TreeNode(int x) { val = x; }
11 | }
12 |
--------------------------------------------------------------------------------
/algorithms/java/src/searchRangeInBinarySearchTree/TreeNode.java:
--------------------------------------------------------------------------------
1 | package searchRangeInBinarySearchTree;
2 |
3 | /**
4 | * Created by leicao on 5/10/15.
5 | */
6 | public class TreeNode {
7 | int val;
8 | TreeNode left;
9 | TreeNode right;
10 | TreeNode(int x) { val = x; }
11 | }
12 |
--------------------------------------------------------------------------------
/algorithms/java/src/validateBinarySearchTree/TreeNode.java:
--------------------------------------------------------------------------------
1 | package validateBinarySearchTree;
2 |
3 | public class TreeNode {
4 | public int val;
5 | public TreeNode left, right;
6 | public TreeNode(int val) {
7 | this.val = val;
8 | this.left = this.right = null;
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/algorithms/java/src/balancedBinaryTree/TreeNode.java:
--------------------------------------------------------------------------------
1 | package balancedBinaryTree;
2 |
3 | /**
4 | * Created by leicao on 5/10/15.
5 | */
6 | public class TreeNode {
7 | public int val;
8 | public TreeNode left, right;
9 | public TreeNode(int val) {
10 | this.val = val;
11 | this.left = this.right = null;
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/algorithms/java/src/binarySearchTreeIterator/TreeNode.java:
--------------------------------------------------------------------------------
1 | package binarySearchTreeIterator;
2 |
3 | /**
4 | * Created by leicao on 5/10/15.
5 | */
6 | public class TreeNode {
7 | public int val;
8 | public TreeNode left, right;
9 | public TreeNode(int val) {
10 | this.val = val;
11 | this.left = this.right = null;
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/algorithms/java/src/firstBadVersion/VersionControl.java:
--------------------------------------------------------------------------------
1 | package firstBadVersion;
2 |
3 | /**
4 | * Created by leicao on 5/10/15.
5 | */
6 | public class VersionControl {
7 | int firstBadVersion;
8 | boolean isBadVersion(int version) {
9 | if (version >= firstBadVersion) {
10 | return true;
11 | }
12 | return false;
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/shell/README.md:
--------------------------------------------------------------------------------
1 | ###LeetCode Shell
2 |
3 |
4 | | # | Title | Solution | Difficulty |
5 | |---| ----- | -------- | ---------- |
6 | |4|[Tenth Line](https://leetcode.com/problems/tenth-line/)| [Bash](./TenthLine.sh)|Easy|
7 | |3|[Transpose File](https://leetcode.com/problems/transpose-file/)| [Bash](./TransposeFile.sh)|Medium|
8 | |2|[Valid Phone Numbers](https://leetcode.com/problems/valid-phone-numbers/)| [Bash](./ValidPhoneNumbers.sh)|Easy|
9 | |1|[Word Frequency](https://leetcode.com/problems/word-frequency/)| [Bash](./WordFrequency.sh)|Medium|
10 |
--------------------------------------------------------------------------------
/algorithms/java/src/dynamicProgramming/climbStairs/climbStairsTest.java:
--------------------------------------------------------------------------------
1 | package dynamicProgramming.climbStairs;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Created by leicao on 12/10/15.
9 | */
10 | public class climbStairsTest {
11 |
12 | @Test
13 | public void testClimbStairs() throws Exception {
14 | int[] inputs = {1,2,3,4};
15 |
16 | int[] results = {1,2,3,5};
17 |
18 | for (int i = 0; i < results.length; i++) {
19 | climbStairs c = new climbStairs();
20 | int r = c.climbStairs(inputs[i]);
21 | System.out.println(r);
22 | assertEquals(results[i], r);
23 | }
24 | }
25 | }
--------------------------------------------------------------------------------
/algorithms/java/src/strStr/strStrTest.java:
--------------------------------------------------------------------------------
1 | package strStr;
2 |
3 | import com.sun.org.apache.xpath.internal.operations.Equals;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Created by leicao on 2/10/15.
9 | */
10 | public class strStrTest {
11 |
12 | @org.junit.Test
13 | public void testStrStr() throws Exception {
14 | strStr strStr = new strStr();
15 | String[][] inputs = {
16 | {"I am the haystack!","haystack!"},
17 | {"I am the haystack!","haytack"},
18 | };
19 | int[] outputs = {9, -1};
20 | for (int i = 0; i < inputs.length; i++) {
21 | assertEquals(outputs[i], strStr.strStr(inputs[i][0], inputs[i][1]));
22 | }
23 | }
24 | }
--------------------------------------------------------------------------------
/algorithms/java/algorithms-java.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/algorithms/java/src/dynamicProgramming/uniquePaths/uniquePathsTest.java:
--------------------------------------------------------------------------------
1 | package dynamicProgramming.uniquePaths;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Created by leicao on 11/10/15.
9 | */
10 | public class uniquePathsTest {
11 |
12 | @Test
13 | public void testUniquePaths() throws Exception {
14 | int[][] inputs = {
15 | {2,2},
16 | {3,7},
17 | };
18 | int[] results = {2,28};
19 | for (int i = 0; i < inputs.length; i++) {
20 | uniquePaths u = new uniquePaths();
21 | int r = u.uniquePaths(inputs[i][0], inputs[i][1]);
22 | System.out.println(r);
23 | assertEquals(results[i], r);
24 | }
25 |
26 | }
27 | }
--------------------------------------------------------------------------------
/algorithms/java/src/firstBadVersion/firstBadVersionTest.java:
--------------------------------------------------------------------------------
1 | package firstBadVersion;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Created by leicao on 5/10/15.
9 | */
10 | public class firstBadVersionTest {
11 |
12 | @Test
13 | public void testFirstBadVersion() throws Exception {
14 | int[] inputs = {1,22,34,40,5232,6342342,71231};
15 | int[] targets = {1, 10, 20, 25, 323, 45454, 23232};
16 |
17 | firstBadVersion f = new firstBadVersion();
18 | for (int i = 0; i < targets.length; i++) {
19 | f.firstBadVersion = targets[i];
20 | int r = f.firstBadVersion(inputs[i]);
21 | System.out.println(r);
22 | assertEquals(targets[i], r);
23 | }
24 | }
25 | }
--------------------------------------------------------------------------------
/algorithms/cpp/reverseString/ReverseString.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://leetcode.com/problems/reverse-string/
2 | // Author : Hao Chen
3 | // Date : 2016-05-29
4 |
5 | /***************************************************************************************
6 | *
7 | * Write a function that takes a string as input and returns the string reversed.
8 | *
9 | * Example:
10 | * Given s = "hello", return "olleh".
11 | ***************************************************************************************/
12 |
13 | class Solution {
14 | public:
15 | string reverseString(string s) {
16 | int len = s.size();
17 | for (int i=0; i& nums) {
17 | unordered_map m;
18 | for (auto item : nums) {
19 | if (m.find(item) != m.end()) return true;
20 | m[item]=true;
21 | }
22 | return false;
23 | }
24 | };
25 |
--------------------------------------------------------------------------------
/algorithms/java/src/findMinimumInRotatedSortedArray/findMinimumInRotatedSortedArrayTest.java:
--------------------------------------------------------------------------------
1 | package findMinimumInRotatedSortedArray;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Created by leicao on 5/10/15.
9 | */
10 | public class findMinimumInRotatedSortedArrayTest {
11 |
12 | @Test
13 | public void testFindMin() throws Exception {
14 | int[][] inputs = {
15 | {4,5,6,7,0,1,2},
16 | {1,2,3},
17 | {2,3,1},
18 | {1,2,3,4},
19 | {2,3,4,1}
20 | };
21 |
22 | int [] results = {0,1,1,1,1};
23 |
24 | findMinimumInRotatedSortedArray f = new findMinimumInRotatedSortedArray();
25 | for (int i = 0; i < results.length; i++) {
26 | int r = f.findMin(inputs[i]);
27 | System.out.println(results[i]);
28 | assertEquals(results[i], r);
29 | }
30 | }
31 | }
--------------------------------------------------------------------------------
/algorithms/cpp/numberOf1Bits/numberOf1Bits.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://leetcode.com/problems/number-of-1-bits/
2 | // Author : Hao Chen
3 | // Date : 2015-03-30
4 |
5 | /**********************************************************************************
6 | *
7 | * Write a function that takes an unsigned integer and returns the number of ’1' bits it has
8 | * (also known as the Hamming weight).
9 | *
10 | * For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011,
11 | * so the function should return 3.
12 | *
13 | * Credits:Special thanks to @ts for adding this problem and creating all test cases.
14 | *
15 | **********************************************************************************/
16 |
17 | class Solution {
18 | public:
19 | int hammingWeight(uint32_t n) {
20 | int cnt = 0;
21 | for(;n>0; n/=2){
22 | if (n & 0x1) cnt++;
23 | }
24 | return cnt;
25 | }
26 | };
27 |
--------------------------------------------------------------------------------
/algorithms/java/src/binaryTreeBFSTraversal/binaryTreeBFSTraversal.java:
--------------------------------------------------------------------------------
1 | package binaryTreeBFSTraversal;
2 |
3 | import java.util.ArrayList;
4 | import java.util.LinkedList;
5 | import java.util.List;
6 | import java.util.Queue;
7 |
8 | /**
9 | * Created by leicao on 5/10/15.
10 | */
11 | public class binaryTreeBFSTraversal {
12 | public List bfsTraversal(TreeNode root) {
13 | List results = new ArrayList();
14 | if (root == null) {
15 | return results;
16 | }
17 |
18 | Queue q = new LinkedList();
19 |
20 | q.offer(root);
21 | while (q.size() != 0) {
22 | TreeNode n = q.remove();
23 | results.add(n.val);
24 | if (n.left != null) {
25 | q.offer(n.left);
26 | }
27 | if (n.right != null) {
28 | q.offer(n.right);
29 | }
30 | }
31 |
32 | return results;
33 |
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/algorithms/java/src/searchInRotatedSortedArray/searchInRotatedSortedArrayTest.java:
--------------------------------------------------------------------------------
1 | package searchInRotatedSortedArray;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Created by leicao on 3/10/15.
9 | */
10 | public class searchInRotatedSortedArrayTest {
11 |
12 | @Test
13 | public void testSearch() throws Exception {
14 |
15 | int[][] inputes = {
16 | {1},
17 | {1},
18 | {6,8,9,1,3,5},
19 | {1,2},
20 | {2,1},
21 | {4,5,6,7,0,1,2},
22 | {0,1,2,4,5,6,7},
23 | };
24 | int[] targets = {0,1,5,2,2,6,6};
25 | int[] results = {-1,0,5,1,0,2,5};
26 |
27 | searchInRotatedSortedArray s = new searchInRotatedSortedArray();
28 | for (int i = 0; i < inputes.length; i++) {
29 | int r = s.search(inputes[i], targets[i]);
30 | System.out.println(r);
31 | assertEquals(results[i], r);
32 | }
33 | }
34 | }
--------------------------------------------------------------------------------
/algorithms/cpp/climbStairs/climbStairs.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/climbing-stairs/
2 | // Author : Hao Chen
3 | // Date : 2014-06-27
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 |
14 | class Solution {
15 | public:
16 |
17 | int climbStairs(int n) {
18 | if (n<=3) return n;
19 | int a[2]={2,3};
20 | for(int i=4; i<=n; i++){
21 | int t = a[0] + a[1];
22 | a[0] = a[1];
23 | a[1] = t;
24 | }
25 | return a[1];
26 | }
27 | //Time too long
28 | int climbStairs2(int n) {
29 | if (n<=3) return n;
30 | return climbStairs(n-1) + climbStairs(n-2);
31 | }
32 | };
33 |
--------------------------------------------------------------------------------
/algorithms/cpp/containsDuplicate/ContainsDuplicate.II.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://leetcode.com/problems/contains-duplicate-ii/
2 | // Author : Hao Chen
3 | // Date : 2015-06-12
4 |
5 | /**********************************************************************************
6 | *
7 | * Given an array of integers and an integer k, find out whether there there are
8 | * two distinct indices i and j in the array such that nums[i] = nums[j] and
9 | * the difference between i and j is at most k.
10 | *
11 | *
12 | **********************************************************************************/
13 |
14 | class Solution {
15 | public:
16 | bool containsNearbyDuplicate(vector& nums, int k) {
17 | unordered_map m;
18 | for (int i=0; i
16 | // This is classical interview question
17 | // As we know, the same number XOR together will be 0,
18 | // So, XOR all of numbers, the result is the number which only appears once.
19 | int singleNumber(int A[], int n) {
20 | int s = 0;
21 | for(int i=0; i& citations) {
18 | int n = citations.size();
19 | int low = 0, high = n-1;
20 |
21 | while( low <= high ) {
22 | int mid = low + (high-low)/2;
23 | if (citations[mid] == n - mid) {
24 | return n - mid;
25 | }else if (citations[mid] > n-mid){
26 | high = mid - 1;
27 | }else {
28 | low = mid + 1;
29 | }
30 | }
31 | return n-low;
32 | }
33 | };
34 |
--------------------------------------------------------------------------------
/shell/TransposeFile.sh:
--------------------------------------------------------------------------------
1 | # Source : https://leetcode.com/problems/transpose-file/
2 | # Author : Hao Chen
3 | # Date : 2015-03-31
4 |
5 | ##################################################################################
6 | #
7 | # Given a text file file.txt, transpose its content.
8 | #
9 | # You may assume that each row has the same number of columns and each field is separated by the ' ' character.
10 | #
11 | # For example, if file.txt has the following content:
12 | #
13 | # name age
14 | # alice 21
15 | # ryan 30
16 | #
17 | # Output the following:
18 | #
19 | # name alice ryan
20 | # age 21 30
21 | ##################################################################################
22 |
23 | #!/bin/sh
24 |
25 | # Read from the file file.txt and print its transposed content to stdout.
26 | awk '
27 | {
28 | for (i = 1; i <= NF; i++) {
29 | if (NR == 1){
30 | s[i]=$i;
31 | }else{
32 | s[i] = s[i] " " $i;
33 | }
34 | }
35 | }
36 | END {
37 | for (i = 1; s[i] != ""; i++) {
38 | print s[i];
39 | }
40 | }' file.txt
41 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/algorithms/cpp/reverseBits/reverseBits.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://leetcode.com/problems/reverse-bits/
2 | // Author : Hao Chen
3 | // Date : 2015-03-30
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),
10 | * return 964176192 (represented in binary as 00111001011110000010100101000000).
11 | *
12 | * Follow up:
13 | * If this function is called many times, how would you optimize it?
14 | *
15 | * Related problem: Reverse Integer
16 | *
17 | * Credits:Special thanks to @ts for adding this problem and creating all test cases.
18 | *
19 | **********************************************************************************/
20 |
21 |
22 |
23 | class Solution {
24 | public:
25 | uint32_t reverseBits(uint32_t n) {
26 | uint32_t ret=0;
27 | for(int i=0; i<32; i++) {
28 | ret = (ret*2) + (n & 0x1);
29 | n /=2 ;
30 | }
31 | return ret;
32 | }
33 | };
34 |
--------------------------------------------------------------------------------
/algorithms/cpp/removeDuplicatesFromSortedArray/removeDuplicatesFromSortedArray.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/
2 | // Author : Hao Chen
3 | // Date : 2014-06-22
4 |
5 | /**********************************************************************************
6 | *
7 | * Given a sorted array, remove the duplicates in place such that each element appear
8 | * only once and return the new length.
9 | *
10 | * Do not allocate extra space for another array, you must do this in place with constant memory.
11 | *
12 | * For example,
13 | * Given input array A = [1,1,2],
14 | *
15 | * Your function should return length = 2, and A is now [1,2].
16 | *
17 | *
18 | **********************************************************************************/
19 |
20 | class Solution {
21 | public:
22 | int removeDuplicates(int A[], int n) {
23 |
24 | if (n<=1) return n;
25 |
26 | int pos=0;
27 | for(int i=0; inext==NULL) return false;
25 | ListNode* fast=head;
26 | ListNode* slow=head;
27 | do{
28 | slow = slow->next;
29 | fast = fast->next->next;
30 | }while(fast != NULL && fast->next != NULL && fast != slow);
31 | return fast == slow? true : false;
32 | }
33 |
--------------------------------------------------------------------------------
/algorithms/cpp/deleteNodeInALinkedList/DeleteNodeInALinkedList.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://leetcode.com/problems/delete-node-in-a-linked-list/
2 | // Author : Hao Chen
3 | // Date : 2015-07-17
4 |
5 | /**********************************************************************************
6 | *
7 | * Write a function to delete a node (except the tail) in a singly linked list, given
8 | * only access to that node.
9 | *
10 | * Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with
11 | * value 3, the linked list should become 1 -> 2 -> 4 after calling your function.
12 | *
13 | **********************************************************************************/
14 |
15 | /**
16 | * Definition for singly-linked list.
17 | * struct ListNode {
18 | * int val;
19 | * ListNode *next;
20 | * ListNode(int x) : val(x), next(NULL) {}
21 | * };
22 | */
23 | class Solution {
24 | public:
25 | //becasue the deleted is not the tail.
26 | //So, we can move the content of next node to this one, and delete the next one
27 | void deleteNode(ListNode* node) {
28 | node->val = node->next->val;
29 | node->next = node->next->next;
30 | }
31 | };
32 |
33 |
34 |
--------------------------------------------------------------------------------
/algorithms/java/src/searchInABigSortedArray/searchInABigSortedArrayTest.java:
--------------------------------------------------------------------------------
1 | package searchInABigSortedArray;
2 |
3 | import org.junit.Test;
4 | import searchInsertPosition.searchInsertPosition;
5 |
6 | import static org.junit.Assert.*;
7 |
8 | /**
9 | * Created by leicao on 5/10/15.
10 | */
11 | public class searchInABigSortedArrayTest {
12 |
13 | @Test
14 | public void testSearchBigSortedArray() throws Exception {
15 | int [][] inputs = {
16 | {1,2,3,4},
17 | {1,1,1,1,2,2,3,3,3,4,4,4,5,5,5,5,5,5,5,6,6,6,6,6,6,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10,
18 | 10,10,10,10,10,11,11,11,11,12,12,12,13,13,13,13,13,14,14,14,14,14,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,16,17,17,
19 | 17,17,17,17,17,18,18,19,19,19,19,20,20,20,20,20,20,20,20,20},
20 | };
21 | int[] targets = {3, 4};
22 | int[] results = {2, 9};
23 | searchInABigSortedArray s = new searchInABigSortedArray();
24 | for (int i = 0; i < inputs.length; i++) {
25 | int r = s.searchBigSortedArray(inputs[i], targets[i]);
26 | System.out.println(r);
27 | assertEquals(results[i], r);
28 | }
29 |
30 |
31 | }
32 | }
--------------------------------------------------------------------------------
/algorithms/java/src/dynamicProgramming/climbStairs/climbStairs.java:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/climbing-stairs/
2 | // Inspired by : http://www.jiuzhang.com/solutions/climbing-stairs/
3 | // Author : Lei Cao
4 | // Date : 2015-10-12
5 |
6 | /**********************************************************************************
7 | *
8 | * You are climbing a stair case. It takes n steps to reach to the top.
9 | *
10 | * Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
11 | *
12 | *
13 | **********************************************************************************/
14 |
15 | package dynamicProgramming.climbStairs;
16 |
17 | public class climbStairs {
18 | /**
19 | * @param n: An integer
20 | * @return: An integer
21 | */
22 | public int climbStairs(int n) {
23 | int[] matrix = new int[n];
24 | if (n < 3) {
25 | return n;
26 | }
27 | matrix[0] = 1;
28 | matrix[1] = 2;
29 | // write your code here
30 | for (int i = 2; i < matrix.length; i++) {
31 | matrix[i] = matrix[i-1] + matrix[i-2];
32 | }
33 | return matrix[n-1];
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/algorithms/cpp/removeElement/removeElement.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/remove-element/
2 | // Author : Hao Chen
3 | // Date : 2014-06-19
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 |
14 | class Solution {
15 | public:
16 | int removeElement(vector& nums, int val) {
17 | int pos = 0;
18 | for (int i=0; i
14 | #include
15 | #include
16 | using namespace std;
17 |
18 | //greeding algorithm
19 | string intToRoman(int num) {
20 | string symbol[] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
21 | int value[] = {1000,900,500,400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
22 | string result;
23 |
24 | for(int i=0; num!=0; i++){
25 | while(num >= value[i]){
26 | num -= value[i];
27 | result+=symbol[i];
28 | }
29 | }
30 |
31 | return result;
32 | }
33 |
34 |
35 | int main(int argc, char** argv)
36 | {
37 | int num = 1234;
38 | if (argc>0){
39 | num = atoi(argv[1]);
40 | }
41 |
42 | cout << num << " : " << intToRoman(num) << endl;
43 | return 0;
44 | }
45 |
--------------------------------------------------------------------------------
/algorithms/java/src/balancedBinaryTree/balancedBinaryTreeTest.java:
--------------------------------------------------------------------------------
1 | package balancedBinaryTree;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.ArrayList;
6 |
7 | import static org.junit.Assert.*;
8 | /**
9 | * Created by leicao on 7/10/15.
10 | */
11 | public class balancedBinaryTreeTest {
12 |
13 | @Test
14 | public void testIsBalanced() throws Exception {
15 | ArrayList inputes = new ArrayList();
16 | boolean[] results = {false, false};
17 | TreeNode n0 = new TreeNode(0);
18 | TreeNode n1 = new TreeNode(1);
19 | TreeNode n2 = new TreeNode(2);
20 | TreeNode n3 = new TreeNode(3);
21 |
22 | n0.left = n1;
23 | n1.left = n2;
24 | n2.left = n3;
25 |
26 | TreeNode nn0 = new TreeNode(0);
27 | TreeNode nn1 = new TreeNode(1);
28 | TreeNode nn2 = new TreeNode(2);
29 | TreeNode nn3 = new TreeNode(3);
30 | nn0.right = nn1;
31 | nn1.left = nn2;
32 | nn2.left = nn3;
33 |
34 | inputes.add(n0);
35 | inputes.add(nn0);
36 |
37 | for (int i = 0; i < results.length; i++) {
38 | balancedBinaryTree b = new balancedBinaryTree();
39 | assertEquals(results[i], b.isBalanced(inputes.get(i)));
40 | }
41 |
42 | }
43 | }
--------------------------------------------------------------------------------
/algorithms/java/src/binarySearchTreeIterator/binarySearchTreeIteratorTest.java:
--------------------------------------------------------------------------------
1 | package binarySearchTreeIterator;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.ArrayList;
6 |
7 | import static org.junit.Assert.*;
8 |
9 | /**
10 | * Created by leicao on 11/10/15.
11 | */
12 | public class binarySearchTreeIteratorTest {
13 | @Test
14 | public void testIterator() throws Exception {
15 | ArrayList inputs = new ArrayList();
16 | TreeNode t0 = new TreeNode(10);
17 | TreeNode t1 = new TreeNode(1);
18 | TreeNode t2 = new TreeNode(11);
19 | TreeNode t3 = new TreeNode(6);
20 | TreeNode t4 = new TreeNode(12);
21 | t0.left = t1;
22 | t0.right = t2;
23 | t1.right = t3;
24 | t2.right = t4;
25 |
26 | inputs.add(t0);
27 |
28 | int[][] results = {
29 | {1,6,10,11,12}
30 | };
31 |
32 | for (int i = 0; i < results.length; i++) {
33 | binarySearchTreeIterator it = new binarySearchTreeIterator(inputs.get(i));
34 | int j = 0;
35 | while (it.hasNext()) {
36 | TreeNode r = it.next();
37 | assertEquals(results[i][j], r.val);
38 | j++;
39 | }
40 | }
41 |
42 | }
43 |
44 | }
--------------------------------------------------------------------------------
/algorithms/cpp/maximumDepthOfBinaryTree/maximumDepthOfBinaryTree.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/maximum-depth-of-binary-tree/
2 | // Author : Hao Chen
3 | // Date : 2014-06-21
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
10 | * down to the farthest leaf node.
11 | *
12 | **********************************************************************************/
13 |
14 | /**
15 | * Definition for binary tree
16 | * struct TreeNode {
17 | * int val;
18 | * TreeNode *left;
19 | * TreeNode *right;
20 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
21 | * };
22 | */
23 | class Solution {
24 | public:
25 | int maxDepth(TreeNode *root) {
26 | if (root==NULL){
27 | return 0;
28 | }
29 | if (!root->left && !root->right){
30 | return 1;
31 | }
32 | int left=1, right=1;
33 | if (root->left){
34 | left += maxDepth(root->left);
35 | }
36 | if (root->right){
37 | right += maxDepth(root->right);
38 | }
39 | return left>right?left:right;
40 | }
41 |
42 | };
43 |
--------------------------------------------------------------------------------
/algorithms/cpp/uglyNumber/UglyNumber.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://leetcode.com/problems/ugly-number/
2 | // Author : Hao Chen
3 | // Date : 2015-10-21
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
10 | * example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.
11 | *
12 | * Note that 1 is typically treated as an ugly number.
13 | *
14 | * Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating
15 | * all test cases.
16 | *
17 | ***************************************************************************************/
18 |
19 | class Solution {
20 | public:
21 | //greeting algorithm
22 | bool isUgly(int num) {
23 | if ( num == 0 ) return false;
24 | if ( num == 1 ) return true;
25 | //becasue the 2,3,5 are prime numbers, so, we just simply remove each factors
26 | //by keeping dividing them one by one
27 | while ( num % 2 == 0 ) num /= 2;
28 | while ( num % 3 == 0 ) num /= 3;
29 | while ( num % 5 == 0 ) num /= 5;
30 |
31 | return num == 1;
32 | }
33 | };
34 |
35 |
--------------------------------------------------------------------------------
/algorithms/cpp/longestCommonPrefix/longestCommonPrefix.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/longest-common-prefix/
2 | // Author : Hao Chen
3 | // Date : 2014-07-03
4 |
5 | /**********************************************************************************
6 | *
7 | * Write a function to find the longest common prefix string amongst an array of strings.
8 | *
9 | *
10 | **********************************************************************************/
11 |
12 | #include
13 | #include
14 | #include
15 | using namespace std;
16 |
17 |
18 | string longestCommonPrefix(vector &strs) {
19 | string word;
20 | if (strs.size()<=0) return word;
21 | for(int i=1; i<=strs[0].size(); i++){
22 | string w = strs[0].substr(0, i);
23 | bool match = true;
24 | int j=1;
25 | for(j=1; jstrs[j].size() || w!=strs[j].substr(0, i) ) {
27 | match=false;
28 | break;
29 | }
30 | }
31 | if (!match) {
32 | return word;
33 | }
34 | word = w;
35 | }
36 | return word;
37 | }
38 |
39 | int main()
40 | {
41 | const char* s[]={"abab","aba","abc"};
42 | vector v(s, s+3);
43 | cout << longestCommonPrefix(v) <
19 | #include
20 | #include
21 | using namespace std;
22 |
23 | vector getRow(int rowIndex) {
24 | vector v(rowIndex+1, 0);
25 | v[0]=1;
26 |
27 | for (int i=0; i0; j--){
29 | v[j] += v[j-1];
30 | }
31 | }
32 | return v;
33 |
34 | }
35 |
36 | void printVector( vector pt)
37 | {
38 | cout << "{ ";
39 | for(int j=0; j1) {
49 | n = atoi(argv[1]);
50 | }
51 | printVector(getRow(n));
52 | }
53 |
--------------------------------------------------------------------------------
/algorithms/cpp/jumpGame/jumpGame.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/jump-game/
2 | // Author : Hao Chen
3 | // Date : 2014-06-27
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 |
21 | class Solution {
22 | public:
23 | bool canJump(int A[], int n) {
24 | if (n<=0) return false;
25 |
26 | // the basic idea is traverse array, maintain the most far can go
27 | int coverPos=0;
28 | // the condition i<=coverPos means traverse all of covered position
29 | for(int i=0; i<=coverPos && i=n-1){
36 | return true;
37 | }
38 | }
39 | return false;
40 | }
41 | };
42 |
--------------------------------------------------------------------------------
/algorithms/java/src/maximumDepthOfBinaryTree/maximumDepthOfBinaryTreeTest.java:
--------------------------------------------------------------------------------
1 | package maximumDepthOfBinaryTree;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.ArrayList;
6 |
7 | import static org.junit.Assert.*;
8 |
9 | /**
10 | * Created by leicao on 5/10/15.
11 | */
12 | public class maximumDepthOfBinaryTreeTest {
13 |
14 | @Test
15 | public void testMaxDepth() throws Exception {
16 | TreeNode t0 = new TreeNode(0);
17 |
18 | TreeNode n0 = new TreeNode(0);
19 | TreeNode n1 = new TreeNode(1);
20 | TreeNode n2 = new TreeNode(2);
21 | TreeNode n3 = new TreeNode(3);
22 | TreeNode n4 = new TreeNode(5);
23 | TreeNode n5 = new TreeNode(6);
24 | TreeNode n6 = new TreeNode(6);
25 |
26 | n0.left = n1;
27 | n0.right = n2;
28 | n1.left = n3;
29 | n1.right = n4;
30 | n4.left = n5;
31 | n2.right = n6;
32 |
33 | ArrayList inputes = new ArrayList();
34 | inputes.add(t0);
35 | inputes.add(n0);
36 | int[] results = {1,3};
37 |
38 | maximumDepthOfBinaryTree m = new maximumDepthOfBinaryTree();
39 | for (int i = 0; i < results.length; i++) {
40 | int d = m.maxDepth(inputes.get(i));
41 | System.out.println(d);
42 | assertEquals(results[i], d);
43 | }
44 | }
45 | }
--------------------------------------------------------------------------------
/shell/WordFrequency.sh:
--------------------------------------------------------------------------------
1 | # Source : https://leetcode.com/problems/word-frequency/
2 | # Author : Hao Chen
3 | # Date : 2015-03-31
4 |
5 | ##################################################################################
6 | #
7 | # Write a bash script to calculate the frequency of each word in a text file words.txt.
8 | #
9 | # For simplicity sake, you may assume:
10 | #
11 | # words.txt contains only lowercase characters and space ' ' characters.
12 | # Each word must consist of lowercase characters only.
13 | # Words are separated by one or more whitespace characters.
14 | #
15 | # For example, assume that words.txt has the following content:
16 | # the day is sunny the the
17 | # the sunny is is
18 | #
19 | # Your script should output the following, sorted by descending frequency:
20 | #
21 | # the 4
22 | # is 3
23 | # sunny 2
24 | # day 1
25 | #
26 | # Note:
27 | # Don't worry about handling ties, it is guaranteed that each word's frequency count is unique.
28 | #
29 | # [show hint]
30 | # Hint:
31 | # Could you write it in one-line using Unix pipes?
32 | ##################################################################################
33 |
34 | #!/bin/sh
35 |
36 | # Read from the file words.txt and output the word frequency list to stdout.
37 | cat words.txt | tr [:space:] "\n" | sed '/^$/d' | tr '[:upper:]' '[:lower:]'|sort|uniq -c|sort -nr | awk '{ print $2,$1}'
38 |
39 |
--------------------------------------------------------------------------------
/algorithms/java/src/lowestCommonAncestorOfABinaryTree/lowestCommonAncestorOfABinaryTreeTest.java:
--------------------------------------------------------------------------------
1 | package lowestCommonAncestorOfABinaryTree;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.ArrayList;
6 |
7 | import static org.junit.Assert.*;
8 |
9 | /**
10 | * Created by leicao on 7/10/15.
11 | */
12 | public class lowestCommonAncestorOfABinaryTreeTest {
13 |
14 | @Test
15 | public void testLowestCommonAncestor() throws Exception {
16 | ArrayList inputeRoots = new ArrayList();
17 | ArrayList inputeAs = new ArrayList();
18 | ArrayList inputeBs = new ArrayList();
19 | ArrayList results = new ArrayList();
20 |
21 | TreeNode n0 = new TreeNode(0);
22 | TreeNode n1 = new TreeNode(1);
23 | TreeNode n2 = new TreeNode(2);
24 | n0.left = n1;
25 | n0.right = n2;
26 | inputeRoots.add(n0);
27 | inputeAs.add(n1);
28 | inputeBs.add(n2);
29 | results.add(n0);
30 |
31 | for (int i = 0; i < results.size(); i++) {
32 | lowestCommonAncestorOfABinaryTree l = new lowestCommonAncestorOfABinaryTree();
33 | TreeNode r = l.lowestCommonAncestor(inputeRoots.get(i), inputeAs.get(i), inputeBs.get(i));
34 | assertEquals(results.get(i).val, r.val);
35 | }
36 |
37 | }
38 | }
--------------------------------------------------------------------------------
/algorithms/cpp/minimumDepthOfBinaryTree/minimumDepthOfBinaryTree.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/minimum-depth-of-binary-tree/
2 | // Author : Hao Chen
3 | // Date : 2014-06-22
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
10 | * down to the nearest leaf node.
11 | *
12 | **********************************************************************************/
13 |
14 | /**
15 | * Definition for binary tree
16 | * struct TreeNode {
17 | * int val;
18 | * TreeNode *left;
19 | * TreeNode *right;
20 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
21 | * };
22 | */
23 | class Solution {
24 | public:
25 | int minDepth(TreeNode *root) {
26 | if (root==NULL){
27 | return 0;
28 | }
29 | if (root->left==NULL && root->right==NULL){
30 | return 1;
31 | }
32 | int left=INT_MAX;
33 | if (root->left){
34 | left = minDepth(root->left) + 1 ;
35 | }
36 | int right=INT_MAX;
37 | if (root->right){
38 | right = minDepth(root->right) + 1;
39 | }
40 |
41 | return left 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
11 | * Return: 1 --> 2 --> 3 --> 4 --> 5
12 | *
13 | * Credits:Special thanks to @mithmatt for adding this problem and creating all test cases.
14 | *
15 | **********************************************************************************/
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 | ListNode* removeElements(ListNode* head, int val) {
28 | static ListNode dummy(-1);
29 | dummy.next = head;
30 | ListNode *p = &dummy;
31 |
32 | while( p->next) {
33 | if (p->next->val == val) {
34 | p->next = p->next->next;
35 | }else{
36 | p = p->next;
37 | }
38 | }
39 |
40 | return dummy.next;
41 | }
42 | };
43 |
44 |
45 |
--------------------------------------------------------------------------------
/algorithms/cpp/powerOfTwo/PowerOfTwo.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://leetcode.com/problems/power-of-two/
2 | // Author : Hao Chen
3 | // Date : 2015-07-16
4 |
5 | /**********************************************************************************
6 | *
7 | * Given an integer, write a function to determine if it is a power of two.
8 | *
9 | * Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating
10 | * all test cases.
11 | *
12 | *
13 | *
14 | **********************************************************************************/
15 |
16 |
17 | class Solution {
18 | public:
19 |
20 | // count the number fo bits 1, if it only has one, then return true
21 | bool isPowerOfTwo01(int n) {
22 | int cnt = 0; //num of bits 1
23 | for(; n>0; n>>=1){
24 | if ( n & 1 ) {
25 | cnt++;
26 | if (cnt>1) return false;
27 | }
28 | }
29 | return cnt==1;
30 | }
31 |
32 | //we notice: 2^n - 1 always be 1111111...
33 | //so, (2^n) & (2^n-1) always be zero
34 | bool isPowerOfTwo02(int n) {
35 | return n<=0 ? false : (n & (n-1)) == 0;
36 | }
37 |
38 | bool isPowerOfTwo(int n) {
39 | if (random()%2){
40 | return isPowerOfTwo02(n);
41 | }
42 | return isPowerOfTwo01(n);
43 | }
44 | };
45 |
--------------------------------------------------------------------------------
/algorithms/cpp/plusOne/plusOne.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/plus-one/
2 | // Author : Hao Chen
3 | // Date : 2014-06-21
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 | #include
14 | #include
15 | using namespace std;
16 |
17 | vector plusOne(vector &digits) {
18 | int carry=1;
19 | vector v;
20 | while(digits.size()>0){
21 | int x = digits.back();
22 | digits.pop_back();
23 | x = x + carry;
24 | v.insert(v.begin(), x%10);
25 | carry = x/10;
26 | }
27 | if (carry>0){
28 | v.insert(v.begin(), carry);
29 | }
30 | return v;
31 |
32 | }
33 |
34 | void printVector(vector& v)
35 | {
36 | cout << "{ ";
37 | for(int i=0; i d(&a[0], &a[0]+sizeof(a)/sizeof(int));
48 | vector v = plusOne(d);
49 | printVector(v);
50 | return 0;
51 | }
52 |
--------------------------------------------------------------------------------
/algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArrays.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://leetcode.com/problems/intersection-of-two-arrays/
2 | // Author : Calinescu Valentin
3 | // Date : 2016-05-20
4 |
5 | /***************************************************************************************
6 | *
7 | * Given two arrays, write a function to compute their intersection.
8 | *
9 | * Example:
10 | * Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
11 | *
12 | * Note:
13 | * Each element in the result must be unique.
14 | * The result can be in any order.
15 | *
16 | ***************************************************************************************/
17 | class Solution {
18 | public:
19 | set inter1, inter2;//we use sets so as to avoid duplicates
20 | vector solution;
21 | vector intersection(vector& nums1, vector& nums2) {
22 | for(int i = 0; i < nums1.size(); i++)
23 | inter1.insert(nums1[i]);//get all of the unique elements in nums1 sorted
24 | for(int i = 0; i < nums2.size(); i++)
25 | if(inter1.find(nums2[i]) != inter1.end())//search inter1 in O(logN)
26 | inter2.insert(nums2[i]);//populate the intersection set
27 | for(set::iterator it = inter2.begin(); it != inter2.end(); ++it)
28 | solution.push_back(*it);//copy the set into a vector
29 | return solution;
30 | }
31 | };
32 |
--------------------------------------------------------------------------------
/algorithms/cpp/validPalindrome/validPalindrome.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/valid-palindrome/
2 | // Author : Hao Chen
3 | // Date : 2014-06-26
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 |
21 | class Solution {
22 | public:
23 | bool isPalindrome(string s) {
24 | s = removeNoise(s);
25 | for(int i=0; i true
16 | * find(7) -> false
17 | *
18 | **********************************************************************************/
19 |
20 | class TwoSum {
21 | private:
22 | unordered_map nums;
23 | public:
24 |
25 | //O(1) add
26 | void add(int number) {
27 | nums[number]++;
28 | }
29 |
30 | //O(n) find
31 | bool find(int value) {
32 | int one, two;
33 | for(auto it = nums.begin(); it != nums.end(); it++){
34 | one = it->first;
35 | two = value - one;
36 | if ( (one == two && it->second > 1) ||
37 | (one != two && nums.find(two) != nums.end() ) ){
38 | return true;
39 | }
40 | }
41 | return false;
42 | }
43 | };
44 |
--------------------------------------------------------------------------------
/algorithms/cpp/addBinary/addBinary.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/add-binary/
2 | // Author : Hao Chen
3 | // Date : 2014-07-05
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 |
17 | #include
18 | #include
19 | using namespace std;
20 |
21 | string addBinary(string a, string b) {
22 | int alen = a.size();
23 | int blen = b.size();
24 | bool carry = false;
25 | string result;
26 | while( alen>0 || blen>0) {
27 | int abit = alen<=0 ? 0 : a[alen-1]-'0';
28 | int bbit = blen<=0 ? 0 : b[blen-1]-'0';
29 | int cbit = carry ? 1 : 0;
30 | result.insert(result.begin(), '0' + ((abit+bbit+cbit) & 1) );
31 | carry = (abit+bbit+cbit>1);
32 | alen--; blen--;
33 | }
34 | if (carry){
35 | result.insert(result.begin(), '1');
36 | }
37 | return result;
38 | }
39 |
40 |
41 | int main(int argc, char** argv)
42 | {
43 | string a = "11";
44 | string b = "1";
45 | if (argc>2){
46 | a = argv[1];
47 | b = argv[2];
48 | }
49 |
50 | cout << a << "+" << b << "=" << addBinary(a, b) << endl;
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/algorithms/cpp/productOfArrayExceptSelf/ProductOfArrayExceptSelf.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://leetcode.com/problems/product-of-array-except-self/
2 | // Author : Hao Chen
3 | // Date : 2015-07-17
4 |
5 | /**********************************************************************************
6 | *
7 | * Given an array of n integers where n > 1, nums, return an array output such that
8 | * output[i] is equal to the product of all the elements of nums except nums[i].
9 | *
10 | * Solve it without division and in O(n).
11 | *
12 | * For example, given [1,2,3,4], return [24,12,8,6].
13 | *
14 | * Follow up:
15 | * Could you solve it with constant space complexity? (Note: The output array does not
16 | * count as extra space for the purpose of space complexity analysis.)
17 | *
18 | **********************************************************************************/
19 |
20 | class Solution {
21 | public:
22 | vector productExceptSelf(vector& nums) {
23 |
24 | int len = nums.size();
25 | vector result(len, 1);
26 |
27 | //from the left to right
28 | for (int i=1; i=0; i--){
34 | factorial *= nums[i+1];
35 | result[i] *= factorial;
36 | }
37 | return result;
38 | }
39 | };
40 |
41 |
42 |
43 |
--------------------------------------------------------------------------------
/algorithms/cpp/twoSum/twoSum.II.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/two-sum-ii-input-array-is-sorted/
2 | // Author : Hao Chen
3 | // Date : 2014-12-25
4 |
5 | /**********************************************************************************
6 | *
7 | * Given an array of integers that is already sorted in ascending order,
8 | * find two numbers such that they add up to a specific target number.
9 | *
10 | * The function twoSum should return indices of the two numbers such that they add up to the target,
11 | * where index1 must be less than index2. Please note that your returned answers (both index1 and index2)
12 | * are not zero-based.
13 | *
14 | * You may assume that each input would have exactly one solution.
15 | *
16 | * Input: numbers={2, 7, 11, 15}, target=9
17 | * Output: index1=1, index2=2
18 | *
19 | **********************************************************************************/
20 |
21 |
22 |
23 | class Solution {
24 | public:
25 | vector twoSum(vector &numbers, int target) {
26 | vector result;
27 | int low=0, high = numbers.size()-1;
28 | while (low < high){
29 | if (numbers[low] + numbers[high] == target){
30 | result.push_back(low+1);
31 | result.push_back(high+1);
32 | return result;
33 | }else{
34 | numbers[low] + numbers[high] > target ? high-- : low++;
35 | }
36 | }
37 |
38 | return result;
39 | }
40 | };
41 |
--------------------------------------------------------------------------------
/algorithms/java/src/maximumDepthOfBinaryTree/maximumDepthOfBinaryTree.java:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/maximum-depth-of-binary-tree/
2 | // Inspired by : http://www.jiuzhang.com/solutions/maximum-depth-of-binary-tree/
3 | // Author : Lei Cao
4 | // Date : 2015-10-03
5 |
6 | /**********************************************************************************
7 | *
8 | * Given a binary tree, find its maximum depth.
9 | *
10 | * The maximum depth is the number of nodes along the longest path from the root node
11 | * down to the farthest leaf node.
12 | *
13 | **********************************************************************************/
14 |
15 |
16 | package maximumDepthOfBinaryTree;
17 |
18 | /**
19 | * Definition for a binary tree node.
20 | * public class TreeNode {
21 | * int val;
22 | * TreeNode left;
23 | * TreeNode right;
24 | * TreeNode(int x) { val = x; }
25 | * }
26 | */
27 | public class maximumDepthOfBinaryTree {
28 | public int maxDepth(TreeNode root) {
29 | if (root == null) {
30 | return 0;
31 | }
32 | return theDepth(root);
33 | }
34 |
35 | private int theDepth(TreeNode root) {
36 | int leftDepth = 1;
37 | int rightDepth = 1;
38 |
39 | if (root.left != null) {
40 | leftDepth = theDepth(root.left) + 1;
41 | }
42 | if (root.right != null) {
43 | rightDepth = theDepth(root.right) + 1;
44 | }
45 | return Math.max(leftDepth, rightDepth);
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/algorithms/cpp/sqrt/sqrt.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/sqrtx/
2 | // Author : Hao Chen
3 | // Date : 2014-08-26
4 |
5 | /**********************************************************************************
6 | *
7 | * Implement int sqrt(int x).
8 | *
9 | * Compute and return the square root of x.
10 | *
11 | **********************************************************************************/
12 |
13 | #include
14 | #include
15 | using namespace std;
16 |
17 |
18 | int sqrt(int x) {
19 |
20 | if (x <=0 ) return 0;
21 |
22 | //the sqrt is not greater than x/2+1
23 | int e = x/2+1;
24 | int s = 0;
25 | // binary search
26 | while ( s <= e ) {
27 | int mid = s + (e-s)/2;
28 | long long sq = (long long)mid*(long long)mid;
29 | if (sq == x ) return mid;
30 | if (sq < x) {
31 | s = mid + 1;
32 | }else {
33 | e = mid - 1;
34 | }
35 | }
36 | return e;
37 |
38 | }
39 |
40 | // http://en.wikipedia.org/wiki/Newton%27s_method
41 | int sqrt_nt(int x) {
42 | if (x == 0) return 0;
43 | double last = 0;
44 | double res = 1;
45 | while (res != last)
46 | {
47 | last = res;
48 | res = (res + x / res) / 2;
49 | }
50 | return int(res);
51 | }
52 |
53 |
54 | int main(int argc, char**argv)
55 | {
56 | int n = 2;
57 | if( argc > 1 ){
58 | n = atoi(argv[1]);
59 | }
60 | cout << "sqrt(" << n << ") = " << sqrt(n) << endl;
61 | return 0;
62 | }
63 |
--------------------------------------------------------------------------------
/algorithms/java/src/lruCache/LRUCache.java:
--------------------------------------------------------------------------------
1 | /*
2 | Analogous to the C++ solution at:
3 | https://github.com/haoel/leetcode/blob/625ad10464701fc4177b9ef33c8ad052d0a7d984/algorithms/cpp/LRUCache/LRUCache.cpp
4 | which uses linked list + hash map. But the Java stdlib provides LinkedHashMap
5 | which already implements that for us, making this solution shorter.
6 |
7 | This could also be done by using, but that generates
8 | some inheritance boilerplate, and ends up taking the same number of lines:
9 | https://github.com/cirosantilli/haoel-leetcode/commit/ff04930b2dc31f270854e40b560723577c7b49fd
10 | */
11 |
12 | import java.util.LinkedHashMap;
13 | import java.util.Iterator;
14 |
15 | public class LRUCache {
16 |
17 | private int capacity;
18 | private LinkedHashMap map;
19 |
20 | public LRUCache(int capacity) {
21 | this.capacity = capacity;
22 | this.map = new LinkedHashMap<>();
23 | }
24 |
25 | public int get(int key) {
26 | Integer value = this.map.get(key);
27 | if (value == null) {
28 | value = -1;
29 | } else {
30 | this.set(key, value);
31 | }
32 | return value;
33 | }
34 |
35 | public void set(int key, int value) {
36 | if (this.map.containsKey(key)) {
37 | this.map.remove(key);
38 | } else if (this.map.size() == this.capacity) {
39 | Iterator it = this.map.keySet().iterator();
40 | it.next();
41 | it.remove();
42 | }
43 | map.put(key, value);
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/algorithms/cpp/reverseLinkedList/reverseLinkedList.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://leetcode.com/problems/reverse-linked-list/
2 | // Author : Hao Chen
3 | // Date : 2015-06-09
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 |
17 |
18 | /**
19 | * Definition for singly-linked list.
20 | * struct ListNode {
21 | * int val;
22 | * ListNode *next;
23 | * ListNode(int x) : val(x), next(NULL) {}
24 | * };
25 | */
26 | class Solution {
27 | public:
28 | ListNode* reverseList_iteratively(ListNode* head) {
29 | ListNode *h=NULL, *p=NULL;
30 | while (head){
31 | p = head->next;
32 | head->next = h;
33 | h = head;
34 | head = p;
35 | }
36 | return h;
37 | }
38 | ListNode* reverseList_recursively(ListNode* head) {
39 | if (head==NULL || head->next==NULL) return head;
40 | ListNode *h = reverseList_recursively(head->next);
41 | head->next->next = head;
42 | head->next = NULL;
43 | return h;
44 |
45 | }
46 | ListNode* reverseList(ListNode* head) {
47 | return reverseList_iteratively(head);
48 | return reverseList_recursively(head);
49 | }
50 | };
51 |
--------------------------------------------------------------------------------
/algorithms/cpp/rotateList/rotateList.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/rotate-list/
2 | // Author : Hao Chen
3 | // Date : 2014-06-20
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 | /**
16 | * Definition for singly-linked list.
17 | * struct ListNode {
18 | * int val;
19 | * ListNode *next;
20 | * ListNode(int x) : val(x), next(NULL) {}
21 | * };
22 | */
23 | class Solution {
24 | public:
25 | ListNode *rotateRight(ListNode *head, int k) {
26 | if (!head || k<=0){
27 | return head;
28 | }
29 |
30 | //find the length of List
31 | int len=1;
32 | ListNode *p=head;
33 | while( p->next != NULL ){
34 | p = p->next;
35 | len++;
36 | }
37 | //connect the tail to head
38 | p->next = head;
39 | //find the left place (take care the case - k > len)
40 | k = len - k % len;
41 |
42 | //find the place
43 | for(int i=0; inext;
45 | }
46 |
47 | //break the list
48 | head = p->next;
49 | p->next = NULL;
50 |
51 | return head;
52 |
53 | }
54 | };
55 |
--------------------------------------------------------------------------------
/algorithms/java/src/binaryTreePreorderTraversal/binaryTreePreorderTraversal.java:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/binary-tree-preorder-traversal/
2 | // Inspired by : http://www.jiuzhang.com/solutions/binary-tree-preorder-traversal/
3 | // Author : Lei Cao
4 | // Date : 2015-10-05
5 |
6 | /**********************************************************************************
7 | *
8 | * Given a binary tree, return the preorder traversal of its nodes' values.
9 | *
10 | * For example:
11 | * Given binary tree {1,#,2,3},
12 | *
13 | * 1
14 | * \
15 | * 2
16 | * /
17 | * 3
18 | *
19 | * return [1,2,3].
20 | *
21 | * Note: Recursive solution is trivial, could you do it iteratively?
22 | *
23 | **********************************************************************************/
24 |
25 | package binaryTreePreorderTraversal;
26 |
27 | import java.util.ArrayList;
28 | import java.util.List;
29 |
30 | /**
31 | * Created by leicao on 5/10/15.
32 | */
33 | public class binaryTreePreorderTraversal {
34 |
35 | //Version 1: Traverse
36 | public List preorderTraversal(TreeNode root) {
37 | List results = new ArrayList();
38 | traversal(results, root);
39 | return results;
40 |
41 | }
42 |
43 | private void traversal(List results, TreeNode root) {
44 | if (results == null || root == null) {
45 | return;
46 | }
47 | results.add(root.val);
48 | traversal(results, root.left);
49 | traversal(results, root.right);
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/algorithms/cpp/containsDuplicate/ContainsDuplicate.III.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://leetcode.com/problems/contains-duplicate-iii/
2 | // Author : Hao Chen
3 | // Date : 2015-06-12
4 |
5 | /**********************************************************************************
6 | *
7 | * Given an array of integers, find out whether there are two distinct indices i and j
8 | * in the array such that the difference between nums[i] and nums[j] is at most t and
9 | * the difference between i and j is at most k.
10 | *
11 | **********************************************************************************/
12 |
13 |
14 |
15 | class Solution {
16 | public:
17 | bool containsNearbyAlmostDuplicate(vector& nums, int k, int t) {
18 | if(nums.size() < 2 || k == 0) return false;
19 | int low = 0;
20 | //maintain a sliding window
21 | set window;
22 | for (int i=0; i k) {
25 | window.erase(nums[low]);
26 | low++;
27 | }
28 |
29 | // lower_bound() is the key,
30 | // it returns an iterator pointing to the first element >= val
31 | auto it = window.lower_bound((long long)nums[i] - (long long)t );
32 | if (it != window.end() && abs((long long)nums[i] - *it) <= (long long)t) {
33 | return true;
34 | }
35 | window.insert(nums[i]);
36 | }
37 | return false;
38 | }
39 | };
40 |
41 |
--------------------------------------------------------------------------------
/algorithms/cpp/validParentheses/validParentheses.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/valid-parentheses/
2 | // Author : Hao Chen
3 | // Date : 2014-06-30
4 |
5 | /**********************************************************************************
6 | *
7 | * Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
8 | * determine if the input string is valid.
9 | *
10 | * The brackets must close in the correct order, "()" and "()[]{}" are all valid
11 | * but "(]" and "([)]" are not.
12 | *
13 | *
14 | **********************************************************************************/
15 |
16 | #include
17 | #include
18 | #include
19 | using namespace std;
20 |
21 | bool isValid(string s) {
22 | stack st;
23 | for(auto ch : s) {
24 | if (ch=='{' || ch =='[' || ch=='(' ) {
25 | st.push(ch);
26 | }else if (ch=='}' || ch ==']' || ch == ')' ){
27 | if (st.empty()) return false;
28 | char sch = st.top();
29 | if ( (sch=='{' && ch =='}') || (sch=='[' && ch==']') || (sch=='(' && ch==')' ) ){
30 | st.pop();
31 | }else {
32 | return false;
33 | }
34 | }else{
35 | return false;
36 | }
37 | }
38 | return st.empty();
39 | }
40 |
41 | int main(int argc, char**argv)
42 | {
43 | string s = "{{}{[]()}}";
44 | if (argc>1){
45 | s = argv[1];
46 | }
47 | cout << "str = \"" << (s) << "\"" << endl;
48 | cout << isValid(s) << endl;
49 | }
50 |
--------------------------------------------------------------------------------
/algorithms/java/src/findMinimumInRotatedSortedArray/findMinimumInRotatedSortedArray.java:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array/
2 | // Inspired by : http://www.jiuzhang.com/solutions/find-minimum-in-rotated-sorted-array/
3 | // Author : Lei Cao
4 | // Date : 2014-10-05
5 |
6 | /**********************************************************************************
7 | *
8 | * Suppose a sorted array is rotated at some pivot unknown to you beforehand.
9 | *
10 | * (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
11 | *
12 | * Find the minimum element.
13 | *
14 | * You may assume no duplicate exists in the array.
15 | *
16 | **********************************************************************************/
17 |
18 | package findMinimumInRotatedSortedArray;
19 |
20 | public class findMinimumInRotatedSortedArray {
21 | public int findMin(int[] num) {
22 | if (num == null || num.length == 0) {
23 | return Integer.MIN_VALUE;
24 | }
25 |
26 | int start = 0;
27 | int end = num.length - 1;
28 |
29 | while (start + 1 < end) {
30 | int mid = start + (end - start) / 2;
31 | if (num[start] < num[end]) {
32 | end = mid;
33 | } else if (num[start] < num[mid]) {
34 | start = mid;
35 | } else {
36 | end = mid;
37 | }
38 | }
39 |
40 | if (num[start] < num[end]) {
41 | return num[start];
42 | } else {
43 | return num[end];
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/algorithms/java/src/searchRangeInBinarySearchTree/searchRangeInBinarySearchTreeTest.java:
--------------------------------------------------------------------------------
1 | package searchRangeInBinarySearchTree;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.ArrayList;
6 | import java.util.Collection;
7 |
8 | import static org.junit.Assert.*;
9 |
10 | /**
11 | * Created by leicao on 9/10/15.
12 | */
13 | public class searchRangeInBinarySearchTreeTest {
14 |
15 | @Test
16 | public void testSearchRange() throws Exception {
17 | ArrayList inputs = new ArrayList();
18 |
19 | TreeNode t1 = new TreeNode(20);
20 | TreeNode t2 = new TreeNode(8);
21 | TreeNode t3 = new TreeNode(22);
22 | TreeNode t4 = new TreeNode(4);
23 | TreeNode t5 = new TreeNode(12);
24 |
25 | t1.left = t2;
26 | t1.right = t3;
27 | t2.left = t4;
28 | t2.right = t5;
29 |
30 | inputs.add(t1);
31 |
32 | int[][] ranges = {
33 | {10,22}
34 | };
35 |
36 | ArrayList> results = new ArrayList>(){{
37 | add(new ArrayList(){{
38 | add(12);
39 | add(20);
40 | add(22);
41 | }});
42 | }};
43 |
44 | for (int i = 0; i < results.size(); i++) {
45 | searchRangeInBinarySearchTree s = new searchRangeInBinarySearchTree();
46 | ArrayList r = s.searchRange(inputs.get(i), ranges[i][0], ranges[i][1]);
47 | assertTrue(r.containsAll(results.get(i)) && r.size() == results.get(i).size());
48 | }
49 | }
50 | }
--------------------------------------------------------------------------------
/algorithms/cpp/largestNumber/largestNumber.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/largest-number/
2 | // Author : Hao Chen
3 | // Date : 2015-01-16
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 | * Credits:Special thanks to @ts for adding this problem and creating all test cases.
14 | *
15 | **********************************************************************************/
16 |
17 | class Solution {
18 | public:
19 |
20 | //compare function
21 | static bool comp (string& s1, string& s2) { return s1+s2 > s2+s1; }
22 |
23 | string largestNumber(vector &num) {
24 |
25 | //convert int to string
26 | vector v;
27 | for (int i=0; i
22 | #include
23 |
24 | int lengthOfLastWord(const char *s) {
25 |
26 | if ( !s ||!*s ) return 0;
27 |
28 | int wordLen=0;
29 | int cnt=0;
30 |
31 | for (;*s!='\0';s++) {
32 | if (isalpha(*s)){
33 | cnt++;
34 | }
35 | if (!isalpha(*s)){
36 | if (cnt>0){
37 | wordLen = cnt;
38 | }
39 | cnt=0;
40 | }
41 | }
42 |
43 | return cnt>0 ? cnt : wordLen;
44 | }
45 |
46 |
47 | int main(int argc, char** argv)
48 | {
49 | const char* p;
50 | p = "hello world";
51 | printf("%s, %d\n", p, lengthOfLastWord(p));
52 | p = "a";
53 | printf("%s, %d\n", p, lengthOfLastWord(p));
54 |
55 | if(argc>1){
56 | p = argv[1];
57 | printf("%s, %d\n", p, lengthOfLastWord(p));
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/algorithms/cpp/searchInsertPosition/searchInsertPosition.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/search-insert-position/
2 | // Author : Hao Chen
3 | // Date : 2014-06-22
4 |
5 | /**********************************************************************************
6 | *
7 | * Given a sorted array and a target value, return the index if the target is found.
8 | * If not, return the index where it would be if it were inserted in order.
9 | *
10 | * You may assume no duplicates in the array.
11 | *
12 | * Here are few examples.
13 | * [1,3,5,6], 5 → 2
14 | * [1,3,5,6], 2 → 1
15 | * [1,3,5,6], 7 → 4
16 | * [1,3,5,6], 0 → 0
17 | *
18 | *
19 | **********************************************************************************/
20 |
21 | #include
22 |
23 |
24 | int binary_search(int A[], int n, int key) {
25 | int low = 0;
26 | int high = n-1;
27 | while (low <= high){
28 | int mid = low +(high-low)/2;
29 | if (A[mid] == key){
30 | return mid;
31 | }
32 | if ( key> A[mid] ) {
33 | low = mid+1;
34 | }else{
35 | high = mid-1;
36 | }
37 | }
38 | return low;
39 | }
40 | int searchInsert(int A[], int n, int target) {
41 | if (n==0) return n;
42 | return binary_search(A, n, target);
43 | }
44 |
45 | int main()
46 | {
47 | int a[]={1,3,5,6};
48 | printf("%d -> %d\n", 5, searchInsert(a, 4, 5));
49 | printf("%d -> %d\n", 2, searchInsert(a, 4, 2));
50 | printf("%d -> %d\n", 7, searchInsert(a, 4, 7));
51 | printf("%d -> %d\n", 0, searchInsert(a, 4, 0));
52 | return 0;
53 | }
54 |
--------------------------------------------------------------------------------
/algorithms/cpp/gasStation/gasStation.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/gas-station/
2 | // Author : Hao Chen
3 | // Date : 2014-10-11
4 |
5 | /**********************************************************************************
6 | *
7 | * There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
8 | *
9 | * You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to
10 | * its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
11 | *
12 | * Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.
13 | *
14 | * Note:
15 | * The solution is guaranteed to be unique.
16 | *
17 | *
18 | **********************************************************************************/
19 |
20 | class Solution {
21 | public:
22 | int canCompleteCircuit(vector &gas, vector &cost) {
23 | int current = 0;
24 | int start = gas.size(); //start from the end to beginning
25 | int total = 0;
26 |
27 | do {
28 | if (total + gas[current] - cost[current] >= 0) {
29 | total += (gas[current] - cost[current]);
30 | current++; // can go from current to current+1
31 | }else{
32 | start--; //not enough gas, try to start the one before origin start point.
33 | total += (gas[start] - cost[start]);
34 | }
35 | } while(current != start);
36 |
37 | return total>=0 ? start % gas.size() : -1;
38 | }
39 | };
40 |
--------------------------------------------------------------------------------
/algorithms/cpp/reverseVowelsOfAString/reverseVowelsOfAString.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://leetcode.com/problems/reverse-vowels-of-a-string/
2 | // Author : Calinescu Valentin
3 | // Date : 2016-04-30
4 |
5 | /***************************************************************************************
6 | *
7 | * Write a function that takes a string as input and reverse only the vowels of a
8 | * string.
9 | *
10 | * Example 1:
11 | * Given s = "hello", return "holle".
12 | *
13 | * Example 2:
14 | * Given s = "leetcode", return "leotcede".
15 | *
16 | ***************************************************************************************/
17 | class Solution {
18 | public:
19 | string reverseVowels(string s) {
20 | list vowels;
21 | set vows;
22 | vows.insert('a');
23 | vows.insert('A');
24 | vows.insert('e');
25 | vows.insert('E');
26 | vows.insert('i');
27 | vows.insert('I');
28 | vows.insert('o');
29 | vows.insert('O');
30 | vows.insert('u');
31 | vows.insert('U');
32 | string result;
33 | for(int i = 0; i < s.size(); i++)
34 | {
35 | if(vows.find(s[i]) != vows.end())
36 | vowels.push_back(s[i]);
37 | }
38 | for(int i = 0; i < s.size(); i++)
39 | {
40 | if(vows.find(s[i]) != vows.end())
41 | {
42 | result.push_back(vowels.back());
43 | vowels.pop_back();
44 | }
45 | else
46 | result.push_back(s[i]);
47 | }
48 | return result;
49 | }
50 | };
51 |
--------------------------------------------------------------------------------
/algorithms/cpp/removeNthNodeFromEndOfList/removeNthNodeFromEndOfList.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/
2 | // Author : Hao Chen
3 | // Date : 2014-06-21
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 | *
15 | * Note:
16 | * Given n will always be valid.
17 | * Try to do this in one pass.
18 | *
19 | *
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 *removeNthFromEnd(ListNode *head, int n) {
33 | if (head==NULL || n<=0){
34 | return NULL;
35 | }
36 | ListNode fakeHead(0);
37 | fakeHead.next=head;
38 | head=&fakeHead;
39 |
40 | ListNode *p1, *p2;
41 | p1=p2=head;
42 | for(int i=0; inext;
45 | }
46 | while (p2->next!=NULL){
47 | p2=p2->next;
48 | p1=p1->next;
49 | }
50 |
51 | p1->next = p1->next->next;
52 | return head->next;
53 | }
54 | };
55 |
--------------------------------------------------------------------------------
/algorithms/cpp/increasingTripletSubsequence/increasingTripletSubsequence.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://leetcode.com/problems/increasing-triplet-subsequence/
2 | // Author : Calinescu Valentin
3 | // Date : 2016-02-27
4 |
5 | /***************************************************************************************
6 | *
7 | * Given an unsorted array return whether an increasing subsequence of length 3 exists
8 | * or not in the array.
9 | *
10 | * Formally the function should:
11 | * Return true if there exists i, j, k
12 | * such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false.
13 | * Your algorithm should run in O(n) time complexity and O(1) space complexity.
14 | *
15 | * Examples:
16 | * Given [1, 2, 3, 4, 5],
17 | * return true.
18 | *
19 | * Given [5, 4, 3, 2, 1],
20 | * return false.
21 | *
22 | ***************************************************************************************/
23 | class Solution {
24 | public:
25 | bool increasingTriplet(vector& nums) {
26 | bool solution = false;
27 | if(nums.size())
28 | {
29 | int first = nums[0];
30 | int second = 0x7fffffff; //MAX_INT so we can always find something smaller than it
31 | for(int i = 1; i < nums.size() && !solution; i++)
32 | {
33 | if(nums[i] > second)
34 | solution = true;
35 | else if(nums[i] > first && nums[i] < second)
36 | second = nums[i];
37 | else if(nums[i] < first)
38 | first = nums[i];
39 | }
40 | }
41 | return solution;
42 | }
43 | };
44 |
--------------------------------------------------------------------------------
/algorithms/cpp/palindromeLinkedList/PalindromeLinkedList.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://leetcode.com/problems/palindrome-linked-list/
2 | // Author : Hao Chen
3 | // Date : 2015-07-17
4 |
5 | /**********************************************************************************
6 | *
7 | * Given a singly linked list, determine if it is a palindrome.
8 | *
9 | * Follow up:
10 | * Could you do it in O(n) time and O(1) space?
11 | *
12 | **********************************************************************************/
13 |
14 | /**
15 | * Definition for singly-linked list.
16 | * struct ListNode {
17 | * int val;
18 | * ListNode *next;
19 | * ListNode(int x) : val(x), next(NULL) {}
20 | * };
21 | */
22 | class Solution {
23 | public:
24 | ListNode* findMiddle(ListNode* head) {
25 | ListNode *p1=head, *p2=head;
26 | while(p2 && p2->next){
27 | p1 = p1->next;
28 | p2 = p2->next->next;
29 | }
30 | return p1;
31 | }
32 |
33 | ListNode* reverseLink(ListNode* head) {
34 | ListNode* p=NULL;
35 |
36 | while (head) {
37 | ListNode* q = head->next;
38 | head->next = p;
39 | p = head;
40 | head = q;
41 | }
42 | return p;
43 | }
44 |
45 | bool isPalindrome(ListNode* head) {
46 | ListNode* pMid = findMiddle(head);
47 | ListNode* pRev = reverseLink(pMid);
48 | for(;head!=pMid; head=head->next, pRev=pRev->next) {
49 | if (head->val != pRev->val) {
50 | return false;
51 | }
52 | }
53 | return true;
54 | }
55 | };
56 |
57 |
58 |
--------------------------------------------------------------------------------
/algorithms/cpp/integerBreak/IntegerBreak.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://leetcode.com/problems/integer-break/
2 | // Author : Hao Chen
3 | // Date : 2016-05-29
4 |
5 | /***************************************************************************************
6 | *
7 | * Given a positive integer n, break it into the sum of at least two positive integers
8 | * and maximize the product of those integers. Return the maximum product you can get.
9 | *
10 | * For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3
11 | * + 4).
12 | *
13 | * Note: you may assume that n is not less than 2.
14 | *
15 | * There is a simple O(n) solution to this problem.
16 | * You may check the breaking results of n ranging from 7 to 10 to discover the
17 | * regularities.
18 | *
19 | * Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating
20 | * all test cases.
21 | ***************************************************************************************/
22 |
23 | class Solution {
24 | public:
25 | // As the hint said, checking the n with ranging from 7 to 10 to discover the regularities.
26 | // n = 7, 3*4 = 12
27 | // n = 8, 3*3*2 = 18
28 | // n = 9, 3*3*3 = 27
29 | // n = 10, 3*3*4 = 36
30 | // n = 11, 3*3*3*2 = 54
31 | //
32 | // we can see we can break the number by 3 if it is greater than 4;
33 | //
34 | int integerBreak(int n) {
35 | if ( n == 2 ) return 1;
36 | if ( n == 3 ) return 2;
37 | int result = 1;
38 | while( n > 4 ) {
39 | result *= 3;
40 | n -= 3;
41 | }
42 | result *= n;
43 | return result;
44 | }
45 | };
46 |
47 |
--------------------------------------------------------------------------------
/algorithms/java/src/firstBadVersion/firstBadVersion.java:
--------------------------------------------------------------------------------
1 | // Source : https://leetcode.com/problems/first-bad-version/
2 | // Inspired by : http://www.jiuzhang.com/solutions/first-bad-version/
3 | // Author : Lei Cao
4 | // Date : 2014-10-05
5 |
6 | /**********************************************************************************
7 | *
8 | * The code base version is an integer start from 1 to n.
9 | * One day, someone committed a bad version in the code case, so it caused this version and the following versions are all failed in the unit tests.
10 | * Find the first bad version.
11 | *
12 | * You can call isBadVersion to help you determine which version is the first bad one.
13 | * The details interface can be found in the code's annotation part.
14 | *
15 | **********************************************************************************/
16 |
17 | package firstBadVersion;
18 |
19 | /* The isBadVersion API is defined in the parent class VersionControl.
20 | boolean isBadVersion(int version); */
21 | public class firstBadVersion extends VersionControl {
22 | public int firstBadVersion(int n) {
23 | if (n < 1) {
24 | return 0;
25 | }
26 | int start = 1;
27 | int end = n;
28 |
29 | while (start + 1 < end) {
30 | int mid = start + (end - start) / 2;
31 | if (super.isBadVersion(mid)) {
32 | end = mid;
33 | } else {
34 | start = mid;
35 | }
36 | }
37 |
38 | if (super.isBadVersion(start)) {
39 | return start;
40 | }
41 | if (super.isBadVersion(end)) {
42 | return end;
43 | }
44 | return 0;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/algorithms/cpp/minimumPathSum/minimumPathSum.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/minimum-path-sum/
2 | // Author : Hao Chen
3 | // Date : 2014-06-21
4 |
5 | /**********************************************************************************
6 | *
7 | * Given a m x n grid filled with non-negative numbers, find a path from top left to
8 | * bottom right which minimizes the sum of all numbers along its path.
9 | *
10 | * Note: You can only move either down or right at any point in time.
11 | *
12 | **********************************************************************************/
13 |
14 | #include
15 | #include
16 | #include
17 | using namespace std;
18 |
19 | int minPathSum(vector > &grid) {
20 | if (grid.size()<=0){
21 | return 0;
22 | }
23 | int i, j;
24 | for(i=0; i > grid;
44 | for(int i=0; i<6; i++){
45 | vector v;
46 | for(int j=0; j<2; j++){
47 | v.push_back(a[i][j]);
48 | }
49 | grid.push_back(v);
50 | }
51 |
52 | cout << "minPathSum=" << minPathSum(grid) << endl;
53 |
54 | return 0;
55 | }
56 |
57 |
--------------------------------------------------------------------------------
/algorithms/cpp/convertSortedArrayToBinarySearchTree/convertSortedArrayToBinarySearchTree.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
2 | // Author : Hao Chen
3 | // Date : 2014-06-23
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 | /**
12 | * Definition for binary tree
13 | * struct TreeNode {
14 | * int val;
15 | * TreeNode *left;
16 | * TreeNode *right;
17 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
18 | * };
19 | */
20 | class Solution {
21 | public:
22 | TreeNode *sortedArrayToBST(vector &num) {
23 | if(num.size()==0){
24 | return NULL;
25 | }
26 | if(num.size()==1){
27 | return new TreeNode(num[0]);
28 | }
29 | int mid = num.size()/2;
30 |
31 | TreeNode *node = new TreeNode(num[mid]);
32 |
33 | vector::const_iterator first;
34 | vector::const_iterator last;
35 |
36 | first = num.begin();
37 | last = num.begin()+mid;
38 | vector v(first, last);
39 | node->left = sortedArrayToBST(v);
40 |
41 | if (mid==num.size()-1){
42 | node->right = NULL;
43 | }else{
44 | first = num.begin()+mid+1;
45 | last = num.end();
46 | vector v(first, last);
47 | node->right = sortedArrayToBST(v);
48 | }
49 | return node;
50 | }
51 | };
52 |
--------------------------------------------------------------------------------
/algorithms/java/src/inorderSuccessorInBST/inorderSuccessorInBSTTest.java:
--------------------------------------------------------------------------------
1 | package inorderSuccessorInBST;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.ArrayList;
6 |
7 | import static org.junit.Assert.*;
8 |
9 | /**
10 | * Created by leicao on 7/10/15.
11 | */
12 | public class inorderSuccessorInBSTTest {
13 |
14 | @Test
15 | public void testInorderSuccessor() throws Exception {
16 | ArrayList inputes = new ArrayList();
17 | ArrayList targets = new ArrayList();
18 |
19 | TreeNode n0 = new TreeNode(2);
20 | TreeNode n1 = new TreeNode(1);
21 | TreeNode n2 = new TreeNode(3);
22 | n0.left = n1;
23 | n0.right = n2;
24 | inputes.add(n0);
25 | targets.add(n2);
26 |
27 | TreeNode nn0 = new TreeNode(2);
28 | TreeNode nn1 = new TreeNode(1);
29 | nn0.left = nn1;
30 | inputes.add(nn0);
31 | targets.add(nn1);
32 |
33 | TreeNode t0 = new TreeNode(1);
34 | TreeNode t1 = new TreeNode(2);
35 | t0.right = t1;
36 | inputes.add(t0);
37 | targets.add(t0);
38 |
39 |
40 | ArrayList results = new ArrayList();
41 | results.add(null);
42 | results.add(nn0);
43 | results.add(t1);
44 |
45 | for (int i = 0; i < results.size(); i++) {
46 | inorderSuccessorInBST finder = new inorderSuccessorInBST();
47 | TreeNode node = finder.inorderSuccessor(inputes.get(i), targets.get(i));
48 | System.out.println(node);
49 | boolean result = node == results.get(i) || node.val == results.get(i).val;
50 | assertTrue(result);
51 | }
52 | }
53 | }
--------------------------------------------------------------------------------
/algorithms/cpp/generateParentheses/generateParentheses.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/generate-parentheses/
2 | // Author : Hao Chen
3 | // Date : 2014-06-29
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 |
16 | #include
17 | #include
18 | #include
19 | using namespace std;
20 |
21 |
22 | void generator(vector& result, int left, int right, string s);
23 | vector generateParenthesis(int n) {
24 |
25 | vector result;
26 | string s;
27 | generator(result, n, n, s);
28 | return result;
29 | }
30 |
31 | void generator(vector& result, int left, int right, string s){
32 | if (left==0 && right==0){
33 | result.push_back(s);
34 | return;
35 | }
36 | if (left>0){
37 | generator(result, left-1, right, s+'(');
38 | }
39 | if (right>0 && right>left){
40 | generator(result, left, right-1, s+')');
41 | }
42 | }
43 |
44 | void printResult(vector& result)
45 | {
46 | for(int i=0; i1){
55 | n = atoi(argv[1]);
56 | }
57 | vector r = generateParenthesis(n);
58 | printResult(r);
59 | return 0;
60 | }
61 |
--------------------------------------------------------------------------------
/algorithms/java/src/dynamicProgramming/minimumPathSum/minimumPathSum.java:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/minimum-path-sum/
2 | // Inspired by : http://www.jiuzhang.com/solutions/minimum-path-sum/
3 | // Author : Lei Cao
4 | // Date : 2015-10-12
5 |
6 | /**********************************************************************************
7 | *
8 | * Given a m x n grid filled with non-negative numbers, find a path from top left to
9 | * bottom right which minimizes the sum of all numbers along its path.
10 | *
11 | * Note: You can only move either down or right at any point in time.
12 | *
13 | **********************************************************************************/
14 |
15 | package dynamicProgramming.minimumPathSum;
16 |
17 | public class minimumPathSum {
18 | /**
19 | * @param grid: a list of lists of integers.
20 | * @return: An integer, minimizes the sum of all numbers along its path
21 | */
22 | public int minPathSum(int[][] grid) {
23 | if (grid.length == 0 || grid[0].length == 0) {
24 | return 0;
25 | }
26 | int m = grid.length;
27 | int n = grid[0].length;
28 | int[][] matrix = new int[m][n];
29 |
30 | matrix[0][0] = grid[0][0];
31 | for (int i = 1; i < m; i++) {
32 | matrix[i][0] = grid[i][0] + matrix[i-1][0];
33 | }
34 |
35 | for (int i = 1; i < n; i++) {
36 | matrix[0][i] = grid[0][i] + matrix[0][i-1];
37 | }
38 |
39 | for (int i = 1; i < m; i++) {
40 | for (int j = 1; j < n; j++) {
41 | matrix[i][j] = grid[i][j] + Math.min(matrix[i-1][j], matrix[i][j-1]);
42 | }
43 | }
44 |
45 | return matrix[m-1][n-1];
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/algorithms/cpp/rangeSumQuery-Immutable/rangeSumQuery-Immutable.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://leetcode.com/problems/range-sum-query-immutable/
2 | // Author : Calinescu Valentin, Hao Chen
3 | // Date : 2015-11-10
4 |
5 | /***************************************************************************************
6 | *
7 | * Given an integer array nums, find the sum of the elements between indices i and j
8 | * (i ≤ j), inclusive.
9 | *
10 | * Example:
11 | * Given nums = [-2, 0, 3, -5, 2, -1]
12 | *
13 | * sumRange(0, 2) -> 1
14 | * sumRange(2, 5) -> -1
15 | * sumRange(0, 5) -> -3
16 | * Note:
17 | * You may assume that the array does not change.
18 | * There are many calls to sumRange function.
19 | *
20 | ***************************************************************************************/
21 |
22 | class NumArray {
23 | /*
24 | * Solution
25 | * =========
26 | *
27 | * The sum of all the elements starting from position 0 to position i is stored in
28 | * sums[i]. This way we can reconstruct the sum from position i to position j by
29 | * subtracting sums[i - 1] from sums[j], leaving us with the sum of the desired elements.
30 | *
31 | * Note: we can add a dummy sum at then beginning to simplify the code
32 | *
33 | */
34 | private:
35 | int size;
36 | vector sums;
37 | public:
38 | NumArray(vector &nums): size(nums.size()), sums(size+1, 0) {
39 | for(int i=0; i
26 | #include
27 | #include
28 | using namespace std;
29 |
30 | string convert(string s, int nRows) {
31 | //The cases no need to do anything
32 | if (nRows<=1 || nRows>=s.size()) return s;
33 |
34 | vector r(nRows);
35 | int row = 0;
36 | int step = 1;
37 | for(int i=0; i
13 | #include
14 |
15 | /*
16 | * Basically, most people think this is very easy as below:
17 | *
18 | * double result = 1.0;
19 | * for (int i=0; i>1;`
36 | * if `n` is an odd number, we can just `result *= x;`
37 | *
38 | */
39 | double pow(double x, int n) {
40 |
41 | bool sign = false;
42 | unsigned int exp = n;
43 | if(n<0){
44 | exp = -n;
45 | sign = true;
46 | }
47 | double result = 1.0;
48 | while (exp) {
49 | if (exp & 1){
50 | result *= x;
51 | }
52 | exp >>= 1;
53 | x *= x;
54 | }
55 |
56 | return sign ? 1/result : result;
57 |
58 | }
59 |
60 | int main(int argc, char** argv){
61 | double x=2.0;
62 | int n = 3;
63 | if (argc==3){
64 | x = atof(argv[1]);
65 | n = atoi(argv[2]);
66 | }
67 | printf("%f\n", pow(x, n));
68 | return 0;
69 | }
70 |
--------------------------------------------------------------------------------
/algorithms/cpp/reverseWordsInAString/reverseWordsInAString.II.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/reverse-words-in-a-string-ii/
2 | // Author : Hao Chen
3 | // Date : 2015-02-09
4 |
5 | /**********************************************************************************
6 | *
7 | * Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.
8 | *
9 | * The input string does not contain leading or trailing spaces and the words are always separated by a single space.
10 | *
11 | * For example,
12 | * Given s = "the sky is blue",
13 | * return "blue is sky the".
14 | *
15 | * Could you do it in-place without allocating extra space?
16 | *
17 | *
18 | **********************************************************************************/
19 |
20 | #include
21 | #include
22 | #include
23 | using namespace std;
24 |
25 |
26 | void swap(char &a, char &b) {
27 | char temp = a;
28 | a = b;
29 | b = temp;
30 | }
31 | void reverse(string &s, int begin, int end) {
32 | while(begin < end) {
33 | swap(s[begin++], s[end--]);
34 | }
35 | }
36 | void reverseWords(string &s) {
37 |
38 | if (s.size()<=1) return;
39 |
40 | // reverse the whole string
41 | reverse(s, 0, s.size()-1);
42 |
43 | // reverse the each word
44 | for ( int begin=0, i=0; i<=s.size(); i++ ) {
45 | if ( isblank(s[i]) || s[i] == '\0') {
46 | reverse(s, begin, i-1);
47 | begin = i+1;
48 | }
49 | }
50 | }
51 |
52 |
53 | int main(int argc, char** argv)
54 | {
55 | string s = "the sky is blue";
56 | if ( argc > 1 ) {
57 | s = argv[1];
58 | }
59 |
60 | cout << s << endl;
61 | reverseWords(s);
62 | cout << s << endl;
63 |
64 | }
65 |
--------------------------------------------------------------------------------
/algorithms/java/src/findPeakElement/findPeakElement.java:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/find-peak-element/
2 | // Inspired by : http://www.jiuzhang.com/solutions/find-peak-element/
3 | // Author : Lei Cao
4 | // Date : 2014-10-05
5 |
6 | /**********************************************************************************
7 | *
8 | * A peak element is an element that is greater than its neighbors.
9 | *
10 | * Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.
11 | *
12 | * You may imagine that num[-1] = num[n] = -∞.
13 | *
14 | * For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.
15 | *
16 | * click to show spoilers.
17 | *
18 | * Note:
19 | * Your solution should be in logarithmic complexity.
20 | *
21 | * Credits:Special thanks to @ts for adding this problem and creating all test cases.
22 | *
23 | **********************************************************************************/
24 |
25 | package findPeakElement;
26 |
27 | public class findPeakElement {
28 | public int findPeakElement(int[] nums) {
29 | if (nums.length == 0) {
30 | return Integer.MIN_VALUE;
31 | }
32 |
33 | int start = 0;
34 | int end = nums.length - 1;
35 |
36 | while (start + 1 < end) {
37 | int mid = start + (end - start) / 2;
38 | if (nums[mid - 1] < nums[mid] && nums[mid] > nums[mid + 1]) {
39 | return mid;
40 | } else if (nums[mid - 1] < nums[mid]) {
41 | start = mid;
42 | } else {
43 | end = mid;
44 | }
45 | }
46 |
47 | if (nums[start] > nums[end]) {
48 | return start;
49 | } else {
50 | return end;
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/algorithms/cpp/binarySearchTreeIterator/binarySearchTreeIterator.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/binary-search-tree-iterator/
2 | // Author : Hao Chen
3 | // Date : 2014-12-31
4 |
5 | /**********************************************************************************
6 | *
7 | * Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
8 | *
9 | * Calling next() will return the next smallest number in the BST.
10 | *
11 | * Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
12 | *
13 | * Credits:Special thanks to @ts for adding this problem and creating all test cases.
14 | *
15 | **********************************************************************************/
16 |
17 | class BSTIterator {
18 | private:
19 | vector v;
20 | int pos;
21 | public:
22 | //Travse the Tree in-order and covert it to an array
23 | BSTIterator(TreeNode *root) {
24 | pos = 0;
25 | vector stack;
26 | while(stack.size()>0 || root !=NULL) {
27 | if (root){
28 | stack.push_back(root);
29 | root = root->left;
30 | }else{
31 | root = stack.back();
32 | stack.pop_back();
33 | v.push_back(root->val);
34 | root = root->right;
35 | }
36 | }
37 | }
38 |
39 | /** @return whether we have a next smallest number */
40 | bool hasNext() {
41 | return pos < v.size();
42 | }
43 |
44 | /** @return the next smallest number */
45 | int next() {
46 | return v[pos++];
47 | }
48 | };
49 |
--------------------------------------------------------------------------------
/algorithms/cpp/anagrams/ValidAnagram.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://leetcode.com/problems/valid-anagram/
2 | // Author : Hao Chen
3 | // Date : 2015-08-16
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 | **********************************************************************************/
17 |
18 |
19 | class Solution {
20 | public:
21 |
22 | //stupid way - but easy to understand - 76ms
23 | bool isAnagram01(string s, string t) {
24 | sort(s.begin(), s.end());
25 | sort(t.begin(), t.end());
26 | return s == t;
27 | }
28 |
29 | //using a map to count every chars in the string.
30 | bool isAnagram02(string s, string t) {
31 | int map[26] ={0} ; //only lowercase alphabets
32 | //memset(map, 0, sizeof(map));
33 |
34 | // count each char for s
35 | for (int i=0; ileft, right=right->right) {
37 | cnt *= 2;
38 | }
39 |
40 | if (left!=NULL || right!=NULL) {
41 | return -1;
42 | }
43 | return cnt-1;
44 | }
45 |
46 | int countNodes(TreeNode* root) {
47 | int cnt = isCompleteTree(root);
48 | if (cnt != -1) return cnt;
49 | int leftCnt = countNodes(root->left);
50 | int rightCnt = countNodes(root->right);
51 | return leftCnt + rightCnt + 1;
52 | }
53 | };
54 |
--------------------------------------------------------------------------------
/algorithms/cpp/oddEvenLinkedList/OddEvenLinkedList.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://leetcode.com/problems/odd-even-linked-list/
2 | // Author : Hao Chen
3 | // Date : 2016-01-16
4 |
5 | /***************************************************************************************
6 | *
7 | * Given a singly linked list, group all odd nodes together followed by the even nodes.
8 | * Please note here we are talking about the node number and not the value in the nodes.
9 | *
10 | * You should try to do it in place. The program should run in O(1) space complexity
11 | * and O(nodes) time complexity.
12 | *
13 | * Example:
14 | * Given 1->2->3->4->5->NULL,
15 | * return 1->3->5->2->4->NULL.
16 | *
17 | * Note:
18 | * The relative order inside both the even and odd groups should remain as it was in
19 | * the input.
20 | * The first node is considered odd, the second node even and so on ...
21 | *
22 | * Credits:Special thanks to @aadarshjajodia for adding this problem and creating all
23 | * test cases.
24 | ***************************************************************************************/
25 |
26 | /**
27 | * Definition for singly-linked list.
28 | * struct ListNode {
29 | * int val;
30 | * ListNode *next;
31 | * ListNode(int x) : val(x), next(NULL) {}
32 | * };
33 | */
34 | class Solution {
35 | public:
36 | ListNode* oddEvenList(ListNode* head) {
37 | if (!head) return head;
38 | ListNode* pOdd = head;
39 | ListNode* p = head->next;
40 | ListNode* pNext = NULL;
41 | while(p && (pNext=p->next)) {
42 |
43 | p->next = pNext->next;
44 | pNext->next = pOdd->next;
45 | pOdd->next = pNext;
46 |
47 | p = p->next;
48 | pOdd = pOdd->next;
49 |
50 | }
51 | return head;
52 | }
53 | };
54 |
--------------------------------------------------------------------------------
/algorithms/cpp/uniquePaths/uniquePaths.II.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/unique-paths-ii/
2 | // Author : Hao Chen
3 | // Date : 2014-06-25
4 |
5 | /**********************************************************************************
6 | *
7 | * Follow up for "Unique Paths":
8 | *
9 | * Now consider if some obstacles are added to the grids. How many unique paths would there be?
10 | *
11 | * An obstacle and empty space is marked as 1 and 0 respectively in the grid.
12 | *
13 | * For example,
14 | * There is one obstacle in the middle of a 3x3 grid as illustrated below.
15 | *
16 | * [
17 | * [0,0,0],
18 | * [0,1,0],
19 | * [0,0,0]
20 | * ]
21 | *
22 | * The total number of unique paths is 2.
23 | *
24 | * Note: m and n will be at most 100.
25 | *
26 | **********************************************************************************/
27 |
28 | #include
29 | #include
30 | using namespace std;
31 |
32 | //As same as DP solution with "Unique Path I", just need to consider the obstacles.
33 | int uniquePathsWithObstacles(vector > &obstacleGrid) {
34 | vector< vector > v = obstacleGrid;
35 | unsigned int max=0;
36 | for (int i=0; i0 && j>0) {
42 | max= v[i][j] = v[i-1][j] + v[i][j-1];
43 | }else if(i>0){
44 | max = v[i][j] = v[i-1][j];
45 | }else if(j>0){
46 | max = v[i][j] = v[i][j-1];
47 | }else{
48 | max = v[i][j] = 1 ;
49 | }
50 | }
51 | }
52 | }
53 | return max;
54 | }
55 |
56 |
57 |
--------------------------------------------------------------------------------
/algorithms/cpp/addTwoNumbers/addTwoNumbers.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/add-two-numbers/
2 | // Author : Hao Chen
3 | // Date : 2014-06-18
4 |
5 | /**********************************************************************************
6 | *
7 | * You are given two linked lists representing two non-negative numbers.
8 | * The digits are stored in reverse order and each of their nodes contain a single digit.
9 | * Add the two numbers and return it as a linked list.
10 | *
11 | * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
12 | * Output: 7 -> 0 -> 8
13 | *
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 |
26 | public:
27 | ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
28 | int x=0, y=0, carry=0, sum=0;
29 | ListNode *h=NULL, **t=&h;
30 |
31 | while (l1!=NULL || l2!=NULL){
32 | x = getValueAndMoveNext(l1);
33 | y = getValueAndMoveNext(l2);
34 |
35 | sum = carry + x + y;
36 |
37 | ListNode *node = new ListNode(sum%10);
38 | *t = node;
39 | t = (&node->next);
40 |
41 | carry = sum/10;
42 | }
43 |
44 | if (carry > 0) {
45 | ListNode *node = new ListNode(carry%10);
46 | *t = node;
47 | }
48 |
49 | return h;
50 | }
51 | private:
52 | int getValueAndMoveNext(ListNode* &l){
53 | int x = 0;
54 | if (l != NULL){
55 | x = l->val;
56 | l = l->next;
57 | }
58 | return x;
59 | }
60 | };
61 |
--------------------------------------------------------------------------------
/algorithms/cpp/removeDuplicatesFromSortedList/removeDuplicatesFromSortedList.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list/
2 | // Author : Hao Chen
3 | // Date : 2014-06-21
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 |
16 | #include
17 |
18 | struct ListNode {
19 | int val;
20 | ListNode *next;
21 | ListNode(int x) : val(x), next(NULL) {}
22 | };
23 |
24 | ListNode *deleteDuplicates(ListNode *head) {
25 |
26 | for(ListNode *p=head; p && p->next; ){
27 | if (p->val == p->next->val){
28 | p->next = p->next->next;
29 | continue;
30 | }
31 | p=p->next;
32 | }
33 | return head;
34 | }
35 |
36 | void printList(ListNode* h)
37 | {
38 | while(h!=NULL){
39 | printf("%d ", h->val);
40 | h = h->next;
41 | }
42 | printf("\n");
43 | }
44 |
45 | ListNode* createList(int a[], int n)
46 | {
47 | ListNode *head=NULL, *p=NULL;
48 | for(int i=0; inext = new ListNode(a[i]);
53 | p = p->next;
54 | }
55 | }
56 | return head;
57 | }
58 |
59 |
60 | int main()
61 | {
62 | int a[]={1,1,2,3,3};
63 | int b[]={1,1,1};
64 |
65 | printList(deleteDuplicates(createList(a, sizeof(a)/sizeof(int))));
66 | printList(deleteDuplicates(createList(b, sizeof(b)/sizeof(int))));
67 | return 0;
68 | }
69 |
70 |
--------------------------------------------------------------------------------
/algorithms/cpp/uniqueBinarySearchTrees/uniqueBinarySearchTrees.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/unique-binary-search-trees/
2 | // Author : Hao Chen
3 | // Date : 2014-06-25
4 |
5 | /**********************************************************************************
6 | *
7 | * Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
8 | *
9 | * For example,
10 | * Given n = 3, there are a total of 5 unique BST's.
11 | *
12 | * 1 3 3 2 1
13 | * \ / / / \ \
14 | * 3 2 1 1 3 2
15 | *
16 | *
17 | **********************************************************************************/
18 |
19 | #include
20 | #include
21 | #include
22 |
23 | int numTrees1(int n) ;
24 | int numTrees2(int n) ;
25 |
26 | int numTrees(int n) {
27 | return numTrees1(n);
28 | }
29 |
30 | int numTrees1(int n) {
31 | int *cnt = (int*)malloc((n+1)*sizeof(int));
32 | memset(cnt, 0, (n+1)*sizeof(int));
33 | cnt[0] = 1;
34 | cnt[1] = 1;
35 |
36 | for (int i=2; i<=n; i++){
37 | for(int j=0; j1){
67 | n = atoi(argv[1]);
68 | }
69 | printf("%d=%d\n", n, numTrees(n));
70 | return 0;
71 | }
72 |
--------------------------------------------------------------------------------
/algorithms/cpp/bestTimeToBuyAndSellStock/bestTimeToBuyAndSellStock.II.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
2 | // Author : Hao Chen
3 | // Date : 2014-06-18
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
10 | * as you like (ie, buy one and sell one share of the stock multiple times). However,
11 | * you may not engage in multiple transactions at the same time (ie, you must sell the
12 | * stock before you buy again).
13 | *
14 | **********************************************************************************/
15 |
16 | class Solution {
17 | public:
18 | //
19 | // find all of ranges: which start a valley with the nearest peak after
20 | // add their delta together
21 | //
22 | int maxProfit(vector &prices) {
23 | int max=0, begin=0, end=0;
24 | bool up=false, down=false;
25 | for (int i=1; i prices[i-1] && up==false){ // goes up
27 | begin = i-1;
28 | up = true;
29 | down = false;
30 | }
31 |
32 | if (prices[i] < prices[i-1] && down==false) { // goes down
33 | end = i-1;
34 | down = true;
35 | up = false;
36 | max += (prices[end] - prices[begin]);
37 | }
38 | }
39 | // edge case
40 | if (begin < prices.size() && up==true){
41 | end = prices.size() - 1;
42 | max += (prices[end] - prices[begin]);
43 | }
44 |
45 | return max;
46 | }
47 | };
48 |
--------------------------------------------------------------------------------
/algorithms/cpp/excelSheetColumnTitle/excelSheetColumnTitle.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/excel-sheet-column-title/
2 | // Author : Hao Chen
3 | // Date : 2014-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 | * Credits:Special thanks to @ifanchu for adding this problem and creating all test cases.
20 | *
21 | **********************************************************************************/
22 |
23 | #include
24 | #include
25 | #include
26 | #include
27 | using namespace std;
28 |
29 |
30 | string base26_int2str(long long n) {
31 | string ret;
32 | while(n>0){
33 | char ch = 'A' + (n-1)%26;
34 | ret.insert(ret.begin(), ch );
35 | n -= (n-1)%26;
36 | n /= 26;
37 | }
38 | return ret;
39 | }
40 |
41 | long long base26_str2int(string& s){
42 | long long ret=0;
43 | for (int i=0; i1){
59 | n = atoll(argv[1]);
60 | }
61 | string ns = base26_int2str(n);
62 | n = base26_str2int(ns);
63 |
64 | cout << n << " = " << ns << endl;
65 |
66 |
67 | ns = "ABCDEFG";
68 | if (argc>2){
69 | ns = argv[2];
70 | }
71 | cout << ns << " = " << base26_str2int(ns) << endl;
72 | }
73 |
--------------------------------------------------------------------------------
/algorithms/cpp/minimumSizeSubarraySum/MinimumSizeSubarraySum.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://leetcode.com/problems/minimum-size-subarray-sum/
2 | // Author : Hao Chen
3 | // Date : 2015-06-09
4 |
5 | /**********************************************************************************
6 | *
7 | * Given an array of n positive integers and a positive integer s, find the minimal length of a subarray
8 | * of which the sum ≥ s. If there isn't one, return 0 instead.
9 | *
10 | * For example, given the array [2,3,1,2,4,3] and s = 7,
11 | * the subarray [4,3] has the minimal length under the problem constraint.
12 | *
13 | * click to show more practice.
14 | *
15 | * More practice:
16 | *
17 | * If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
18 | *
19 | * Credits:Special thanks to @Freezen for adding this problem and creating all test cases.
20 | *
21 | **********************************************************************************/
22 |
23 |
24 | class Solution {
25 | public:
26 | int minSubArrayLen(int s, vector& nums) {
27 | int min = nums.size();
28 | int begin=0, end=0;
29 | int sum = 0;
30 | bool has = false;
31 |
32 | for (int i=0; i= s && begin <= end) {
37 | //the 1 is minial length, just return
38 | if (begin == end) return 1;
39 |
40 | if (end-begin+1 < min) {
41 | min = end - begin + 1;
42 | has = true;
43 | }
44 | //move the begin
45 | sum -= nums[begin++];
46 | }
47 |
48 | }
49 |
50 | return has ? min : 0;
51 | }
52 | };
53 |
--------------------------------------------------------------------------------
/algorithms/cpp/longestValidParentheses/longestValidParentheses.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/longest-valid-parentheses/
2 | // Author : Hao Chen
3 | // Date : 2014-07-18
4 |
5 | /**********************************************************************************
6 | *
7 | * Given a string containing just the characters '(' and ')',
8 | * find the length of the longest valid (well-formed) parentheses substring.
9 | *
10 | * For "(()", the longest valid parentheses substring is "()", which has length = 2.
11 | *
12 | * Another example is ")()())", where the longest valid parentheses substring is "()()",
13 | * which has length = 4.
14 | *
15 | *
16 | **********************************************************************************/
17 |
18 | #include
19 | #include
20 | #include
21 | using namespace std;
22 |
23 | int longestValidParentheses(string s) {
24 | int maxLen = 0;
25 | int lastError = -1;
26 | vector stack;
27 | for(int i=0; i0 ){
32 | stack.pop_back();
33 | int len;
34 | if (stack.size()==0){
35 | len = i - lastError;
36 | } else {
37 | len = i - stack.back();
38 | }
39 | if (len > maxLen) {
40 | maxLen = len;
41 | }
42 | }else{
43 | lastError = i;
44 | }
45 | }
46 | }
47 | return maxLen;
48 | }
49 |
50 |
51 | int main(int argc, char** argv)
52 | {
53 | string s = ")()())";
54 | if (argc>1){
55 | s = argv[1];
56 | }
57 | cout << s << " : " << longestValidParentheses(s) << endl;
58 | return 0;
59 | }
60 |
--------------------------------------------------------------------------------
/algorithms/cpp/excelSheetColumnNumber/excelSheetColumnNumber.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/excel-sheet-column-number/
2 | // Author : Hao Chen
3 | // Date : 2014-12-29
4 |
5 | /**********************************************************************************
6 | *
7 | * Related to question Excel Sheet Column Title
8 | * Given a column title as appear in an Excel sheet, return its corresponding column number.
9 | *
10 | * For example:
11 | * A -> 1
12 | * B -> 2
13 | * C -> 3
14 | * ...
15 | * Z -> 26
16 | * AA -> 27
17 | * AB -> 28
18 | *
19 | * Credits:Special thanks to @ts for adding this problem and creating all test cases.
20 | *
21 | **********************************************************************************/
22 |
23 |
24 | #include
25 | #include
26 | #include
27 | #include
28 | using namespace std;
29 |
30 |
31 | string base26_int2str(long long n) {
32 | string ret;
33 | while(n>0){
34 | char ch = 'A' + (n-1)%26;
35 | ret.insert(ret.begin(), ch );
36 | n -= (n-1)%26;
37 | n /= 26;
38 | }
39 | return ret;
40 | }
41 |
42 | long long base26_str2int(string& s){
43 | long long ret=0;
44 | for (int i=0; i1){
60 | n = atoll(argv[1]);
61 | }
62 | string ns = base26_int2str(n);
63 | n = base26_str2int(ns);
64 |
65 | cout << n << " = " << ns << endl;
66 |
67 |
68 | ns = "ABCDEFG";
69 | if (argc>2){
70 | ns = argv[2];
71 | }
72 | cout << ns << " = " << base26_str2int(ns) << endl;
73 | }
74 |
--------------------------------------------------------------------------------
/algorithms/cpp/findTheDuplicateNumber/findTheDuplicateNumber.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://leetcode.com/problems/find-the-duplicate-number/
2 | // Author : Hao Chen, Calinescu Valentin
3 | // Date : 2015-10-19
4 |
5 | /***************************************************************************************
6 | *
7 | * Given an array nums containing n + 1 integers where each integer is between 1 and
8 | * n (inclusive), prove that at least one duplicate number must exist.
9 | * Assume that there is only one duplicate number, find the duplicate one.
10 | *
11 | * Note:
12 | * > You must not modify the array (assume the array is read only).
13 | * > You must use only constant, O(1) extra space.
14 | * > Your runtime complexity should be less than O(n2).
15 | * > There is only one duplicate number in the array, but it could be repeated more than
16 | * once.
17 | *
18 | * Credits:
19 | * Special thanks to @jianchao.li.fighter for adding this problem and creating all test
20 | * cases.
21 | *
22 | ***************************************************************************************/
23 |
24 |
25 | class Solution {
26 | public:
27 | //
28 | // This problem can be transfromed to "Linked List Cycle" problem.
29 | // There are two pointers, one goes one step, another goes two steps.
30 | //
31 | // Refer to: https://en.wikipedia.org/wiki/Cycle_detection
32 | //
33 | int findDuplicate(vector& nums) {
34 | int n = nums.size();
35 | int one = n;
36 | int two = n;
37 |
38 | do{
39 | one = nums[one-1];
40 | two = nums[nums[two-1]-1];
41 | } while(one != two);
42 |
43 | //find the start point of the cycle
44 | one = n;
45 | while(one != two){
46 | one = nums[one-1];
47 | two = nums[two-1];
48 | }
49 |
50 | return one;
51 | }
52 | };
53 |
--------------------------------------------------------------------------------
/algorithms/cpp/romanToInteger/romanToInteger.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/roman-to-integer/
2 | // Author : Hao Chen
3 | // Date : 2014-07-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 | #include
14 | #include
15 | using namespace std;
16 |
17 | int romanCharToInt(char ch){
18 | int d = 0;
19 | switch(ch){
20 | case 'I':
21 | d = 1;
22 | break;
23 | case 'V':
24 | d = 5;
25 | break;
26 | case 'X':
27 | d = 10;
28 | break;
29 | case 'L':
30 | d = 50;
31 | break;
32 | case 'C':
33 | d = 100;
34 | break;
35 | case 'D':
36 | d = 500;
37 | break;
38 | case 'M':
39 | d = 1000;
40 | break;
41 | }
42 | return d;
43 | }
44 | int romanToInt(string s) {
45 | if (s.size()<=0) return 0;
46 | int result = romanCharToInt(s[0]);
47 | for (int i=1; i1){
64 | s = argv[1];
65 | }
66 | cout << s << " : " << romanToInt(s) << endl;
67 | return 0;
68 | }
69 |
--------------------------------------------------------------------------------
/algorithms/cpp/summaryRanges/SummaryRanges.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://leetcode.com/problems/summary-ranges/
2 | // Author : Hao Chen
3 | // Date : 2015-07-03
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 | * Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
12 | *
13 | **********************************************************************************/
14 |
15 |
16 | class Solution {
17 | public:
18 | string makeRange(int start, int end) {
19 | ostringstream oss;
20 | if (start != end) {
21 | oss << start << "->" << end;
22 | } else {
23 | oss << start;
24 | }
25 | return oss.str();
26 | }
27 |
28 | vector summaryRanges(vector& nums) {
29 | vector result;
30 | int len = nums.size();
31 | if (len == 0) return result;
32 |
33 | // we have two pointer for range-starter and range-ender
34 | int start=nums[0], end=nums[0];
35 |
36 | for (int i=1; i 0, then move the "end" pointer to next
22 | // 3) if prices[end] - prices[begin] <= 0, then move the "begin" pointer to current posstion.
23 | // 4) tracking the max profit
24 | //
25 | // Notes:
26 | // Some people think find the highest-price & lowest-price, this is wrong.
27 | // Because the highest-price must be after lowest-price
28 | //
29 | int maxProfit(vector &prices) {
30 |
31 | int max=0, begin=0, end=0, delta=0;
32 |
33 | for (int i=0; i max ){
44 | max = delta;
45 | }
46 |
47 | }
48 |
49 | return max;
50 |
51 | }
52 | };
53 |
--------------------------------------------------------------------------------
/algorithms/cpp/sumRootToLeafNumber/sumRootToLeafNumber.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://oj.leetcode.com/problems/sum-root-to-leaf-numbers/
2 | // Author : Hao Chen
3 | // Date : 2014-06-21
4 |
5 | /**********************************************************************************
6 | *
7 | * Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
8 | * An example is the root-to-leaf path 1->2->3 which represents the number 123.
9 | *
10 | * Find the total sum of all root-to-leaf numbers.
11 | *
12 | * For example,
13 | *
14 | * 1
15 | * / \
16 | * 2 3
17 | *
18 | * The root-to-leaf path 1->2 represents the number 12.
19 | * The root-to-leaf path 1->3 represents the number 13.
20 | *
21 | * Return the sum = 12 + 13 = 25.
22 | *
23 | *
24 | **********************************************************************************/
25 |
26 | /**
27 | * Definition for binary tree
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 | int sumNumbers(TreeNode *root) {
38 |
39 | if (!root) return 0;
40 |
41 | int sum = 0;
42 | vector v;
43 | v.push_back(root);
44 | while(v.size()>0){
45 | TreeNode* node = v.back();
46 | v.pop_back();
47 | if (node->left){
48 | node->left->val += (10*node->val);
49 | v.push_back(node->left);
50 | }
51 | if (node->right){
52 | node->right->val += (10*node->val);
53 | v.push_back(node->right);
54 | }
55 | if(!node->right && !node->left){
56 | sum += node->val;
57 | }
58 | }
59 |
60 | return sum;
61 | }
62 | };
63 |
--------------------------------------------------------------------------------
/algorithms/java/src/inorderSuccessorInBST/inorderSuccessorInBST.java:
--------------------------------------------------------------------------------
1 | // Source : http://www.lintcode.com/en/problem/inorder-successor-in-bst/
2 | // https://leetcode.com/problems/inorder-successor-in-bst/
3 | // Inspired by : http://www.jiuzhang.com/solutions/inorder-successor-in-bst/
4 | // Author : Lei Cao
5 | // Date : 2015-10-06
6 |
7 | /**********************************************************************************
8 | *
9 | * Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
10 | *
11 | * Example
12 | * Given tree = [2,1] and node = 1:
13 | *
14 | * 2
15 | * /
16 | * 1
17 | * return node 2.
18 | *
19 | * Given tree = [2,1,3] and node = 2:
20 | *
21 | * 2
22 | * / \
23 | * 1 3
24 | *
25 | * return node 3.
26 | *
27 | * Note
28 | * If the given node has no in-order successor in the tree, return null.
29 | *
30 | * Challenge
31 | * O(h), where h is the height of the BST.
32 | **********************************************************************************/
33 |
34 | package inorderSuccessorInBST;
35 |
36 | public class inorderSuccessorInBST {
37 | public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
38 | TreeNode successor = null;
39 | if (root == null) {
40 | return null;
41 | }
42 | while (root != null && root.val != p.val) {
43 | if (root.val > p.val) {
44 | successor = root;
45 | root = root.left;
46 | } else {
47 | root = root.right;
48 | }
49 | }
50 |
51 | if (root == null) {
52 | return null;
53 | }
54 |
55 | if (root.right == null) {
56 | return successor;
57 | }
58 |
59 | root = root.right;
60 | while (root.left != null) {
61 | root = root.left;
62 | }
63 | return root;
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/algorithms/java/src/searchRangeInBinarySearchTree/searchRangeInBinarySearchTree.java:
--------------------------------------------------------------------------------
1 | // Source : http://www.lintcode.com/en/problem/search-range-in-binary-search-tree/
2 | // Inspired by : http://www.jiuzhang.com/solutions/search-range-in-binary-search-tree/
3 | // Author : Lei Cao
4 | // Date : 2015-10-09
5 |
6 | /**********************************************************************************
7 | *
8 | * Search Range in Binary Search Tree
9 | *
10 | * Given two values k1 and k2 (where k1 < k2) and a root pointer to a Binary Search Tree.
11 | * Find all the keys of tree in range k1 to k2.
12 | * i.e. print all x such that k1<=x<=k2 and x is a key of given BST.
13 | * Return all the keys in ascending order.
14 | *
15 | * Example:
16 | *
17 | * If k1 = 10 and k2 = 22, then your function should return [12, 20, 22].
18 | *
19 | * 20
20 | * / \
21 | * 8 22
22 | * / \
23 | * 4 12
24 | *
25 | *
26 | **********************************************************************************/
27 |
28 | package searchRangeInBinarySearchTree;
29 |
30 | import java.util.ArrayList;
31 |
32 | public class searchRangeInBinarySearchTree {
33 | /**
34 | * @param root: The root of the binary search tree.
35 | * @param k1 and k2: range k1 to k2.
36 | * @return: Return all keys that k1<=key<=k2 in ascending order.
37 | */
38 | public ArrayList searchRange(TreeNode root, int k1, int k2) {
39 | ArrayList result = new ArrayList();
40 | if (root == null) {
41 | return result;
42 | }
43 |
44 | ArrayList left = searchRange(root.left, k1, k2);
45 | ArrayList right = searchRange(root.right, k1, k2);
46 |
47 | result.addAll(left);
48 | if (root.val >= k1 && root.val <= k2) {
49 | result.add(root.val);
50 | }
51 | result.addAll(right);
52 | return result;
53 | }
54 |
55 | }
56 |
--------------------------------------------------------------------------------
/algorithms/cpp/happyNumber/HappyNumber.cpp:
--------------------------------------------------------------------------------
1 | // Source : https://leetcode.com/problems/happy-number/
2 | // Author : Hao Chen
3 | // Date : 2015-06-08
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,
10 | * replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1
11 | * (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this
12 | * process ends in 1 are happy numbers.
13 | *
14 | * Example: 19 is a happy number
15 | *
16 | * 1^2 + 9^2 = 82
17 | * 8^2 + 2^2 = 68
18 | * 6^2 + 8^2 = 100
19 | * 1^2 + 0^2 + 0^2 = 1
20 | *
21 | * Credits:Special thanks to @mithmatt and @ts for adding this problem and creating all test cases.
22 | *
23 | **********************************************************************************/
24 | #include
25 | #include
26 | #include