├── README.md ├── codility ├── C&C++ │ ├── TODO │ ├── lesson-1 │ │ ├── FrogJmp.c │ │ ├── PermMissingElem.c │ │ ├── README │ │ └── TapeEquilibrium.c │ ├── lesson-10 │ │ ├── ChocolatesByNumbers.c │ │ ├── CommonPrimeDicisors.c │ │ └── README │ ├── lesson-11 │ │ ├── FibFrog.c │ │ ├── Ladder.c │ │ └── README │ ├── lesson-12 │ │ ├── MinMaxDivision.c │ │ ├── NailingPlanks.c │ │ └── README │ ├── lesson-13 │ │ ├── AbsDistinct.c │ │ ├── CountDistinctSlices.c │ │ ├── CountTriangles.c │ │ ├── MinAbsSumOfTwo.c │ │ └── README │ ├── lesson-14 │ │ ├── README │ │ └── TieRopes.c │ ├── lesson-2 │ │ ├── FrogRiverOne.c │ │ ├── MaxCounters.c │ │ ├── MissingInteger.c │ │ ├── PermCheck.c │ │ └── README │ ├── lesson-3 │ │ ├── CountDiv.c │ │ ├── GenomicRangeQuery.c │ │ ├── MinAvgTwoSlice.c │ │ ├── PassingCars.c │ │ └── README │ ├── lesson-4 │ │ ├── Distinct.c │ │ ├── MaxProductOfThree.c │ │ ├── NumberOfDiscIntersections.cpp │ │ ├── README │ │ └── Triangle.c │ ├── lesson-5 │ │ ├── Brackets.c │ │ ├── Fish.c │ │ ├── Nesting.c │ │ ├── README │ │ └── StoneWall.c │ ├── lesson-6 │ │ ├── Dominator.c │ │ ├── EquiLeader.c │ │ └── README │ ├── lesson-7 │ │ ├── MaxDoubleSliceSum.c │ │ ├── MaxProfit.c │ │ ├── MaxSliceSum.c │ │ └── README │ ├── lesson-8 │ │ ├── CountFactors.c │ │ ├── Flags.c │ │ ├── MinPerimeterRectangle.c │ │ ├── Peaks.c │ │ └── README │ ├── lesson-9 │ │ ├── CountNonDivisible.c │ │ ├── CountSemiprimes.c │ │ └── README │ └── others │ │ ├── ArrayInversionCount.c │ │ ├── BinaryGap.c │ │ ├── StrSymmetryPoint.c │ │ └── TreeHeight.cpp └── README └── leetcode ├── C&C++ ├── easy │ ├── BestTimetoBuyandSellStock.cpp │ ├── BestTimetoBuyandSellStockII.cpp │ ├── BinaryTreeInorderTraversal.cpp │ ├── BinaryTreePreorderTraversal.cpp │ ├── ClimbingStairs.cpp │ ├── Combinations.cpp │ ├── ContainerWithMostWater.cpp │ ├── ConvertSortedArraytoBinarySearchTree.cpp │ ├── CountandSay.cpp │ ├── GenerateParentheses.cpp │ ├── GrayCode.cpp │ ├── JumpGame.cpp │ ├── LengthofLastWord.cpp │ ├── LinkedListCycle.cpp │ ├── MaximumDepthofBinaryTree.cpp │ ├── MaximumSubarray.cpp │ ├── MergeSortedArray.cpp │ ├── MergeTwoSortedLists.cpp │ ├── MinimumDepthofBinaryTree.cpp │ ├── MinimumPathSum.cpp │ ├── PalindromeNumber.cpp │ ├── PascalsTriangle.cpp │ ├── PathSum.cpp │ ├── PlusOne.cpp │ ├── PopulatingNextRightPointersinEachNode.c │ ├── README │ ├── RemoveDuplicatesfromSortedArray.cpp │ ├── RemoveDuplicatesfromSortedArrayII.cpp │ ├── RemoveDuplicatesfromSortedList.cpp │ ├── RemoveElement.cpp │ ├── RemoveNthNodeFromEndofList.cpp │ ├── ReverseInteger.cpp │ ├── RomaintoInteger.cpp │ ├── RotateImage.cpp │ ├── SameTree.cpp │ ├── SearchInsertPosition.cpp │ ├── Searcha2DMatrix.cpp │ ├── SearchforaRange.cpp │ ├── SetMatrixZeroes.cpp │ ├── SingleNumber.cpp │ ├── SingleNumberII.cpp │ ├── SortColors.cpp │ ├── SumRoottoLeafNumbers.cpp │ ├── SwapNodesinPairs.cpp │ ├── SymmetricTree.cpp │ ├── UniqueBinarySearchTrees.cpp │ ├── UniquePaths.cpp │ └── ValidParentheses.cpp ├── hard │ ├── 3Sum.cpp │ ├── BinaryTreeMaximumPathSum.cpp │ ├── Candy.cpp │ ├── DivideTwoIntegers.cpp │ ├── InterleavingString.cpp │ ├── LongestPalindromicSubstring.cpp │ ├── LongestValidParentheses.cpp │ ├── MaxPointsonaLine.cpp │ ├── MedianofTwoSortedArrays.cpp │ ├── PalindromePartitioningII.cpp │ ├── README │ ├── RegularExpressionMatching.cpp │ ├── SimplifyPath.cpp │ ├── WildcardMatching.cpp │ ├── WordBreakII.cpp │ ├── WordLadder.cpp │ └── WordLadderII.cpp └── medium │ ├── 3SumClosest.cpp │ ├── 4Sum.cpp │ ├── AddBinary.cpp │ ├── AddTwoNumbers.cpp │ ├── Anagrams.cpp │ ├── BestTimetoBuyandSellStockIII.cpp │ ├── BinaryTreeLevelOrderTraversal.cpp │ ├── BinaryTreeLevelOrderTraversalII.cpp │ ├── BinaryTreeZigzagLevelOrderTraversal.cpp │ ├── CloneGraph.cpp │ ├── CombinationSum.cpp │ ├── CombinationSumII.cpp │ ├── ConstructBinaryTreefromInorderandPostorderTraversal.cpp │ ├── ConstructBinaryTreefromPreorderandInorderTraversal.cpp │ ├── ConvertSortedListtoBinarySearchTree.cpp │ ├── CopyListwithRandomPointer.cpp │ ├── DistinctSubsequences.cpp │ ├── EditDistance.cpp │ ├── FirstMissingPositive.cpp │ ├── FlattenBinaryTreetoLinkedList.cpp │ ├── GasStation.cpp │ ├── InsertInterval.cpp │ ├── InsertionSortList.cpp │ ├── JumpGameII.cpp │ ├── LargestRectangleinHistogram.cpp │ ├── LetterCombinationsofaPhoneNumber.cpp │ ├── LinkedListCycleII.cpp │ ├── LongestCommonPrefix.cpp │ ├── LongestConsecutiveSequence.cpp │ ├── LongestSubstringWithoutRepeatingCharacters.cpp │ ├── MaximalRectangle.cpp │ ├── MergeIntervals.cpp │ ├── MergekSortedLists.cpp │ ├── MultiplyStrings.cpp │ ├── N-Queens.cpp │ ├── N-QueensII.cpp │ ├── NextPermutation.cpp │ ├── PalindromePartitioning.cpp │ ├── PartitionList.cpp │ ├── PascalsTriangleII.cpp │ ├── PathSumII.cpp │ ├── PermutationSequence.cpp │ ├── Permutations.cpp │ ├── PermutationsII.cpp │ ├── PopulatingNextRightPointersinEachNodeII.cpp │ ├── README │ ├── RecoverBinarySearchTree.cpp │ ├── RemoveDuplicatesfromSortedListII.cpp │ ├── ReorderList.cpp │ ├── RestoreIPAddresses.cpp │ ├── ReverseLinkedListII.cpp │ ├── ReverseNodesink-Group.cpp │ ├── RotateList.cpp │ ├── ScrambleString.cpp │ ├── SearchinRotatedSortedArray.cpp │ ├── SearchinRotatedSortedArrayII.cpp │ ├── SortList.cpp │ ├── SpiralMatrix.cpp │ ├── SpiralMatrixII.cpp │ ├── Sqrt(x).cpp │ ├── Subsets.cpp │ ├── SubsetsII.cpp │ ├── SudokuSolver.cpp │ ├── TrappingRainWater.cpp │ ├── Triangle.cpp │ ├── TwoSum.cpp │ ├── UniqueBinarySearchTreesII.cpp │ ├── UniquePathsII.cpp │ ├── ValidPalindrome.cpp │ ├── ValidSudoku.cpp │ ├── ValidataBinarySearchTree.cpp │ ├── WordBreak.cpp │ └── ZigZagConversion.cpp └── README /README.md: -------------------------------------------------------------------------------- 1 | Coding 2 | ====== 3 | 4 | To improve my coding skills, I did a little practice in a few websites (codility, leetcode, ...). The main reason for creating this repo is that I want to record all the "mind workings" in this process. 5 | 6 | 7 | ###How to contribute 8 | It would be great if anyone can join me, so feel free to make your pull requests to this repository. 9 | ######What you need to do is quite simple, such as: 10 | 11 | 1. fork this repository to your own github; 12 | 2. clone your forked repository to local; 13 | #git clone the-name-of-your-forked-repository 14 | 3. add upstream for your local repository 15 | #git remote add upstream https://github.com/PerthCharles/Coding.git 16 | 4. get the newest version of this repository 17 | #git pull upstream master 18 | 5. add new branch for your changes/codes/anything 19 | #git checkout -b your-branch 20 | 6. do whatever you want to: 21 | a. fix bugs 22 | b. add new website to pratice coding 23 | c. use new language to solve problems 24 | d. any advices 25 | 7. get the newest version of this repository 26 | #git checkout master 27 | #git pull upstream master 28 | #git checkout your-branch 29 | #git rebase master 30 | 8. commit your changes 31 | #git add ... 32 | #git commit ... 33 | #git push origin your-branch 34 | 9. go to the github.com to make your pull request 35 | -------------------------------------------------------------------------------- /codility/C&C++/TODO: -------------------------------------------------------------------------------- 1 | Lesson 12: NailingPlanks 2 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-1/FrogJmp.c: -------------------------------------------------------------------------------- 1 | /* 2 | * FrogJmp 3 | * Count minimal number of jumps from position X to Y. 4 | */ 5 | 6 | int solution(int X, int Y, int D) 7 | { 8 | // write your code in C90 9 | int steps = 0; 10 | steps = (Y - X)/D; // look out '/' in C 11 | if ((Y - X)%D != 0) { 12 | steps++; 13 | } 14 | return steps 15 | } 16 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-1/PermMissingElem.c: -------------------------------------------------------------------------------- 1 | /* 2 | * PermMissingElem 3 | * Find the missing element in a given permutation. 4 | */ 5 | 6 | int solution(int A[], int N) 7 | { 8 | // write your code in C90 9 | // This method can avoid overflow of 'int' 10 | int miss = 0, i; 11 | 12 | for (i = 0; i < N; i++) { 13 | miss += (i+1) - A[i]; 14 | } 15 | miss += N + 1; 16 | 17 | return miss; 18 | } 19 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-1/README: -------------------------------------------------------------------------------- 1 | Time Complexity 2 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-1/TapeEquilibrium.c: -------------------------------------------------------------------------------- 1 | /* 2 | * TapeEquilibrium 3 | * Minimize the value |(A[0] + ... + A[P-1]) - (A[P] + ... + A[N-1])|. 4 | */ 5 | 6 | #define ABS(a) (((a) >= 0) ? (a) : (-(a))) 7 | #define MIN(a, b) (((a) <= (b)) ? (a) : (b)) 8 | 9 | int solution(int A[], int N) 10 | { 11 | // write your code in C90 12 | int diff, min_diff = 0; 13 | int split, sum = 0, l_sum = 0, r_sum, i; 14 | 15 | // get the sum of A[] 16 | for (i = 0; i < N; i++) { 17 | sum += A[i]; 18 | } 19 | 20 | // find min_diff fot these two pieces: 21 | // [0, split] and [split+1, N) 22 | for (split = 0; split < N-1; split++) { 23 | l_sum += A[split]; // left sum 24 | r_sum = sum - l_sum; 25 | diff = ABS(r_sum - l_sum); 26 | 27 | if (split == 0) { 28 | min_diff = diff; 29 | } else { 30 | min_diff = MIN(min_diff, diff); 31 | } 32 | } 33 | 34 | return min_diff; 35 | } 36 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-10/ChocolatesByNumbers.c: -------------------------------------------------------------------------------- 1 | /* 2 | * ChocolatesByNumbers 3 | * There are N chocolates in a circle. Count the number of chocolates you will eat. 4 | */ 5 | 6 | int solution(int N, int M) 7 | { 8 | in gcd = 1, result = 0, a = N, b = M; 9 | 10 | while (a != b) { 11 | if (a % 2 == 0 && b % 2 == 0) { 12 | gcd *= 2; 13 | a /= 2; 14 | b /= 2; 15 | } else if (a % 2 == 0) { 16 | a /= 2; 17 | } else if (b % 2 == 0) { 18 | b /= 2; 19 | } else if (a > b) { 20 | a = a - b; 21 | } else { 22 | b = b - a; 23 | } 24 | } 25 | gcd *= a; 26 | result = N/gcd; 27 | 28 | return result; 29 | } 30 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-10/CommonPrimeDicisors.c: -------------------------------------------------------------------------------- 1 | /* 2 | * CommonPrimeDivisors 3 | * Check whether two numbers have the same prime divisors. 4 | */ 5 | 6 | 7 | int gcd(int a, int b) 8 | { 9 | int gcd = 1; 10 | while (a != b) { 11 | if (a % 2 == 0 && b % 2 == 0) { 12 | a /= 2; 13 | b /= 2; 14 | gcd *= 2; 15 | } else if (a % 2 == 0) { 16 | a /= 2; 17 | } else if (b % 2 == 0) { 18 | b /= 2; 19 | } else if (a > b) { 20 | a = a-b; 21 | } else { 22 | b = b-a; 23 | } 24 | } 25 | gcd *= a; 26 | 27 | return gcd; 28 | } 29 | 30 | int solution(int A[], int B[], int Z) { 31 | // write your code in C90 32 | int result = 0; 33 | int a, b, gcd_ab, gcd_a, gcd_b, i; 34 | 35 | for (i = 0; i < Z; i++) { 36 | gcd_ab = gcd(A[i], B[i]); 37 | a = A[i]; 38 | b = B[i]; 39 | 40 | while (a != 1) { 41 | gcd_a = gcd(a, gcd_ab); 42 | if (gcd_a == 1) break; 43 | a /= gcd_a; 44 | } 45 | if (a != 1) continue; 46 | 47 | while (b != 1) { 48 | gcd_b = gcd(b, gcd_ab); 49 | if (gcd_b == 1) break; 50 | b /= gcd_b; 51 | } 52 | if (b != 1) continue; 53 | 54 | result++; 55 | } 56 | 57 | return result; 58 | } 59 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-10/README: -------------------------------------------------------------------------------- 1 | Euclidean algorithm 2 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-11/FibFrog.c: -------------------------------------------------------------------------------- 1 | /* 2 | * FibFrog 3 | * Count the minimum number of jumps required for a frog to get to the other side of a river. 4 | */ 5 | 6 | 7 | int min(int a, int b) 8 | { 9 | if (a >= b) return b; 10 | else return a; 11 | } 12 | 13 | int solution(int A[], int N) { 14 | // write your code in C90 15 | if (N <= 2) return 1; 16 | 17 | int i, j, k, result = -1; 18 | int *fibo, *cnt; 19 | fibo = (int *)malloc(sizeof(int)*50); 20 | cnt = (int *)malloc(sizeof(int)*N); 21 | memset(fibo, 0, sizeof(int)*50); 22 | memset(cnt, 0, sizeof(int)*N); 23 | fibo[1] = 1; 24 | 25 | i = 1; 26 | while(fibo[i++] <= N) { 27 | fibo[i] = fibo[i-1] + fibo[i-2]; 28 | } 29 | 30 | for (i = N-1; i >= 0; i--) { 31 | if (A[i] == 1) { 32 | k = 2; 33 | j = i + fibo[k++]; 34 | while(j < N) { 35 | if (A[j] == 1 && cnt[j] != 0) { 36 | if (cnt[i] == 0) cnt[i] = cnt[j] + 1; 37 | else cnt[i] = min(cnt[i], cnt[j] + 1); 38 | } 39 | j = i + fibo[k++]; 40 | } 41 | if (j == N) cnt[i] = 1; 42 | } 43 | } 44 | 45 | k = 2; 46 | j = -1 + fibo[k++]; 47 | while (j < N) { 48 | if (A[j] == 1 && cnt[j] != 0) { 49 | if (result == -1) result = cnt[j] + 1; 50 | else result = min(result, cnt[j] + 1); 51 | } 52 | j = -1 + fibo[k++]; 53 | } 54 | if (j == N) result = 1; 55 | 56 | return result > 0 ? result : -1; 57 | } 58 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-11/Ladder.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Ladder 3 | * Count the number of different ways of climbing to the top of a ladder. 4 | */ 5 | 6 | 7 | struct Results solution(int A[], int B[], int L) { 8 | struct Results result; 9 | int i; 10 | int *fibo; 11 | // write your code in C90 12 | result.C = (int *)malloc(sizeof(int)*L); 13 | memset(result.C, 0, sizeof(int)*L); 14 | 15 | if (L == 1) { 16 | result.C[0] = 1; 17 | result.L = 1; 18 | return result; 19 | } 20 | 21 | fibo = (int *)malloc(sizeof(int)*(L+1)); 22 | memset(fibo, 0, sizeof(int)*(L+1)); 23 | fibo[1] = 1; 24 | fibo[2] = 2; 25 | for (i = 3; i < L+1; i++) { 26 | // what if INT is not bigger enough for a fibonacci number? 27 | fibo[i] = fibo[i-1] + fibo[i-2]; 28 | } 29 | 30 | for (i = 0; i < L; i++) { 31 | result.C[i] = fibo[A[i]] & ((1 << B[i]) - 1); 32 | } 33 | 34 | 35 | result.L = L; 36 | return result; 37 | } 38 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-11/README: -------------------------------------------------------------------------------- 1 | Fibonacci numbers 2 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-12/MinMaxDivision.c: -------------------------------------------------------------------------------- 1 | /* 2 | * MinMaxDivision 3 | * Divide array A into K blocks and minimize the largest sum of any block. 4 | */ 5 | 6 | 7 | int compute_mgn(int A[], int N, int ems) 8 | { 9 | int cursum = 0; 10 | int mgn = 0; 11 | int i; 12 | 13 | for (i = 0; i < N; i++) { 14 | cursum += A[i]; 15 | if (cursum > ems) { 16 | mgn++; 17 | cursum = A[i]; 18 | } 19 | } 20 | if (cursum > 0) mgn++; 21 | 22 | return mgn; 23 | } 24 | 25 | 26 | int solution(int K, int M, int A[], int N) { 27 | // write your code in C90 28 | int ems; // expected minimum sum 29 | int mgn; // minimum group number 30 | int big = 0; // biggest in A[] 31 | int sum = 0; // sum of A[] 32 | int i, beg, end; 33 | 34 | for (i = 0; i < N; i++) { 35 | sum += A[i]; 36 | if (i == 0) big = A[i]; 37 | else if (A[i] > big) big = A[i]; 38 | } 39 | 40 | beg = big; 41 | end = sum; 42 | while (beg <= end) { 43 | ems = (beg + end)/2; 44 | mgn = compute_mgn(A, N, ems); 45 | if (mgn <= K) { 46 | end = ems - 1; 47 | } else { 48 | beg = ems + 1; 49 | } 50 | } 51 | 52 | return beg; 53 | } 54 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-12/NailingPlanks.c: -------------------------------------------------------------------------------- 1 | /* 2 | * NailingPlanks 3 | * Count the minimum number of nails that allow a series of planks to be nailed. 4 | */ 5 | 6 | TODO 7 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-12/README: -------------------------------------------------------------------------------- 1 | Binary search algorithm 2 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-13/AbsDistinct.c: -------------------------------------------------------------------------------- 1 | /* 2 | * AbsDistinct 3 | * Compute number of distinct absolute values of sorted array elements. 4 | */ 5 | 6 | 7 | // you can write to stdout for debugging purposes, e.g. 8 | // printf("this is a debug message\n"); 9 | int abs(int a) 10 | { 11 | return a >= 0 ? a : -a; 12 | } 13 | 14 | int solution(int A[], int N) { 15 | // write your code in C90 16 | int result = 0; 17 | int neg = -1, pos = N, begin = 0; 18 | int i; 19 | for (i = 0; i < N; i++) { 20 | if (A[i] == (1<< (sizeof(int)*8 - 1))) { 21 | begin++; 22 | } else if (A[i] < 0) { 23 | neg = i; 24 | } else if (A[i] > 0) { 25 | pos = i; 26 | break; 27 | } 28 | } 29 | if (begin != 0) result++; // A[0] = MIN_NEGTIVE_INT 30 | if (neg != pos - 1) result++; // A[x] == 0 31 | 32 | while (neg >= begin && pos < N) { 33 | if (abs(A[neg]) == A[pos]) { 34 | result++; 35 | neg--; 36 | while (neg >= begin && A[neg] == A[neg+1]) neg--; 37 | pos++; 38 | while (pos < N && A[pos] == A[pos-1]) pos++; 39 | } else if (abs(A[neg]) < A[pos]) { 40 | result++; 41 | neg--; 42 | while (neg >= begin && A[neg] == A[neg+1]) neg--; 43 | } else { 44 | result++; 45 | pos++; 46 | while (pos < N && A[pos] == A[pos-1]) pos++; 47 | } 48 | } 49 | 50 | while (neg >= begin) { 51 | if (A[neg] != A[neg+1]) { 52 | result++; 53 | } 54 | neg--; 55 | } 56 | while (pos < N) { 57 | if (A[pos] != A[pos-1]) { 58 | result++; 59 | } 60 | pos++; 61 | } 62 | 63 | return result; 64 | } -------------------------------------------------------------------------------- /codility/C&C++/lesson-13/CountDistinctSlices.c: -------------------------------------------------------------------------------- 1 | /* 2 | * CountDistinctSlices 3 | * Count the number of distinct slices (containing only unique numbers). 4 | */ 5 | 6 | 7 | // you can write to stdout for debugging purposes, e.g. 8 | // printf("this is a debug message\n"); 9 | 10 | int solution(int M, int A[], int N) { 11 | // write your code in C90 12 | int *hash = (int *)malloc(sizeof(int)*(M+1)); 13 | memset(hash, 0, sizeof(int)*(M+1)); 14 | int head, tail, result = 0; 15 | int unique = 1; // default unique is True 16 | 17 | for (head = 0, tail = 0; tail < N; tail++) { 18 | hash[A[tail]]++; 19 | if (hash[A[tail]] != 1) { 20 | unique = 0; 21 | while (head <= tail && (!unique)) { 22 | if (A[head] == A[tail]) { 23 | unique = 1; 24 | } 25 | hash[A[head]]--; // clear hash 26 | head++; 27 | } 28 | } 29 | result += tail - head + 1; 30 | if (result > 1000000000) return 1000000000; 31 | } 32 | 33 | return result; 34 | } -------------------------------------------------------------------------------- /codility/C&C++/lesson-13/CountTriangles.c: -------------------------------------------------------------------------------- 1 | /* 2 | * CountTriangles 3 | * Count the number of triangles that can be built from a given set of edges. 4 | */ 5 | 6 | 7 | void merge_sort(int A[], int N) 8 | { 9 | int *tmp, steps, mid, from, to, i, j, k; 10 | tmp = (int *)malloc(sizeof(int)*N); 11 | memset(tmp, 0, sizeof(int)*N); 12 | 13 | for (steps = 1; steps <= N; steps += steps) { 14 | for (from = 0; from < N; from += steps + steps) { 15 | mid = from + steps; 16 | if (mid > N) break;; 17 | to = from + steps + steps; 18 | if (to > N) to = N; 19 | 20 | for (i = k = from, j = mid; k < to; k++) { 21 | if (i == mid) tmp[k] = A[j++]; 22 | else if (j == to) tmp[k] = A[i++]; 23 | else if (A[i] <= A[j]) tmp[k] = A[i++]; 24 | else tmp[k] = A[j++]; 25 | } 26 | } 27 | 28 | for (i = 0; i < k; i++) { 29 | A[i] = tmp[i]; 30 | } 31 | } 32 | } 33 | 34 | int solution(int A[], int N) { 35 | if (N < 3) return 0; 36 | // write your code in C90 37 | int result = 0, i, j, k; 38 | //qsort(A, N, sizeof(int), compare); // qsort can cause timeout :( 39 | merge_sort(A, N); 40 | 41 | for (i = 0; i < N-2; i++) { 42 | for (j = i+1; j < N-1; j++) { 43 | k = j+1; // Lookout that this statement cannot be in the second loop 44 | while (k < N && A[i] + A[j] > A[k]) { 45 | k++; 46 | } 47 | result += (k-1) - j; 48 | } 49 | } 50 | 51 | return result; 52 | } 53 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-13/MinAbsSumOfTwo.c: -------------------------------------------------------------------------------- 1 | /* 2 | * MinAbsSumOfTwo 3 | * Find the minimal absolute value of a sum of two elements. 4 | */ 5 | 6 | 7 | // you can write to stdout for debugging purposes, e.g. 8 | // printf("this is a debug message\n"); 9 | 10 | #define MIN(a, b) (((a) <= (b)) ? (a) : (b)) 11 | #define ABS(a) (((a) >= 0) ? (a) : (-(a))) 12 | 13 | int compare(const void *a, const void *b) 14 | { 15 | return *(int *)a - *(int *)b; 16 | } 17 | 18 | int solution(int A[], int N) { 19 | // write your code in C90 20 | if (N < 2) return ABS(2*A[0]); 21 | 22 | int head, tail, min, tmp; 23 | qsort(A, N, sizeof(int), compare); 24 | if (A[0] >= 0) return ABS(2*A[0]); // A[i] >= 0 25 | if (A[N-1] <=0) return ABS(2*A[N-1]); // A[i] <= 0 26 | 27 | head = 0; 28 | tail = N - 1; 29 | min = ABS(A[head] + A[tail]); 30 | while (head <= tail) { 31 | tmp = A[head] + A[tail]; 32 | min = MIN(min, ABS(tmp)); 33 | if (tmp == 0) return 0; 34 | else if (tmp > 0) tail--; 35 | else head++; 36 | } 37 | 38 | return min; 39 | } 40 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-13/README: -------------------------------------------------------------------------------- 1 | Caterpillar method 2 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-14/README: -------------------------------------------------------------------------------- 1 | Greedy algorithms 2 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-14/TieRopes.c: -------------------------------------------------------------------------------- 1 | /* 2 | * TieRopes 3 | * Tie adjacent ropes to achieve the maximum number of ropes of length >= K. 4 | */ 5 | 6 | 7 | // you can write to stdout for debugging purposes, e.g. 8 | // printf("this is a debug message\n"); 9 | 10 | int solution(int K, int A[], int N) { 11 | // write your code in C90 12 | int result = 0; 13 | int i, tmp; 14 | 15 | tmp = 0; 16 | for (i = 0; i < N; i++) { 17 | tmp += A[i]; 18 | if (tmp >= K) { 19 | result++; 20 | tmp = 0; 21 | } 22 | } 23 | 24 | return result; 25 | } -------------------------------------------------------------------------------- /codility/C&C++/lesson-2/FrogRiverOne.c: -------------------------------------------------------------------------------- 1 | /* 2 | * FrogRiverOne 3 | * Find the earliest time when a frog can jump to the other side of a river. 4 | */ 5 | 6 | int solution(int X, int A[], int N) 7 | { 8 | // write your code in C90 9 | int *hash = (int *)malloc(sizeof(int)*(X+1)); 10 | int time, leaves = 0; 11 | memset(hash, 0, sizeof(int)*(X+1)); 12 | 13 | for (time = 0; time < N; time++) { 14 | if (hash[A[time]] == 0) { 15 | hash[A[time]]++; 16 | leaves++; // found a new leave 17 | } 18 | if (leaves == X) { 19 | return time; 20 | } 21 | } 22 | 23 | return -1; 24 | } 25 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-2/MaxCounters.c: -------------------------------------------------------------------------------- 1 | /* 2 | * MaxCounters 3 | * Calculate the values of counters after applying all alternating operations: increase counter by 1; set value of all counters to current maximum. 4 | */ 5 | 6 | struct Results solution(int N, int A[], int M) 7 | { 8 | // write your code in C90 9 | struct Results result; 10 | int i, counter, base = 0, max = 0; 11 | result.C = (int *)malloc(sizeof(int)*N); 12 | memset(result.C, 0, sizeof(int)*N); 13 | result.L = N; 14 | 15 | for (i = 0; i < M; i++) { 16 | if (A[i] > N) { 17 | base = max; 18 | } else { 19 | counter = A[i] - 1; 20 | if (result.C[counter] >= base) { 21 | result.C[counter]++; 22 | } else { 23 | result.C[counter] = base + 1; 24 | } 25 | // reset max 26 | if (result.C[counter] > max) { 27 | max = result.C[counter]; 28 | } 29 | } 30 | } 31 | 32 | // build the last result 33 | for (i = 0; i < N; i++) { 34 | if (result.C[i] < base) { 35 | result.C[i] = base; 36 | } 37 | } 38 | 39 | return result; 40 | } 41 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-2/MissingInteger.c: -------------------------------------------------------------------------------- 1 | /* 2 | * MissingInteger 3 | * Find the minimal positive integer not occurring in a given sequence. 4 | */ 5 | 6 | int solution(int A[], int N) 7 | { 8 | // write your code in C90 9 | int *hash = (int *)malloc(sizeof(int)*(N+1)); 10 | memset(hash, 0, sizeof(int)*(N+1)); 11 | 12 | int result = 1, i; 13 | 14 | for (i = 0; i < N; i++) { 15 | if (A[i] > 0 && A[i] <= N) { 16 | hash[A[i]] = 1; 17 | } 18 | } 19 | 20 | for (result = 1; result <= N; result++) { 21 | if (hash[result] == 0) { 22 | return result; 23 | } 24 | } 25 | 26 | return result; 27 | } 28 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-2/PermCheck.c: -------------------------------------------------------------------------------- 1 | /* 2 | * PermCheck 3 | * Check whether array A is a permutation 4 | */ 5 | 6 | int solution(int A[], int N) 7 | { 8 | int i; 9 | int *hash = (int *)malloc(sizeof(int)*(N+1)); 10 | memset(hash, 0, sizeof(int)*(N+1)); 11 | 12 | for (i = 0; i < N; i++) { 13 | if (A[i] > N || hash[A[i]] != 0) { 14 | return 0; 15 | } 16 | hash[A[i]]++; 17 | } 18 | 19 | return 1; 20 | } 21 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-2/README: -------------------------------------------------------------------------------- 1 | Counting Elements 2 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-3/CountDiv.c: -------------------------------------------------------------------------------- 1 | /* 2 | * CountDiv 3 | * Compute number of integers divisible by k in range [a..b] 4 | */ 5 | 6 | int solution(int A, int B, int K) 7 | { 8 | if (A%K == 0) { 9 | return (B - A)/K + 1; 10 | } else { 11 | return (B - (A - A%K))/K; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-3/GenomicRangeQuery.c: -------------------------------------------------------------------------------- 1 | /* 2 | * GenomicRangeQuery 3 | * Find the minimal nucleotide from a range of sequence DNA. 4 | */ 5 | #include 6 | #include 7 | 8 | struct Results solution(char *S, int P[], int Q[], int M) 9 | { 10 | struct Results result; 11 | result.A = (int *)malloc(sizeof(int)*M); 12 | result.M = M; 13 | 14 | int i, j, N, from, to; 15 | int **counter; 16 | N = strlen(S); 17 | 18 | // initial counter 19 | counter = (int **)malloc(sizeof(int *)*4); 20 | for (i = 0; i < 4; i++) { 21 | counter[i] = (int *)malloc(sizeof(int)*(N+1)); 22 | memset(counter[i], 0, sizeof(int)*(N+1)); 23 | } 24 | 25 | // 1. record the appearance of nucleotides respectively 26 | // 2. the index of counter starts from 1! 27 | for (i = 0; i < N; i++) { 28 | if (S[i] == 'A') counter[0][i+1]++; // note.2 29 | else if (S[i] == 'C') counter[1][i+1]++; 30 | else if (S[i] == 'G') counter[2][i+1]++; 31 | else if (S[i] == 'T') counter[3][i+1]++; 32 | else return -1; 33 | } 34 | // 3. get the appearance from [1, k] for queries 35 | for (i = 0; i < 4; i++) { 36 | for (j = 2; j <= N; j++) { 37 | counter[j][i] += counter[j][i-1]; 38 | } 39 | } 40 | 41 | // 4. get the final result 42 | // 5. The index of P&Q starts from 0, 43 | // so [P, Q] "==" (from, to] in counter. 44 | for (i = 0; i < M; i++) { 45 | from = P[i]; // note.5 46 | to = Q[i] + 1; 47 | 48 | if (counter[0][to] - counter[0][from] > 0) { 49 | result.A[i] = 1; 50 | } else if (counter[1][to] - counter[1][from] > 0) { 51 | result.A[i] = 2; 52 | } 53 | } else if (counter[2][to] - counter[2][from] > 0) { 54 | result.A[i] = 3; 55 | } 56 | } else if (counter[3][to] - counter[3][from] > 0) { 57 | result.A[i] = 4; 58 | } else { 59 | return -1; 60 | } 61 | } 62 | 63 | return result; 64 | } 65 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-3/MinAvgTwoSlice.c: -------------------------------------------------------------------------------- 1 | /* 2 | * MinAvgTwoSlice 3 | * Find the minimal average of any slice containing at least two elements. 4 | */ 5 | 6 | int solution(int A[], int N) 7 | { 8 | int i, start = 0; 9 | float mean, min; 10 | 11 | min = (A[0], A[i])/2.0; 12 | 13 | /* The len of MinAvgTwoSlice can only be 2 or 3. 14 | * The proven can be found in here: 15 | * http://codesays.com/2014/solution-to-min-avg-two-slice-by-codility/ 16 | */ 17 | 18 | // For slices which len == 2 19 | for (i = 0; i < N - 1; i++) { 20 | mean = (A[i] + A[i+1])/2.0; 21 | if (mean < min) { 22 | min = mean; 23 | start = index; 24 | } 25 | } 26 | 27 | // For slices which len == 3 28 | for (i = 0; i < N - 2; i++) { 29 | mean = (A[i] + A[i+1] + A[i+2])/3.0; 30 | if (mean < min) { 31 | min = mean; 32 | start = index; 33 | } 34 | } 35 | 36 | return start; 37 | } 38 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-3/PassingCars.c: -------------------------------------------------------------------------------- 1 | /* 2 | * PassingCars 3 | * Count the number of passing cars on the road 4 | */ 5 | 6 | int solution(int A[], int N) 7 | { 8 | // write your code in C90 9 | int result = 0; 10 | int west_sum = 0, west_remain = 0; 11 | int i; 12 | 13 | for (i = 0; i < N; i++) { 14 | west_sum += A[i]; 15 | } 16 | west_remain = west_sum; 17 | for (i = 0; i < N; i++) { 18 | if (A[i] == 0) { 19 | result += west_remain; 20 | } else { 21 | west_remain--; 22 | } 23 | 24 | if (result > 1000000000) { 25 | return -1; 26 | } 27 | } 28 | 29 | return result; 30 | } 31 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-3/README: -------------------------------------------------------------------------------- 1 | Prefix Sums 2 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-4/Distinct.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Distinct 3 | * Compute number of distinct values in an array. 4 | */ 5 | 6 | int compare(const void *a, const void *b) 7 | { 8 | return *(int *)a - *(int *)b; 9 | } 10 | 11 | // Method one: use qsort() 12 | // Note: qsort can cause timeout for some extreme cases 13 | int solution_1(int A[], int N) 14 | { 15 | int cnt = 0, i; 16 | qsort(A, N, sizeof(int), compare); 17 | 18 | for (i = 0; i < N; i++) { 19 | if (i == 0) cnt = 1; 20 | else if (A[i] != A[i-1]) cnt++; 21 | } 22 | 23 | return cnt; 24 | } 25 | 26 | // Method two: merge-and-sort 27 | int solution_2(int A[], int N) 28 | { 29 | int cnt = 0; 30 | int *tmp = (int *)malloc(sizeof(int)*N); 31 | memset(tmp, 0, sizeof(int)*N); 32 | int i, j, k, from, mid, to, steps; 33 | 34 | // non-recursive merget-and-sort: bottom up style 35 | for (steps = 1; steps <= N; steps += steps) { 36 | // select two sub-slice to merge which len == steps: 37 | // [from, mid) + [mid, to) ==> [from, to) 38 | for (from = 0; from < N; from += steps + steps) { 39 | mid = from + steps; 40 | to = mid + steps; 41 | 42 | // there is only one slice left, leave to the next round 43 | if (mid >= N) break; 44 | if (to >= N) to = N; 45 | 46 | // merge 47 | for (i = k = from, j = mid; k < to; k++) { 48 | if (i == mid) tmp[k] = A[j++]; 49 | else if (j == to) tmp[k] = A[i++]; 50 | else if (A[i] <= A[j]) tmp[k] = A[i++]; 51 | else tmp[k] = A[j++]; 52 | } 53 | } 54 | 55 | // copy tmp back to A 56 | // Note: only *k* items is used in tmp! 57 | for (i = 0; i < k; i++) { 58 | A[i] = tmp[i]; 59 | } 60 | } 61 | 62 | for (i = 0; i < N; i++) { 63 | if (i == 0) cnt = 1; 64 | else if (A[i] != A[i-1]) cnt++; 65 | } 66 | 67 | return cnt; 68 | } 69 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-4/MaxProductOfThree.c: -------------------------------------------------------------------------------- 1 | /* 2 | * MaxProductOfThree 3 | * Maximize A[P] * A[Q] * A[R] for any triplet (P, Q, R). 4 | */ 5 | 6 | // There is a O(n) method, but the code can be really messy: 7 | // 1. find three smallest negtive numbers: n1 <= n2 <= n3 < 0 8 | // 2. find three biggest postive numbers: p1 >= p2 >= p3 > 0 9 | // 3. result = MAX(p1*p2*p3, p1*n1*n2) 10 | // 4. some other extremely cases needs to be discussed. 11 | 12 | // Method: sort then get the result 13 | #define MAX(a, b) (((a) >= (b)) ? (a) : (b)) 14 | 15 | int compare(const void *a, const void *b) 16 | { 17 | return *(int *)a - *(int *)b; 18 | } 19 | 20 | int solution(int A[], int N) 21 | { 22 | // write your code in C90 23 | qsort(A, N, sizeof(int), compare); 24 | 25 | return MAX(A[0]*A[1]*A[N-1], A[N-3]*A[N-2]*A[N-1]); 26 | } 27 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-4/NumberOfDiscIntersections.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * NumberOfDiscIntersections 3 | * Compute intersections between sequence od discs 4 | */ 5 | 6 | #include 7 | 8 | // Find this method from: 9 | // http://blog.csdn.net/caopentcs/article/details/9327069 10 | 11 | int solution(const vector &A) 12 | { 13 | // write your code in C++98 14 | int N = A.size(); 15 | int M = N << 1; 16 | int result = 0, intersect = 0, i, j; 17 | vector< pair > end_points(M); 18 | 19 | for (i = 0, j = 0; i < N; i++) { 20 | end_points[j++] = make_pair((long long)i - A[i], -1); // -1 means left edge point 21 | end_points[j++] = make_pair((long long)i + A[i], 1); // 1 means right edge point 22 | } 23 | 24 | sort(end_points.begin(), end_points.end()); 25 | 26 | for (j = 0; j < M; j++) { 27 | if (end_points[j].second < 0) { 28 | // new disc comes, so this new disc has intersect with all the discs left 29 | result += intersect; 30 | intersect++; 31 | } else { 32 | intersect--; 33 | } 34 | if (result > 10000000) { 35 | return -1; 36 | } 37 | } 38 | 39 | return result; 40 | } 41 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-4/README: -------------------------------------------------------------------------------- 1 | Sorting 2 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-4/Triangle.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Triangle 3 | * Determine whether a triangle can be built from a given set of edges. 4 | */ 5 | 6 | // qsort is too simple, try to practice merge-and-sort 7 | int solution(int A[], int N) 8 | { 9 | int from, to, mid, steps, i, j, k; 10 | int *tmp = (int *)malloc(sizeof(int)*N); 11 | memset(tmp, 0, sizeof(int)*N); 12 | 13 | for (steps = 1; steps <= N; steps += steps) { 14 | for (from = 0; from < N; from += steps + steps) { 15 | mid = from + steps; 16 | to = mid + steps; 17 | if (mid >= N) break; 18 | if (to >= N) to = N; 19 | 20 | for (i = k = from, j = mid; k < to; k++) { 21 | if (i == mid) tmp[k] = A[j++]; 22 | else if (j == to) tmp[k] = A[i++]; 23 | else if (A[i] <= A[j]) tmp[k] = A[i++]; 24 | else tmp[k] = A[j++]; 25 | } 26 | } 27 | for (i = 0; i < k; i++) { 28 | A[i] = tmp[i]; 29 | } 30 | } 31 | 32 | for (i = 0; i < N - 2; i++) { 33 | if (A[i] < 0) continue; 34 | // be careful with overflow, use sub instead of add 35 | if (A[i+2] - A[i+1] < A[i]) { 36 | return 1; 37 | } 38 | } 39 | 40 | return 0; 41 | } 42 | 43 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-5/Brackets.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Brackets 3 | * Determine whether a given string of parentheses is properly nested. 4 | */ 5 | 6 | int solution(char *S) 7 | { 8 | int i, top; 9 | int n = strlen(S); 10 | char *stack; 11 | stack = (char *)malloc(sizeof(char)*n); 12 | 13 | for (top = 0, i = 0; i < n; i++) { 14 | if (S[i] == '(' || S[i] == '[' || S[i] == '{') { 15 | stack[top++] = S[i]; 16 | } else if (top > 0 && ( (S[i] == ']' && stack[top-1] == '[') 17 | || (S[i] == ')' && stack[top-1] == '(') 18 | || (S[i] == '}' && stack[top-1] == '}') )) { 19 | top--; 20 | } else { 21 | return 0; 22 | } 23 | } 24 | 25 | if (top == 0) { 26 | return 1; 27 | } else { 28 | return 0; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-5/Fish.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Fish 3 | * N voracious fish are moving along a river. Calculate how many fish are alive. 4 | */ 5 | 6 | int solution(int A[], int B[], int N) 7 | { 8 | int cnt = 0, i, top; 9 | int *stack = (int *)malloc(sizeof(int)*N); 10 | memset(stack, 0, N); 11 | 12 | for (top = 0, i = 0; i < N; i++) { 13 | if (B[i] == 1) { 14 | stack[top++] = A[i]; // downstream fishes 15 | } else { 16 | while (top > 0 && stack[top-1] < A[i]) { 17 | top--; 18 | } 19 | if (top == 0) { 20 | cnt ++; // this fish is bigger then all the lived downstream fishes 21 | } 22 | } 23 | } 24 | 25 | return cnt + top; 26 | } 27 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-5/Nesting.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Nesting 3 | * Determine whether given string of parentheses is properly nested. 4 | */ 5 | 6 | int solution(char *S) 7 | { 8 | int i, cnt = 0; 9 | int n = strlen(S); 10 | 11 | for (i = 0; i < n; i++) { 12 | if (S[i] == '(') { 13 | cnt++; 14 | } else if (cnt > 0) { 15 | cnt--; 16 | } else { 17 | return 0; 18 | } 19 | } 20 | if (cnt == 0) { 21 | return 1; 22 | } else { 23 | return 0; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-5/README: -------------------------------------------------------------------------------- 1 | Stacks and Queues 2 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-5/StoneWall.c: -------------------------------------------------------------------------------- 1 | /* 2 | * StoneWall 3 | * Cover "Manhattan skyline" using the minimum number of rectangles. 4 | */ 5 | 6 | int solution(int H[], int N) 7 | { 8 | int top, i, cnt = 0; 9 | int *stack = (int *)malloc(sizeof(int)*N); 10 | memset(stack, 0, sizeof(int)*N); 11 | 12 | for (top = 0, i = 0; i < N; i++) { 13 | while (top > 0 && H[i] < stack[top-1]) { 14 | top--; 15 | cnt++; 16 | } 17 | 18 | if (top == 0 || H[i] < stack[top-1]) { 19 | stack[top++] = H[i]; 20 | } 21 | } 22 | 23 | return cnt + top; 24 | } 25 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-6/Dominator.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Dominator 3 | * Find an index of an array such that its value occurs at more than half of indices in the array. 4 | */ 5 | 6 | // This is a very classic problem disscussed here: 7 | // http://www.cs.utexas.edu/~moore/best-ideas/mjrty/ 8 | int solution(int A[], int N) 9 | { 10 | int dominator, index; 11 | int cnt = 0, i; 12 | 13 | for (i = 0; i < N; i++) { 14 | if (cnt == 0) { 15 | dominator = A[i]; 16 | index = i; 17 | cnt = 1; 18 | } else if (A[i] == dominator) { 19 | cnt++; 20 | } else { 21 | cnt--; 22 | } 23 | } 24 | 25 | if (cnt > 0) { 26 | // double check dominator 27 | cnt = 0;; 28 | for (i = 0; i < N; i++) { 29 | if (A[i] == dominator) cnt++; 30 | } 31 | if (cnt > N/2) return index; 32 | else return -1; 33 | } else { 34 | return -1; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-6/EquiLeader.c: -------------------------------------------------------------------------------- 1 | /* 2 | * EquiLeader 3 | * Find the index S such that the leaders of the sequences A[0], A[1], ..., A[S] and A[S + 1], A[S + 2], ..., A[N - 1] are the same. 4 | */ 5 | 6 | int solution(int A[], int N) 7 | { 8 | int cnt = 0, lcnt, rcnt, i, candidate; 9 | int result = 0; 10 | 11 | // find candidate 12 | for (i = 0; i < N; i++) { 13 | if (cnt == 0) { 14 | candidate = A[i]; 15 | cnt = 1; 16 | } else if (A[i] == candidate) { 17 | cnt++; 18 | } else { 19 | cnt--; 20 | } 21 | } 22 | // double check candidate 23 | if (cnt > 0) { 24 | cnt = 0; 25 | for (i = 0; i < N; i++) { 26 | if (A[i] == candidate) cnt++; 27 | } 28 | if (cnt <= N/2) return 0; 29 | } else { 30 | return 0; 31 | } 32 | 33 | lcnt = rcnt = 0; 34 | for (i = 0; i < N; i++) { 35 | if (A[i] == candidate) lcnt++; 36 | rcnt = cnt - lcnt; 37 | if (lcnt > (i+1)/2 && rcnt > (N-i-1)/2) { 38 | result++; 39 | } 40 | } 41 | 42 | return result; 43 | } 44 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-6/README: -------------------------------------------------------------------------------- 1 | Leader 2 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-7/MaxDoubleSliceSum.c: -------------------------------------------------------------------------------- 1 | /* 2 | * MaxDoubleSliceSum 3 | * Find the maximal sum of any double slice. 4 | */ 5 | 6 | #define MAX(a, b) (((a) >= (b)) ? (a) : (b)) 7 | 8 | int solution(int A[], int N) 9 | { 10 | int *L, *R; 11 | int i, max = 0; 12 | 13 | if (N <= 3) return 0; 14 | 15 | L = (int *)malloc(sizeof(int)*N); 16 | R = (int *)malloc(sizeof(int)*N); 17 | memset(L, 0, sizeof(int)*N); 18 | memset(R, 0, sizeof(int)*N); 19 | 20 | for (i = 1; i < N-1; i++) { 21 | L[i] = MAX(L[i-1] + A[i], 0); 22 | } 23 | for (i = N-2; i > 0; i--) { 24 | R[i] = MAX(R[i+1] + A[i], 0); 25 | } 26 | 27 | for (i = 1; i < N-1; i++) { 28 | max = MAX(max, L[i-1] + R[i+1]); 29 | } 30 | 31 | return max; 32 | } 33 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-7/MaxProfit.c: -------------------------------------------------------------------------------- 1 | /* 2 | * MaxProfit 3 | * Given a log of stock prices compute the maximum possible earning 4 | */ 5 | 6 | #define MAX(a, b) (((a) >= (b)) ? (a) : (b)) 7 | 8 | int solution(int A[], int N) 9 | { 10 | int max = 0, profit = 0, i; 11 | 12 | for (i = 0; i < N; i++) { 13 | profit += A[i] - A[i-1]; 14 | profit = MAX(O, profit); 15 | max = MAX(max, profit); 16 | } 17 | 18 | return max; 19 | } 20 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-7/MaxSliceSum.c: -------------------------------------------------------------------------------- 1 | /* 2 | * MaxSliceSum 3 | * Find a maximum sum of a compact subsequence of array elements. 4 | */ 5 | 6 | #define MAX(a, b) (((a) >= (b)) ? (a) : (b)) 7 | 8 | int solution(int A[], int N) 9 | { 10 | int sum = 0, max = 0, i; 11 | 12 | if (N == 0) return 0; 13 | max = A[0]; 14 | 15 | for (i = 0; i < N; i++) { 16 | sum += A[i]; 17 | sum = MAX(0, sum); 18 | max = MAX(max, sum); 19 | } 20 | 21 | return max; 22 | } 23 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-7/README: -------------------------------------------------------------------------------- 1 | Maximum slice problem 2 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-8/CountFactors.c: -------------------------------------------------------------------------------- 1 | /* 2 | * CountFactors 3 | * Count factors of given number n. 4 | */ 5 | 6 | int solution(int N) 7 | { 8 | int result = 0, i; 9 | 10 | while (N/i > i) { // use '/' to avoid overflow 11 | if (N % i == 0) result += 2; 12 | i++; 13 | } 14 | if (N % i == 0 && N / i == i) result++; 15 | 16 | return reuslt; 17 | } 18 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-8/Flags.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Flags 3 | * Find the maximum number of flags that can be set on mountain peaks. 4 | */ 5 | 6 | int solution(int A[], int N) 7 | { 8 | int i, result, pos, sum; 9 | int *next = (int *)malloc(sizeof(int)*N); 10 | memset(next, 0, sizeof(int)*N); 11 | 12 | if (N < 3) return 0; 13 | 14 | // initial next peaks 15 | next[N-1] = -1; // -1 means no peak after this point 16 | for (i = N-2; i > 0; i++) { 17 | if (A[i] > A[i-1] && A[i] > A[i+1]) { 18 | next[i] = i; 19 | } else { 20 | next[i] = next[i+1]; 21 | } 22 | } 23 | next[0] = next[1]; 24 | 25 | i = 1; 26 | result = 0; 27 | while ( N/(i-1) >= (i-1) ) { 28 | pos = 1; 29 | sum = 0; 30 | while (pos < N && sum < i) { 31 | pos = next[pos]; 32 | if (pos == -1) break; 33 | sum += 1; // number of flags for step == i 34 | pos += i; 35 | } 36 | result = sum >= result ? sum : result; 37 | i++; 38 | } 39 | 40 | return result; 41 | } 42 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-8/MinPerimeterRectangle.c: -------------------------------------------------------------------------------- 1 | /* 2 | * MinPerimeterRectangle 3 | * Find the minimal perimeter of any rectangle whose area equals N. 4 | */ 5 | 6 | int solution(int N) 7 | { 8 | int biggest_factor = 1; 9 | int i = 1, j; 10 | 11 | while (i*i <= N) { 12 | if (N % i = 0) biggest_factor = i; 13 | i++; 14 | } 15 | j = N/biggest_factor; 16 | 17 | return 2*(j + biggest_factor); 18 | } 19 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-8/Peaks.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Peaks 3 | * Divide an array into the maximum number of same((-))sized blocks, each of which should contain an index P such that A[P - 1] < A[P] > A[P + 1]. 4 | */ 5 | 6 | int solution(int A[], int N) 7 | { 8 | int i, step, flag, result = 0; 9 | int *peak = (int *)malloc(sizeof(int)*N); 10 | memset(peak, 0, sizeof(int)*N); 11 | 12 | if (N < 3) return 0; 13 | 14 | for (i = 1; i < N-1; i++) { 15 | if (A[i] > A[i-1] && A[i] > A[i+1]) { 16 | peak[i] = peak[i-1] + 1; 17 | } else { 18 | peak[i] = peak[i-1]; 19 | } 20 | } 21 | peak[N-1] = peak[N-2]; 22 | 23 | step = 2; 24 | while(step <= N) { 25 | if (N%step == 0) { 26 | flag = 1; // when step is an candidate, flag == 1 27 | for (i = step - 1; i < N; i += step) { 28 | // No peak in the first slice *OR* no peak in the rest slices 29 | if ((i == step - 1 && peak[i] <= 0) 30 | || (i > step - 1 && peak[i] - peak[i-step] <= 0)) { 31 | flag = 0; 32 | break; 33 | } 34 | } 35 | if (flag == 1) { 36 | result = N/step; 37 | break; 38 | } 39 | } 40 | } 41 | 42 | return result; 43 | } 44 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-8/README: -------------------------------------------------------------------------------- 1 | Prime and composite numbers 2 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-9/CountNonDivisible.c: -------------------------------------------------------------------------------- 1 | /* 2 | * CountNonDivisible 3 | * Calculate the number of elements of an array that are not divisors of each element. 4 | */ 5 | 6 | struct Result solution(int A[], N) 7 | { 8 | struct Results result; 9 | result.C = (int *)malloc(sizeof(int)*N); 10 | memset(result.C, 0, sizeof(int)*N); 11 | 12 | int *nums, *divisors; 13 | nums = (int *)malloc(sizeof(int)*(N*2+1)); 14 | divisors = (int *)malloc(sizeof(int)*(N*2+1)); 15 | memset(nums, 0, sizeof(int)*(N*2+1)); 16 | memset(divisors, 0, sizeof(int)*(N*2+1)); 17 | int i, j; 18 | 19 | for (i = 0; i < N; i++) { 20 | nums[A[i]]++; 21 | } 22 | 23 | // divisors[i] marks how much divisors of *i* that shown up in array A 24 | for (i = 1; i <= 2*N; i++) { 25 | if (nums[i] > 0) { 26 | if (nums[i] > 1) divisors[i] += nums[i] - 1; 27 | j = i + i; 28 | while (j <= 2*N) { 29 | if (nums[j] > 0) { 30 | divisors[j] += nums[i]; 31 | } 32 | j += i; 33 | } 34 | } 35 | } 36 | 37 | for (i = 0; i < N; i++) { 38 | result.C[i] = (N-1) - divisors[A[i]]; 39 | } 40 | result.L = N; 41 | 42 | return result; 43 | } 44 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-9/CountSemiprimes.c: -------------------------------------------------------------------------------- 1 | /* 2 | * CountSemiprimes 3 | * Count the semiprime numbers in the given range [a..b] 4 | */ 5 | 6 | 7 | struct Results solution(int N, int P[], int Q[], int M) { 8 | struct Results result; 9 | result.A = (int *)malloc(sizeof(int)*M); 10 | memset(result.A, 0, sizeof(int)*M); 11 | 12 | int *divisors, *counter, i, k; 13 | divisors = (int *)malloc(sizeof(int)*(N+1)); 14 | counter = (int *)malloc(sizeof(int)*(N+1)); 15 | memset(divisors, 0, sizeof(int)*(N+1)); 16 | memset(counter, 0, sizeof(int)*(N+1)); 17 | 18 | i = 2; 19 | while (i*i <= N) { 20 | if (divisors[i] == 0) { 21 | k = i*i; 22 | while (k <= N) { 23 | if (divisors[k] == 0) divisors[k] = i; 24 | k += i; 25 | } 26 | } 27 | i++; 28 | } 29 | 30 | for (i = 1; i <= N; i++) { 31 | if (divisors[i] != 0 && divisors[i/divisors[i]] == 0) 32 | counter[i] = counter[i-1] + 1; 33 | else 34 | counter[i] = counter[i-1]; 35 | } 36 | 37 | for (i = 0; i < M; i++) { 38 | result.A[i] = counter[Q[i]] - counter[P[i] - 1]; 39 | } 40 | 41 | result.M = M; 42 | return result; 43 | } 44 | -------------------------------------------------------------------------------- /codility/C&C++/lesson-9/README: -------------------------------------------------------------------------------- 1 | Sieve of Eratosthenes 2 | -------------------------------------------------------------------------------- /codility/C&C++/others/ArrayInversionCount.c: -------------------------------------------------------------------------------- 1 | /* 2 | * ArrayInversionCount 3 | * Compute number of inversion in an array. 4 | */ 5 | 6 | 7 | // you can write to stdout for debugging purposes, e.g. 8 | // printf("this is a debug message\n"); 9 | 10 | int solution(int A[], int N) { 11 | // write your code in C90 12 | int result = 0; 13 | 14 | // Merge-and-Sort 15 | int from, to, mid, steps; 16 | int i = 0, j = 0, k = 0; 17 | int *tmp; 18 | tmp = (int *)malloc(sizeof(int)*N); 19 | 20 | for (steps = 1; steps <= N; steps += steps) { 21 | for (from = 0; from < N; from += steps + steps) { 22 | mid = from + steps; 23 | to = mid + steps; 24 | if (mid >= N) break; 25 | if (to >= N) to = N; 26 | 27 | for (i = k = from, j = mid; k < to; k++) { 28 | if (i == mid) { 29 | tmp[k] = A[j++]; 30 | } else if (j == to) { 31 | tmp[k] = A[i++]; 32 | } else if (A[i] <= A[j]) { 33 | tmp[k] = A[i++]; 34 | } else { 35 | tmp[k] = A[j++]; 36 | result += mid - i; 37 | } 38 | } 39 | } 40 | // Swap tmp and A 41 | for (i = 0; i < k; i++) { // tmp is only used up to 'k' 42 | A[i] = tmp[i]; 43 | } 44 | } 45 | 46 | return result; 47 | } -------------------------------------------------------------------------------- /codility/C&C++/others/BinaryGap.c: -------------------------------------------------------------------------------- 1 | /* 2 | * BinaryGap 3 | * Find longest sequence of zeros in binary representation of an integer. 4 | */ 5 | 6 | 7 | // you can write to stdout for debugging purposes, e.g. 8 | // printf("this is a debug message\n"); 9 | 10 | int solution(int N) { 11 | // write your code in C90 12 | int max, tmp, start; 13 | 14 | max = 0; 15 | start = 0; 16 | tmp = 0; 17 | while (N > 0) { 18 | if (N & 1) { 19 | if (start == 1) { 20 | if (tmp > max) max = tmp; 21 | } 22 | tmp = 0; 23 | start = 1; 24 | } else { 25 | tmp++; 26 | } 27 | N = (N >> 1); 28 | } 29 | 30 | return max; 31 | } -------------------------------------------------------------------------------- /codility/C&C++/others/StrSymmetryPoint.c: -------------------------------------------------------------------------------- 1 | /* 2 | * StrSymmetryPoint 3 | * Find a symmetry point of a string, if any. 4 | */ 5 | 6 | 7 | // you can write to stdout for debugging purposes, e.g. 8 | // printf("this is a debug message\n"); 9 | 10 | int solution(char *S) { 11 | // write your code in C90 12 | int i, j, pivot, len; 13 | 14 | len = strlen(S); 15 | if (len % 2 == 0) return -1; 16 | pivot = len/2; 17 | 18 | for (i = pivot - 1, j = pivot + 1; i >= 0; i--, j++) { 19 | if (S[i] != S[j]) return -1; 20 | } 21 | 22 | return pivot; 23 | } 24 | -------------------------------------------------------------------------------- /codility/C&C++/others/TreeHeight.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * TreeHeight 3 | * Compute the height of a binary link-tree. 4 | */ 5 | 6 | 7 | // you can write to stdout for debugging purposes, e.g. 8 | // printf("this is a debug message\n"); 9 | 10 | // This recursive version in C can cause timeout 11 | /* 12 | #define MAX(a, b) (((a) >= (b)) ? (a) : (b)) 13 | 14 | int solution(struct tree * T) { 15 | // write your code in C90 16 | if (T->r == NULL && T->l == NULL) { 17 | return 0; 18 | } else if (T->r == NULL) { 19 | return 1 + solution(T->l); 20 | } else if (T->l == NULL) { 21 | return 1 + solution(T->r); 22 | } else { 23 | return 1 + MAX(solution(T->r), solution(T->l)); 24 | } 25 | } 26 | */ 27 | 28 | // you can use includes, for example: 29 | // #include 30 | 31 | // you can write to stdout for debugging purposes, e.g. 32 | // cout << "this is a debug message" << endl; 33 | #include 34 | #include 35 | 36 | using namespace std; 37 | 38 | int solution(tree * T) { 39 | // write your code in C++11 40 | int height = 0; 41 | queue current, next, tmp; 42 | current.push(T); 43 | 44 | while(!current.empty()) { 45 | while(!current.empty()) { 46 | tree *p = current.front(); 47 | current.pop(); 48 | if (p->l != NULL) next.push(p->l); 49 | if (p->r != NULL) next.push(p->r); 50 | } 51 | 52 | // swap current and next 53 | tmp = next; 54 | next = current; 55 | current = tmp; 56 | 57 | // count height 58 | if (!current.empty()) { 59 | height++; 60 | } 61 | } 62 | 63 | return height; 64 | } 65 | 66 | -------------------------------------------------------------------------------- /codility/README: -------------------------------------------------------------------------------- 1 | ###Codility 2 | 3 | [Lessons](https://codility.com/programmers/lessons/) 4 | [Challenges](https://codility.com/programmers/challenges/) 5 | 6 | 7 | [Unofficial Solutions to the Training by Codility](http://codesays.com/solutions-to-training-by-codility/) 8 | 9 | 10 | -------------------------------------------------------------------------------- /leetcode/C&C++/easy/BestTimetoBuyandSellStock.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Best Time to Buy and Sell Stock 3 | * Say you have an array for which the ith element is the price of a given stock on day i. 4 | * 5 | * If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. 6 | */ 7 | 8 | 9 | class Solution { 10 | public: 11 | int maxProfit(vector &prices) { 12 | int max, buy, sell; 13 | int i, size; 14 | size = prices.size(); 15 | 16 | if (size < 2) return 0; 17 | 18 | buy = prices[0]; 19 | max = 0; 20 | for (i = 1; i < size; i++) { 21 | if (prices[i] < buy) { 22 | buy = prices[i]; 23 | } else { 24 | int profits; 25 | profits = prices[i] - buy; 26 | if (profits > max) max = profits; 27 | } 28 | } 29 | 30 | return max; 31 | } 32 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/BestTimetoBuyandSellStockII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Best Time to Buy and Sell Stock II 3 | * Say you have an array for which the ith element is the price of a given stock on day i. 4 | * 5 | * Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 6 | */ 7 | 8 | 9 | class Solution { 10 | public: 11 | int maxProfit(vector &prices) { 12 | int profit = 0, diff, i; 13 | for (i = 1; i < prices.size(); i++) { 14 | diff = prices[i] - prices[i-1]; 15 | if (diff > 0) profit += diff; 16 | } 17 | 18 | return profit; 19 | } 20 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/ClimbingStairs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Climbing Stairs 3 | * You are climbing a stair case. It takes n steps to reach to the top. 4 | * 5 | * Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 6 | */ 7 | 8 | 9 | class Solution { 10 | public: 11 | int climbStairs(int n) { 12 | // method one: recursive which can cause timeout 13 | /* 14 | if (n == 0) return 0; 15 | else if (n == 1) return 1; 16 | else if (n == 2) return 2; 17 | else return climbStairs(n-1) + climbStairs(n-2); 18 | */ 19 | 20 | // method two: Fibonacci numbers 21 | int a = 0, b = 1; 22 | int i, result = 0;; 23 | 24 | for (i = 0; i < n; i++) { 25 | result = a + b; 26 | a = b; 27 | b = result; 28 | } 29 | return result; 30 | } 31 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/Combinations.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Combinations 3 | * Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. 4 | */ 5 | 6 | 7 | class Solution { 8 | public: 9 | vector > combine(int n, int k) { 10 | vector > result; 11 | vector combination; 12 | int i; 13 | if (n < k) return result; 14 | for (i = 1; i <= k; i++) { 15 | combination.push_back(i); 16 | } 17 | result.push_back(combination); 18 | 19 | while (next_combination(combination, n, k) == 1) { 20 | result.push_back(combination); 21 | } 22 | 23 | return result; 24 | } 25 | 26 | private: 27 | int next_combination(vector &combination, int n, int k) { 28 | int i, hasnext = 0; 29 | int tmp; 30 | for (i = k - 1; i >= 0; i--) { 31 | if (combination[i] < (n - k + 1) + i) { 32 | hasnext = 1; 33 | tmp = combination[i]; 34 | while (i < k) { 35 | combination[i++] =(++tmp); 36 | } 37 | return hasnext; 38 | } 39 | } 40 | 41 | return hasnext; 42 | } 43 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/ContainerWithMostWater.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Container With Most Water 3 | * Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. 4 | * 5 | * Note: You may not slant the container. 6 | */ 7 | 8 | 9 | class Solution { 10 | public: 11 | int maxArea(vector &height) { 12 | // If left < right, find another bigger left; else find another bigger right 13 | int begin = 0, end = height.size() - 1; 14 | int result = -1, tmp, shorter; 15 | 16 | while (begin < end) { 17 | shorter = height[begin] <= height[end] ? height[begin] : height[end]; 18 | tmp = (end - begin)*shorter; 19 | result = tmp > result ? tmp : result; 20 | if (height[begin] <= height[end]) { 21 | while (begin < end && height[begin] <= shorter) { 22 | begin++; 23 | } 24 | } else { 25 | while (begin < end && height[end] <= shorter) { 26 | end--; 27 | } 28 | } 29 | } 30 | 31 | return result; 32 | } 33 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/ConvertSortedArraytoBinarySearchTree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Convert Sorted Array to Binary Search Tree 3 | * Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 4 | */ 5 | 6 | 7 | /** 8 | * Definition for binary tree 9 | * struct TreeNode { 10 | * int val; 11 | * TreeNode *left; 12 | * TreeNode *right; 13 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 14 | * }; 15 | */ 16 | class Solution { 17 | public: 18 | TreeNode *sortedArrayToBST(vector &num) { 19 | int n = num.size(); 20 | return BinarySearchStyleConvert(num, 0, n); 21 | } 22 | 23 | TreeNode *BinarySearchStyleConvert(vector &num, int from, int to) { 24 | if (from >= to) return NULL; 25 | 26 | int mid = (from + to)/2; 27 | TreeNode *root = new TreeNode(num[mid]); 28 | root->left = BinarySearchStyleConvert(num, from, mid); 29 | root->right = BinarySearchStyleConvert(num, mid+1, to); 30 | 31 | return root; 32 | } 33 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/CountandSay.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Count and Say 3 | * The count-and-say sequence is the sequence of integers beginning as follows: 4 | * 1, 11, 21, 1211, 111221, ... 5 | * 6 | * 1 is read off as "one 1" or 11. 7 | * 11 is read off as "two 1s" or 21. 8 | * 21 is read off as "one 2, then one 1" or 1211. 9 | * Given an integer n, generate the nth sequence. 10 | * 11 | * Note: The sequence of integers will be represented as a string. 12 | */ 13 | 14 | 15 | class Solution { 16 | public: 17 | string countAndSay(int n) { 18 | string result, tmp; 19 | char *p; 20 | if (n <= 0) return result; 21 | 22 | 23 | int count; 24 | char say; 25 | int i, j, k, len; 26 | 27 | for (i = 0; i < n; i++) { 28 | len = result.length(); 29 | if (len == 0) result += '1'; 30 | else { 31 | count = 0; 32 | tmp = ""; 33 | for (j = 0; j < len; j++) { 34 | if (count == 0) { 35 | count = 1; 36 | say = result[j]; 37 | } else if (result[j] == result[j-1]) { 38 | count++; 39 | } else { // find a new char 40 | tmp += (char)(count + '0'); 41 | tmp += say; 42 | 43 | count = 1; 44 | say = result[j]; 45 | } 46 | } 47 | tmp += (char)(count + '0'); 48 | tmp += say; 49 | 50 | result = tmp; 51 | } 52 | } 53 | 54 | return result; 55 | } 56 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/GenerateParentheses.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Generate Parentheses 3 | * Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 4 | * 5 | * For example, given n = 3, a solution set is: 6 | * 7 | * "((()))", "(()())", "(())()", "()(())", "()()()" 8 | */ 9 | 10 | 11 | class Solution { 12 | public: 13 | vector generateParenthesis(int n) { 14 | if (n == 0) return vector(1, ""); 15 | if (n == 1) return vector(1, "()"); 16 | 17 | vector result; 18 | vector inner, outer; 19 | string s1, s2; 20 | int i, j, k, len1, len2; 21 | 22 | for (i = 0; i < n; i++) { 23 | inner = generateParenthesis(i); 24 | outer = generateParenthesis(n-i-1); 25 | len1 = inner.size(); 26 | len2 = outer.size(); 27 | 28 | for(j = 0; j < len1; j++) { 29 | for (k = 0; k < len2; k++) { 30 | result.push_back("(" + inner[j] + ")" + outer[k]); 31 | } 32 | } 33 | } 34 | 35 | return result; 36 | } 37 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/GrayCode.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Gray Code 3 | * The gray code is a binary numeral system where two successive values differ in only one bit. 4 | * 5 | * Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0. 6 | * 7 | * For example, given n = 2, return [0,1,3,2]. Its gray code sequence is: 8 | * 9 | * 00 - 0 10 | * 01 - 1 11 | * 11 - 3 12 | * 10 - 2 13 | */ 14 | 15 | 16 | class Solution { 17 | public: 18 | vector grayCode(int n) { 19 | vector result; 20 | int size = 1 << n; 21 | int i; 22 | 23 | for (i = 0; i < size; i++) { 24 | result.push_back(i ^ (i >> 1)); 25 | } 26 | 27 | return result; 28 | } 29 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/JumpGame.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Jump Game 3 | * Given an array of non-negative integers, you are initially positioned at the first index of the array. 4 | * 5 | * Each element in the array represents your maximum jump length at that position. 6 | * 7 | * Determine if you are able to reach the last index. 8 | * 9 | * For example: 10 | * A = [2,3,1,1,4], return true. 11 | * 12 | * A = [3,2,1,0,4], return false. 13 | */ 14 | 15 | 16 | class Solution { 17 | public: 18 | bool canJump(int A[], int n) { 19 | int max, i = 0; 20 | max = A[0]; 21 | while (i <= max && max < n-1) { 22 | if ( i + A[i] > max) max = i + A[i]; 23 | i++; 24 | } 25 | if (max >= n-1) return true; 26 | else return false; 27 | } 28 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/LengthofLastWord.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Length of Last Word 3 | * Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. 4 | * 5 | * If the last word does not exist, return 0. 6 | * 7 | * Note: A word is defined as a character sequence consists of non-space characters only. 8 | * 9 | * For example, 10 | * Given s = "Hello World", 11 | * return 5. 12 | */ 13 | 14 | // Note: 15 | // Given s = "Hello World ", 16 | // also return 5! 17 | 18 | 19 | 20 | class Solution { 21 | public: 22 | int lengthOfLastWord(const char *s) { 23 | int len = 0; 24 | while (*s != '\0') { 25 | if (*s != ' ') len++; 26 | else if (*(s+1) != '\0' && *(s+1) != ' ') len = 0; 27 | 28 | s++; 29 | } 30 | 31 | return len; 32 | } 33 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/LinkedListCycle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Linked List Cycle 3 | * Given a linked list, determine if it has a cycle in it. 4 | * 5 | * Follow up: 6 | * Can you solve it without using extra space? 7 | */ 8 | 9 | 10 | /** 11 | * Definition for singly-linked list. 12 | * struct ListNode { 13 | * int val; 14 | * ListNode *next; 15 | * ListNode(int x) : val(x), next(NULL) {} 16 | * }; 17 | */ 18 | class Solution { 19 | public: 20 | bool hasCycle(ListNode *head) { 21 | ListNode *p, *q; 22 | p = q = head; 23 | while(p != NULL && p->next != NULL && p->next->next != NULL){ 24 | p = p->next->next; 25 | q = q->next; 26 | if (p == q) { 27 | return true; 28 | } 29 | } 30 | return false; 31 | } 32 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/MaximumDepthofBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Maximum Depth of Binary Tree 3 | * Given a binary tree, find its maximum depth. 4 | * 5 | * The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 6 | */ 7 | 8 | 9 | /** 10 | * Definition for binary tree 11 | * struct TreeNode { 12 | * int val; 13 | * TreeNode *left; 14 | * TreeNode *right; 15 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 16 | * }; 17 | */ 18 | // Recursive 19 | class Solution_1 { 20 | public: 21 | int maxDepth(TreeNode *root) { 22 | int left, right; 23 | if (root == NULL) return 0; 24 | left = maxDepth(root->left); 25 | right = maxDepth(root->right); 26 | return left >= right ? (left + 1):(right + 1); 27 | } 28 | }; 29 | 30 | // Non-recursive 31 | class Solution_2 { 32 | public: 33 | int maxDepth(TreeNode *root) { 34 | queue current, next; 35 | TreeNode *node; 36 | int result = 0; 37 | 38 | if (root == NULL) return result; 39 | current.push(root); 40 | 41 | while(!current.empty()) { 42 | result++; 43 | while(!current.empty()) { 44 | node = current.front(); 45 | if (node->left) next.push(node->left); 46 | if (node->right) next.push(node->right); 47 | current.pop(); 48 | } 49 | // swap next and current; 50 | while(!next.empty()) { 51 | node = next.front(); 52 | current.push(node); 53 | next.pop(); 54 | } 55 | } 56 | 57 | return result; 58 | } 59 | }; 60 | -------------------------------------------------------------------------------- /leetcode/C&C++/easy/MaximumSubarray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Maximum Subarray 3 | * Find the contiguous subarray within an array (containing at least one number) which has the largest sum. 4 | */ 5 | 6 | 7 | class Solution { 8 | public: 9 | int maxSubArray(int A[], int n) { 10 | int result = INT_MIN, tmp = 0, i; 11 | 12 | for (i = 0; i < n; i++) { 13 | tmp = max(tmp + A[i], A[i]); 14 | result = max(result, tmp); 15 | } 16 | 17 | return result; 18 | } 19 | private: 20 | int max(int a, int b) { 21 | return a >= b ? a: b; 22 | } 23 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/MergeSortedArray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Merge Sorted Array 3 | * Given two sorted integer arrays A and B, merge B into A as one sorted array. 4 | */ 5 | 6 | 7 | class Solution { 8 | public: 9 | void merge(int A[], int m, int B[], int n) { 10 | int i = m, j = n, k = m+n; 11 | 12 | while (i > 0 && j > 0) { 13 | if (A[i-1] <= B[j-1]) { 14 | A[k-1] = B[j-1]; 15 | j--; 16 | } else { 17 | A[k-1] = A[i-1]; 18 | i--; 19 | } 20 | k--; 21 | } 22 | while (j > 0) { 23 | A[k-1] = B[j-1]; 24 | j--; 25 | k--; 26 | } 27 | } 28 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/MergeTwoSortedLists.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Merge Two Sorted Lists 3 | * Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 4 | */ 5 | 6 | 7 | /** 8 | * Definition for singly-linked list. 9 | * struct ListNode { 10 | * int val; 11 | * ListNode *next; 12 | * ListNode(int x) : val(x), next(NULL) {} 13 | * }; 14 | */ 15 | class Solution { 16 | public: 17 | ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { 18 | ListNode *l3, *p, *q, *r; 19 | l3 = new ListNode(0); 20 | p = l1; 21 | q = l2; 22 | r = l3; 23 | 24 | while (p && q) { 25 | if (p->val <= q->val) { 26 | r->next = p; 27 | r = p; 28 | p = p->next; 29 | } else { 30 | r->next = q; 31 | r = q; 32 | q = q->next; 33 | } 34 | } 35 | while (p) { 36 | r->next = p; 37 | r = p; 38 | p = p->next; 39 | } 40 | while (q) { 41 | r->next = q; 42 | r = q; 43 | q = q->next; 44 | } 45 | 46 | return l3->next; 47 | } 48 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/MinimumDepthofBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Minimum Depth of Binary Tree 3 | * Given a binary tree, find its minimum depth. 4 | * 5 | * The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 6 | */ 7 | 8 | 9 | /** 10 | * Definition for binary tree 11 | * struct TreeNode { 12 | * int val; 13 | * TreeNode *left; 14 | * TreeNode *right; 15 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 16 | * }; 17 | */ 18 | 19 | // Non-recursive with two queue. 20 | class Solution { 21 | public: 22 | int minDepth(TreeNode *root) { 23 | if (root == NULL) return 0; 24 | 25 | queue cur, nxt; 26 | TreeNode *p; 27 | int result = 0; 28 | 29 | cur.push(root); 30 | while (!cur.empty()) { 31 | result++; 32 | while (!cur.empty()) { 33 | p = cur.front(); 34 | cur.pop(); 35 | if (p->left == NULL && p->right == NULL) { 36 | return result; 37 | } 38 | if (p->left) { 39 | nxt.push(p->left); 40 | } 41 | if (p->right) { 42 | nxt.push(p->right); 43 | } 44 | } 45 | 46 | // swap cur and nxt; 47 | while (!nxt.empty()) { 48 | p = nxt.front(); 49 | nxt.pop(); 50 | cur.push(p); 51 | } 52 | } 53 | 54 | return result; 55 | } 56 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/MinimumPathSum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Minimum Path Sum 3 | * Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. 4 | * 5 | * Note: You can only move either down or right at any point in time. 6 | */ 7 | 8 | 9 | class Solution { 10 | public: 11 | int minPathSum(vector > &grid) { 12 | int row, col, m, n, result; 13 | m = grid.size(); 14 | n = grid[0].size(); 15 | if (m <=0 || n <= 0) return 0; 16 | vector buf(n); 17 | 18 | // init buf 19 | for (col = 0; col < n; col++) { 20 | if (col == 0) buf[col] = grid[0][col]; 21 | else buf[col] = buf[col-1] + grid[0][col]; 22 | } 23 | 24 | for (row = 1; row < m; row++) { 25 | for (col = 0; col < n; col++) { 26 | if (col == 0) buf[col] = buf[col] + grid[row][col]; 27 | else buf[col] = min(buf[col-1], buf[col]) + grid[row][col]; 28 | } 29 | } 30 | 31 | return buf[n-1]; 32 | } 33 | 34 | private: 35 | int min(int a, int b) { 36 | return (a <= b) ? a : b; 37 | } 38 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/PalindromeNumber.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Palindrome Number 3 | * Determine whether an integer is a palindrome. Do this without extra space. 4 | * 5 | * click to show spoilers. 6 | * 7 | * Some hints: 8 | * Could negative integers be palindromes? (ie, -1) 9 | * 10 | * If you are thinking of converting the integer to string, note the restriction of using extra space. 11 | * 12 | * You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case? 13 | * 14 | * There is a more generic way of solving this problem. 15 | */ 16 | 17 | 18 | class Solution { 19 | public: 20 | bool isPalindrome(int x) { 21 | if (x < 0) return false; 22 | 23 | int factor = 1, head ,tail ; 24 | while (x / factor >= 10) factor *= 10; 25 | 26 | while (x > 0) { // spolier: 10000021 27 | head = x / factor; 28 | tail = x % 10; 29 | if (head != tail) return false; 30 | x = x % factor; //delete head 31 | x = x / 10; //delete tail 32 | factor /= 100; 33 | } 34 | 35 | return true; 36 | } 37 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/PascalsTriangle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Pascal's Triangle (Yanghui's Triangle) 3 | * Given numRows, generate the first numRows of Pascal's triangle. 4 | */ 5 | 6 | 7 | class Solution { 8 | public: 9 | vector > generate(int numRows) { 10 | vector > result; 11 | int i, j; 12 | 13 | if (numRows == 0) return result; 14 | result.push_back(vector (1, 1)); 15 | for (i = 2; i <= numRows; i++) { 16 | vector &prev = result[(i-1) - 1]; 17 | vector item(i, 1); 18 | for (j = 1; j < i - 1; j++) { 19 | item[j] = prev[j-1] + prev[j]; 20 | } 21 | result.push_back(item); 22 | } 23 | 24 | return result; 25 | } 26 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/PathSum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Path Sum 3 | * Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. 4 | */ 5 | 6 | 7 | /** 8 | * Definition for binary tree 9 | * struct TreeNode { 10 | * int val; 11 | * TreeNode *left; 12 | * TreeNode *right; 13 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 14 | * }; 15 | */ 16 | 17 | // recursive 18 | class Solution { 19 | public: 20 | bool hasPathSum(TreeNode *root, int sum) { 21 | if (root == NULL) return false; 22 | if (root->left == NULL && root->right == NULL) return root->val == sum; 23 | 24 | return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val); 25 | } 26 | }; 27 | 28 | -------------------------------------------------------------------------------- /leetcode/C&C++/easy/PlusOne.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Plus One 3 | * Given a non-negative number represented as an array of digits, plus one to the number. 4 | * 5 | * The digits are stored such that the most significant digit is at the head of the list. 6 | */ 7 | 8 | 9 | class Solution { 10 | public: 11 | vector plusOne(vector &digits) { 12 | int carry = 1; 13 | int i, size, current; 14 | size = digits.size(); 15 | 16 | for (i = size - 1; i >= 0; i--) { 17 | current = digits[i] + carry; 18 | carry = current/10; 19 | digits[i] = current%10; 20 | } 21 | if (carry > 0) { 22 | digits.insert(digits.begin(), carry); 23 | } 24 | 25 | return digits; 26 | } 27 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/PopulatingNextRightPointersinEachNode.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Populating Next Right Pointers in Each Node 3 | * Given a binary tree 4 | * 5 | * struct TreeLinkNode { 6 | * TreeLinkNode *left; 7 | * TreeLinkNode *right; 8 | * TreeLinkNode *next; 9 | * } 10 | * 11 | * Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. 12 | * Initially, all next pointers are set to NULL. 13 | */ 14 | 15 | 16 | /** 17 | * Definition for binary tree with next pointer. 18 | * struct TreeLinkNode { 19 | * int val; 20 | * TreeLinkNode *left, *right, *next; 21 | * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} 22 | * }; 23 | */ 24 | class Solution { 25 | public: 26 | void connect(TreeLinkNode *root) { 27 | TreeLinkNode *cur = root; 28 | 29 | while (cur) { 30 | TreeLinkNode *first = NULL; // the first node of next level 31 | TreeLinkNode *prev = NULL; // previous node on the same level; 32 | 33 | // connect nodes which in the same level with cur 34 | for (; cur; cur = cur->next) { 35 | if (!first) first = cur->left ? cur->left : cur->right; 36 | 37 | if (cur->left) { 38 | if (prev) prev->next = cur->left; 39 | prev = cur->left; 40 | } 41 | if (cur->right) { 42 | if (prev) prev->next = cur->right; 43 | prev = cur->right; 44 | } 45 | } 46 | 47 | // go to the next level 48 | cur = first; 49 | } 50 | } 51 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/README: -------------------------------------------------------------------------------- 1 | Easy 2 | AC rate: [30%, 100%] 3 | 4 | -------------------------------------------------------------------------------- /leetcode/C&C++/easy/RemoveDuplicatesfromSortedArray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Remove Duplicates from Sorted Array 3 | * Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. 4 | * 5 | * Do not allocate extra space for another array, you must do this in place with constant memory. 6 | */ 7 | 8 | 9 | class Solution { 10 | public: 11 | int removeDuplicates(int A[], int n) { 12 | int i, j; 13 | if (n <= 1) return n; 14 | 15 | for (i = 0, j = 1; j < n; j++) { 16 | if (A[j] != A[i]) { 17 | i++; 18 | A[i] = A[j]; 19 | } 20 | } 21 | 22 | return i+1; 23 | } 24 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/RemoveDuplicatesfromSortedArrayII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Remove Duplicates from Sorted Array II 3 | * Follow up for "Remove Duplicates": 4 | * What if duplicates are allowed at most twice? 5 | * 6 | * For example, 7 | * Given sorted array A = [1,1,1,2,2,3], 8 | * 9 | * Your function should return length = 5, and A is now [1,1,2,2,3]. 10 | */ 11 | 12 | 13 | class Solution { 14 | public: 15 | int removeDuplicates(int A[], int n) { 16 | int flag, count; 17 | int len, i; 18 | if (n <= 2) return n; 19 | flag = A[0]; 20 | count = 0; 21 | len = 0; 22 | for (i = 0; i < n; i++) { 23 | if (A[i] == flag) { 24 | count++; 25 | } else { 26 | flag = A[i]; 27 | count = 1; 28 | } 29 | 30 | if (count <= 2) { 31 | A[len++] = A[i]; 32 | } 33 | } 34 | 35 | return len; 36 | } 37 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/RemoveDuplicatesfromSortedList.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Remove Duplicates from Sorted List 3 | * Given a sorted linked list, delete all duplicates such that each element appear only once. 4 | */ 5 | 6 | 7 | /** 8 | * Definition for singly-linked list. 9 | * struct ListNode { 10 | * int val; 11 | * ListNode *next; 12 | * ListNode(int x) : val(x), next(NULL) {} 13 | * }; 14 | */ 15 | class Solution { 16 | public: 17 | ListNode *deleteDuplicates(ListNode *head) { 18 | ListNode *p, *q; 19 | p = head; 20 | while (p && p->next) { 21 | q = p->next; 22 | if (q->val == p->val) { 23 | p->next = q->next; 24 | free(q); 25 | } else { 26 | p = p->next; 27 | } 28 | } 29 | return head; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /leetcode/C&C++/easy/RemoveElement.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Remove Element 3 | * Given an array and a value, remove all instances of that value in place and return the new length. 4 | * 5 | * The order of elements can be changed. It doesn't matter what you leave beyond the new length. 6 | */ 7 | 8 | 9 | class Solution { 10 | public: 11 | int removeElement(int A[], int n, int elem) { 12 | int i, len, tmp; 13 | 14 | for (i = 0, len = n; i < len; i++) { 15 | if (A[i] == elem) { 16 | while(len > 0 && A[len - 1] == elem) { 17 | len--; 18 | } 19 | if (i < len) { 20 | tmp = A[i]; 21 | A[i] = A[len-1]; 22 | A[len-1] = tmp; 23 | len--; 24 | } 25 | } 26 | } 27 | 28 | return len; 29 | } 30 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/RemoveNthNodeFromEndofList.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Remove Nth Node From End of List 3 | * Given a linked list, remove the nth node from the end of list and return its head. 4 | * 5 | * For example, 6 | * 7 | * Given linked list: 1->2->3->4->5, and n = 2. 8 | * 9 | * After removing the second node from the end, the linked list becomes 1->2->3->5. 10 | * Note: 11 | * Given n will always be valid. 12 | * Try to do this in one pass. 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 | public: 26 | ListNode *removeNthFromEnd(ListNode *head, int n) { 27 | ListNode *p, *q; 28 | ListNode tmp(0); // Notice the way to declare new node 29 | tmp.next = head; 30 | p = q = &tmp; 31 | int i; 32 | 33 | // move q by n steps 34 | for (i = 0; i < n; i++) { 35 | q = q->next; 36 | } 37 | // find the node *before* the node to remove 38 | while (q->next != NULL) { 39 | p = p->next; 40 | q = q->next; 41 | } 42 | 43 | q = p->next; 44 | p->next = q->next; 45 | free(q); 46 | 47 | return tmp.next; 48 | } 49 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/ReverseInteger.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Reverse Integer 3 | * Reverse digits of an integer 4 | */ 5 | 6 | 7 | class Solution { 8 | public: 9 | int reverse(int x) { 10 | int abs_x, flag, result = 0; 11 | int of_check; // overflow check 12 | 13 | if (x >= 0) { 14 | abs_x = x; 15 | flag = 0; 16 | } else { 17 | abs_x = -x; 18 | flag = 1; 19 | } 20 | 21 | while(abs_x > 0) { 22 | of_check = result * 10; 23 | if (of_check < 0) return -1; 24 | 25 | result = of_check + abs_x%10; 26 | abs_x = abs_x/10; 27 | } 28 | 29 | if (flag == 1) { 30 | of_check = -result; 31 | if (of_check >= 0) return -1; 32 | 33 | result = of_check; 34 | } 35 | 36 | return result; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /leetcode/C&C++/easy/RomaintoInteger.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Roman to Integer 3 | * Given a roman numeral, convert it to an integer. 4 | * 5 | * Input is guaranteed to be within the range from 1 to 3999. 6 | */ 7 | 8 | // This is boring, by the way. 9 | class Solution { 10 | public: 11 | int map(char c) { 12 | switch(c) { 13 | case 'I': return 1; 14 | case 'V': return 5; 15 | case 'X': return 10; 16 | case 'L': return 50; 17 | case 'C': return 100; 18 | case 'D': return 500; 19 | case 'M': return 1000; 20 | default: return 0; 21 | } 22 | } 23 | 24 | int romanToInt(string s) { 25 | int i, result = 0; 26 | 27 | for (i = 0; i < s.size(); i++) { 28 | if (i > 0 && map(s[i]) > map(s[i-1])) { 29 | result += ((map(s[i]) - map(s[i-1])) - map(s[i-1])); 30 | } else { 31 | result += map(s[i]); 32 | } 33 | } 34 | 35 | return result; 36 | } 37 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/RotateImage.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Rotate Image 3 | * You are given an n x n 2D matrix representing an image. 4 | * 5 | * Rotate the image by 90 degrees (clockwise). 6 | * 7 | * Follow up: 8 | * Could you do this in-place? 9 | */ 10 | 11 | 12 | class Solution { 13 | public: 14 | void rotate(vector > &matrix) { 15 | int i, j, n; 16 | int tmp; 17 | 18 | n = matrix.size(); 19 | // transposition 20 | for (i = 0; i < n; i++) { 21 | for (j = 0; j < i; j++) { 22 | tmp = matrix[i][j]; 23 | matrix[i][j] = matrix[j][i]; 24 | matrix[j][i] = tmp; 25 | } 26 | } 27 | 28 | // reverse 29 | for (j = 0; j < n/2; j++) { 30 | for (i = 0; i < n; i++) { 31 | tmp = matrix[i][j]; 32 | matrix[i][j] = matrix[i][n-j-1]; 33 | matrix[i][n-j-1] = tmp; 34 | } 35 | } 36 | } 37 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/SameTree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Same Tree 3 | * Given two binary trees, write a function to check if they are equal or not. 4 | * 5 | * Two binary trees are considered equal if they are structurally identical and the nodes have the same value. 6 | */ 7 | 8 | 9 | /** 10 | * Definition for binary tree 11 | * struct TreeNode { 12 | * int val; 13 | * TreeNode *left; 14 | * TreeNode *right; 15 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 16 | * }; 17 | */ 18 | class Solution { 19 | public: 20 | bool isSameTree(TreeNode *p, TreeNode *q) { 21 | if (p == NULL && q == NULL) return true; 22 | else if (p == NULL) return false; 23 | else if (q == NULL) return false; 24 | else if (p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right)) { 25 | return true; 26 | } 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /leetcode/C&C++/easy/SearchInsertPosition.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Search Insert Position 3 | * Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. 4 | * 5 | * You may assume no duplicates in the array. 6 | */ 7 | 8 | 9 | class Solution { 10 | public: 11 | int searchInsert(int A[], int n, int target) { 12 | int begin, middle, end; 13 | begin = 0; 14 | end = n; 15 | middle = (begin + end)/2; 16 | while (begin < end && A[middle] != target) { 17 | if (A[middle] < target) { 18 | begin = middle + 1; 19 | middle = (begin + end)/2; 20 | } else { 21 | end = middle; 22 | middle = (begin + end)/2; 23 | } 24 | } 25 | return middle; 26 | } 27 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/Searcha2DMatrix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Search a 2D Matrix 3 | * Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 4 | * 5 | * Integers in each row are sorted from left to right. 6 | * The first integer of each row is greater than the last integer of the previous row. 7 | */ 8 | 9 | 10 | class Solution { 11 | public: 12 | bool searchMatrix(vector > &matrix, int target) { 13 | if (matrix.empty()) return false; 14 | int m = matrix.size(), n = matrix[0].size(); 15 | int from = 0, to = m * n, mid; 16 | 17 | while (from < to) { 18 | mid = (from + to)/2; 19 | if (matrix[mid/n][mid%n] == target) { 20 | return true; 21 | } else if (matrix[mid/n][mid%n] > target) { 22 | to = mid; 23 | } else { 24 | from = mid + 1; 25 | } 26 | } 27 | 28 | return false; 29 | } 30 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/SearchforaRange.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Search for a Range 3 | * Given a sorted array of integers, find the starting and ending position of a given target value. 4 | * 5 | * Your algorithm's runtime complexity must be in the order of O(log n). 6 | * 7 | * If the target is not found in the array, return [-1, -1]. 8 | * 9 | * For example, 10 | * Given [5, 7, 7, 8, 8, 10] and target value 8, 11 | * return [3, 4]. 12 | */ 13 | 14 | 15 | class Solution { 16 | public: 17 | vector searchRange(int A[], int n, int target) { 18 | vector result(2, -1); 19 | 20 | // find the leftest one 21 | int from = 0, to = n, mid; 22 | while(from < to) { 23 | mid = from + (to - from)/2; 24 | if (target == A[mid]) { 25 | result[0] = mid; 26 | } 27 | 28 | if (target <= A[mid]) { 29 | to = mid; 30 | } else { 31 | from = mid + 1; 32 | } 33 | } 34 | 35 | if (result[0] == -1) { 36 | return result; 37 | } else { 38 | result[1] = result[0]; 39 | } 40 | 41 | // fint the rightest one 42 | from = result[0] + 1; to = n; 43 | while (from < to) { 44 | mid = from + (to - from)/2; 45 | if (target == A[mid]) { 46 | result[1] = mid; 47 | } 48 | 49 | if (target < A[mid]) { 50 | to = mid; 51 | } else { 52 | from = mid + 1; 53 | } 54 | } 55 | 56 | return result; 57 | } 58 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/SetMatrixZeroes.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Set Matrix Zeroes 3 | * Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. 4 | */ 5 | 6 | 7 | class Solution { 8 | public: 9 | void setZeroes(vector > &matrix) { 10 | if (matrix.empty()) return; 11 | int m = matrix.size(); 12 | int n = matrix[0].size(); 13 | int flag_fr = 0, flag_fc = 0; // flag for the first row and colomn 14 | int i, j; 15 | 16 | // init flag for the first col and row 17 | for (i = 0; i < m; i++) { 18 | if (matrix[i][0] == 0) { 19 | flag_fc = 1; 20 | break; 21 | } 22 | } 23 | for (j = 0; j < n; j++) { 24 | if (matrix[0][j] == 0) { 25 | flag_fr = 1; 26 | break; 27 | } 28 | } 29 | 30 | // use the first col and row as bitmap 31 | for (i = 1; i < m; i++) { 32 | for (j = 1; j < n; j++) { 33 | if (matrix[i][j] == 0) { 34 | matrix[0][j] = 0; 35 | matrix[i][0] = 0; 36 | } 37 | } 38 | } 39 | 40 | // set matrix by first col and first row 41 | for (i = 1; i < m; i++) { 42 | if (matrix[i][0] == 0) { 43 | for (j = 1; j < n; j++) { 44 | matrix[i][j] = 0; 45 | } 46 | } 47 | } 48 | for (j = 1; j < n; j++) { 49 | if (matrix[0][j] == 0) { 50 | for (i = 1; i < m; i++) { 51 | matrix[i][j] = 0; 52 | } 53 | } 54 | } 55 | 56 | if (flag_fc == 1) { 57 | for (i = 0; i < m; i++) { 58 | matrix[i][0] = 0; 59 | } 60 | } 61 | if (flag_fr == 1) { 62 | for (j = 0; j < n; j++) { 63 | matrix[0][j] = 0; 64 | } 65 | } 66 | } 67 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/SingleNumber.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Single Number 3 | * Given an array of integers, every element appears twice except for one. Find that single one. 4 | */ 5 | 6 | 7 | class Solution { 8 | public: 9 | int singleNumber(int A[], int n) { 10 | int result = 0, i; 11 | 12 | for (i = 0; i < n; i++) { 13 | result = result ^ A[i]; 14 | } 15 | 16 | return result; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /leetcode/C&C++/easy/SingleNumberII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Single Number II 3 | * Given an array of integers, every element appears three times except for one. Find that single one. 4 | * 5 | * Note: 6 | * Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 7 | */ 8 | 9 | 10 | class Solution { 11 | public: 12 | int singleNumber(int A[], int n) { 13 | int sum_bits[32] = {0}; 14 | int i, j, flag, result; 15 | int size = sizeof(int); 16 | 17 | for (i = 0; i < n; i++) { 18 | for (j = 0; j < size*8; j++) { 19 | flag = A[i] & (1 << j); 20 | if (flag) { 21 | sum_bits[j] = (sum_bits[j] + 1)%3; 22 | } 23 | } 24 | } 25 | 26 | result = 0; 27 | for (j = size*8 - 1; j >= 0; j--) { 28 | result = (result << 1) | sum_bits[j]; 29 | } 30 | 31 | return result; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /leetcode/C&C++/easy/SortColors.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Sort Colors 3 | * Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. 4 | * 5 | * Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. 6 | */ 7 | 8 | 9 | class Solution_1 { 10 | public: 11 | void sortColors(int A[], int n) { 12 | int count[3] = {0}; 13 | int index = 0; 14 | int i, j; 15 | 16 | for (i = 0; i < n; i++) { 17 | count[A[i]]++; 18 | } 19 | 20 | for (i = 0; i < 3; i++) { 21 | for (j = 0; j < count[i]; j++) { 22 | A[index++] = i; 23 | } 24 | } 25 | } 26 | }; 27 | 28 | 29 | class Solution_2 { 30 | public: 31 | void sortColors(int A[], int n) { 32 | int red = 0, blue = n - 1; 33 | int i, tmp; 34 | 35 | for (i = 0; i < blue + 1;) { 36 | if (A[i] == 0) { 37 | A[i++] = A[red]; 38 | A[red++] = 0; 39 | } else if (A[i] == 2) { 40 | A[i] = A[blue]; 41 | A[blue--] = 2; 42 | } else { 43 | i++; 44 | } 45 | } 46 | } 47 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/SumRoottoLeafNumbers.cpp: -------------------------------------------------------------------------------- 1 | /* Sum Root to Leaf Numbers 2 | * Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. 3 | * 4 | * An example is the root-to-leaf path 1->2->3 which represents the number 123. 5 | * 6 | * Find the total sum of all root-to-leaf numbers. 7 | */ 8 | 9 | 10 | /** 11 | * Definition for binary tree 12 | * struct TreeNode { 13 | * int val; 14 | * TreeNode *left; 15 | * TreeNode *right; 16 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | int sumNumbers(TreeNode *root) { 22 | return dfs(root, 0); 23 | } 24 | 25 | private: 26 | int dfs(TreeNode *root, int sum) { 27 | int result; 28 | 29 | if (root == NULL) return 0; 30 | 31 | result = sum * 10 + root->val; 32 | if (root->left == NULL && root->right == NULL) return result; 33 | return dfs(root->left, result) + dfs(root->right, result); 34 | } 35 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/SwapNodesinPairs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Swap Nodes in Pairs 3 | * Given a linked list, swap every two adjacent nodes and return its head. 4 | * 5 | * For example, 6 | * Given 1->2->3->4, you should return the list as 2->1->4->3. 7 | * 8 | * Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. 9 | */ 10 | 11 | 12 | /** 13 | * Definition for singly-linked list. 14 | * struct ListNode { 15 | * int val; 16 | * ListNode *next; 17 | * ListNode(int x) : val(x), next(NULL) {} 18 | * }; 19 | */ 20 | class Solution { 21 | public: 22 | ListNode *swapPairs(ListNode *head) { 23 | ListNode *p, *q, *left, *h, *prev = NULL; 24 | h = left = head; 25 | while (left && left->next) { 26 | if (left == head) h = left->next; 27 | p = left; 28 | q = left->next; 29 | left = left->next->next; 30 | 31 | p->next = q->next; 32 | q->next = p; 33 | if (prev) { 34 | prev->next = q; 35 | } 36 | prev = p; 37 | } 38 | return h; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /leetcode/C&C++/easy/SymmetricTree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Symmetric Tree 3 | * Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). 4 | */ 5 | 6 | 7 | /** 8 | * Definition for binary tree 9 | * struct TreeNode { 10 | * int val; 11 | * TreeNode *left; 12 | * TreeNode *right; 13 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 14 | * }; 15 | */ 16 | class Solution { 17 | public: 18 | bool isMirror(TreeNode *l, TreeNode *r) 19 | { 20 | if (l == NULL && r == NULL) return true; 21 | else if (l == NULL || r == NULL) return false; 22 | else return (l->val == r->val)&&isMirror(l->left, r->right)&&isMirror(l->right, r->left); 23 | } 24 | 25 | bool isSymmetric(TreeNode *root) { 26 | if (root == NULL) return true; 27 | 28 | return isMirror(root->left, root->right); 29 | } 30 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/UniqueBinarySearchTrees.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Unique Binary Search Trees 3 | * Given n, how many structurally unique BST's (binary search trees) that store values 1...n? 4 | */ 5 | 6 | // Of course, this can be improved by dynamic programing. 7 | class Solution { 8 | public: 9 | int numTrees(int n) { 10 | int i, cnt = 0; 11 | if (n == 0 || n == 1) return 1; 12 | for (i = 0; i < n; i++) { 13 | cnt += numTrees(i)*numTrees(n-i-1); 14 | } 15 | 16 | return cnt; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /leetcode/C&C++/easy/UniquePaths.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Unique Paths 3 | * A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). 4 | * 5 | * The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). 6 | * 7 | * How many possible unique paths are there? 8 | */ 9 | 10 | 11 | class Solution { 12 | private: 13 | vector > buf; 14 | 15 | public: 16 | 17 | /* Method one: Memo 18 | int uniquePaths(int m, int n) { 19 | this->buf = vector >(m+1, vector(n+1, 0)); 20 | return dfs(m, n); 21 | } 22 | 23 | int dfs(int m, int n) { 24 | if (m == 1 || n == 1) return 1; 25 | if (buf[m][n] > 0) return buf[m][n]; 26 | 27 | if (buf[m-1][n] == 0) buf[m-1][n] = dfs(m-1, n); 28 | if (buf[m][n-1] == 0) buf[m][n-1] = dfs(m, n-1); 29 | return buf[m][n] = buf[m-1][n] + buf[m][n-1]; 30 | } 31 | */ 32 | int uniquePaths(int m, int n) { 33 | vector buf(n, 0); 34 | buf[0] = 1; 35 | 36 | for (int i = 0; i < m; i++) { 37 | for (int j = 1; j < n; j++) { 38 | buf[j] = buf[j-1] + buf[j]; 39 | } 40 | } 41 | 42 | return buf[n-1]; 43 | } 44 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/easy/ValidParentheses.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Valid Parentheses 3 | * Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 4 | * 5 | * The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. 6 | */ 7 | 8 | 9 | class Solution { 10 | public: 11 | bool isValid(string s) { 12 | stack s1; 13 | map mapper = {{'}', '{'}, {']', '['}, {')', '('}}; 14 | int len = s.length(), i; 15 | 16 | if (len == 0) return true; 17 | for (i = 0; i < len; i++) { 18 | if (s[i] == '[' || s[i] == '(' || s[i] == '{') { 19 | s1.push(s[i]); 20 | } else if (!s1.empty() && mapper[s[i]] == s1.top()) { 21 | s1.pop(); 22 | } else { 23 | return false; 24 | } 25 | } 26 | 27 | if (s1.empty()) { 28 | return true; 29 | } else { 30 | return false; 31 | } 32 | } 33 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/hard/3Sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3Sum 3 | * Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. 4 | * 5 | * Note: 6 | * Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) 7 | * The solution set must not contain duplicate triplets. 8 | * For example, given array S = {-1 0 1 2 -1 -4}, 9 | * 10 | * A solution set is: 11 | * (-1, 0, 1) 12 | * (-1, -1, 2) 13 | */ 14 | 15 | 16 | class Solution { 17 | public: 18 | vector > threeSum(vector &num) { 19 | vector > result; 20 | int target = 0; 21 | if (num.size() < 3) return result; 22 | sort(num.begin(), num.end()); 23 | 24 | for (int a = 0; a < num.size() - 2; a++) { 25 | int b = a+1; 26 | int c = num.size()-1; 27 | while (b < c) { 28 | int tmp = num[a] + num[b] + num[c]; 29 | if (tmp == target) { 30 | vector tmp; 31 | tmp.push_back(num[a]); 32 | tmp.push_back(num[b]); 33 | tmp.push_back(num[c]); 34 | result.push_back(tmp); 35 | b++; 36 | c--; 37 | } else if (tmp < target) { 38 | b++; 39 | } else if (tmp > target) { 40 | c--; 41 | } 42 | } 43 | } 44 | sort(result.begin(), result.end()); 45 | auto it = unique(result.begin(), result.end()); 46 | result.resize(distance(result.begin(), it)); 47 | return result; 48 | } 49 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/hard/BinaryTreeMaximumPathSum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Binary Tree Maximum Path Sum 3 | * Given a binary tree, find the maximum path sum. 4 | * 5 | * The path may start and end at any node in the tree. 6 | */ 7 | 8 | 9 | /** 10 | * Definition for binary tree 11 | * struct TreeNode { 12 | * int val; 13 | * TreeNode *left; 14 | * TreeNode *right; 15 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 16 | * }; 17 | */ 18 | class Solution { 19 | public: 20 | int maxPathSum(TreeNode *root) { 21 | int result = INT_MIN; 22 | 23 | dfs(root, result); 24 | return result; 25 | } 26 | private: 27 | // return value represents the maximum sum path which starts from root 28 | int dfs(TreeNode *root, int &result) { 29 | if (root == NULL) return 0; 30 | int l = dfs(root->left, result); 31 | int r = dfs(root->right, result); 32 | int sum = root->val; 33 | 34 | sum += max(max(l, r), 0); 35 | result = max(result, root->val + max(l, 0) + max(r, 0)); 36 | 37 | return sum; 38 | } 39 | 40 | int max(int a, int b) { 41 | return a > b ? a : b; 42 | } 43 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/hard/Candy.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Candy 3 | * There are N children standing in a line. Each child is assigned a rating value. 4 | * 5 | * You are giving candies to these children subjected to the following requirements: 6 | * 7 | * Each child must have at least one candy. 8 | * Children with a higher rating get more candies than their neighbors. 9 | * What is the minimum candies you must give? 10 | */ 11 | 12 | 13 | class Solution { 14 | public: 15 | int candy(vector &ratings) { 16 | const int n = ratings.size(); 17 | if (n < 2) return n; 18 | vector dis(n, 1); // distribution 19 | 20 | // scan from left 21 | for (int i = 1; i < n; i++) { 22 | if (ratings[i] > ratings[i-1]) { 23 | dis[i] = max(dis[i], dis[i-1] + 1); 24 | } 25 | // if ratings[i] == ratings[i-1] 26 | // both dis[i] >= dis[i-1] and dis[i] < dis[i-1] is OK! 27 | } 28 | // scan from right 29 | for (int i = n-2; i >= 0; i--) { 30 | if (ratings[i] > ratings[i+1]) { 31 | dis[i] = max(dis[i], dis[i+1] + 1); 32 | } 33 | } 34 | 35 | int sum = 0; 36 | for (int i = 0; i < n; i++) { 37 | sum += dis[i]; 38 | } 39 | 40 | return sum; 41 | } 42 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/hard/DivideTwoIntegers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Divide Two Integers 3 | * Divide two integers without using multiplication, division and mod operator. 4 | */ 5 | 6 | // Note: 1. try to double divisor to accelerate the algorithm 7 | // Be careful with overflow 8 | 9 | class Solution { 10 | public: 11 | int divide(int dividend, int divisor) { 12 | int result = 0; 13 | bool sign(false); // sign == false represent positive 14 | if ((dividend > 0) ^ (divisor > 0)) sign = true; 15 | 16 | unsigned int undividend = abs((long long)dividend); 17 | unsigned int undivisor = abs((long long)divisor); 18 | 19 | while (undividend >= undivisor) { 20 | unsigned int new_undivisor = undivisor; 21 | int multi = 1; 22 | while (undividend >= new_undivisor) { 23 | undividend -= new_undivisor; 24 | result += multi; 25 | 26 | if (new_undivisor < INT_MAX >> 1) { 27 | multi <<= 1; 28 | new_undivisor <<= 1; 29 | } 30 | } 31 | } 32 | 33 | return sign ? (0 - result) : result; 34 | } 35 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/hard/InterleavingString.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Interleaving String 3 | * Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. 4 | * 5 | * For example, 6 | * Given: 7 | * s1 = "aabcc", 8 | * s2 = "dbbca", 9 | * 10 | * When s3 = "aadbbcbcac", return true. 11 | * When s3 = "aadbbbaccc", return false. 12 | */ 13 | 14 | 15 | class Solution { 16 | public: 17 | bool isInterleave(string s1, string s2, string s3) { 18 | if (s3.size() != s1.size() + s2.size()) return false; 19 | //if (s1.size() == 0) return s2 == s3; 20 | //if (s2.size() == 0) return s1 == s3; 21 | 22 | vector match(s2.size()+1, false); 23 | 24 | match[0] = true; 25 | for (int k2 = 1; k2 <= s2.size(); k2++) { 26 | match[k2] = (match[k2-1] && s2[k2-1] == s3[k2-1]); 27 | } 28 | 29 | for (int k1 = 1; k1 <= s1.size(); k1++) { 30 | match[0] = (match[0] && s1[k1-1] == s3[k1-1]); 31 | for (int k2 = 1; k2 <= s2.size(); k2++) { 32 | match[k2] = (s1[k1-1] == s3[k1+k2-1] && match[k2]) || (s2[k2-1] == s3[k1+k2-1] && match[k2-1]); 33 | } 34 | } 35 | 36 | return match[s2.size()]; 37 | } 38 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/hard/LongestPalindromicSubstring.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Longest Palindromic Substring 3 | * Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring. 4 | */ 5 | 6 | // DP 7 | class Solution_1 { 8 | public: 9 | string longestPalindrome(string s) { 10 | int n = s.size(); 11 | bool f[n][n]; // f[i][j] == true represents [i, j] is palindrome 12 | fill_n(&f[0][0], n*n, false); 13 | if (n < 2) return s; 14 | 15 | int max = 1, start = 0; 16 | for (int i = 0; i < n; i++) { 17 | f[i][i] = true; 18 | for (int j = i-1; j >= 0; j--) { // [j, i] 19 | f[j][i] = (s[j] == s[i] && (i-j < 2 || f[j+1][i-1])) ; 20 | if (f[j][i] && max < (i-j+1)) { 21 | max = i-j+1; 22 | start = j; 23 | } 24 | } 25 | } 26 | 27 | return s.substr(start, max); 28 | } 29 | }; 30 | 31 | // TODO: manacher 32 | -------------------------------------------------------------------------------- /leetcode/C&C++/hard/LongestValidParentheses.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Longest Valid Parentheses 3 | * Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. 4 | * 5 | * For "(()", the longest valid parentheses substring is "()", which has length = 2. 6 | * 7 | * Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4. 8 | */ 9 | 10 | 11 | class Solution { 12 | public: 13 | int longestValidParentheses(string s) { 14 | stack stk; // the position of the last non-matched '(' 15 | int len = 0, last = -1; // the position of the last non-matched ')' 16 | int result = 0; 17 | 18 | //stk.push(0); 19 | for (int i = 0; i < s.size(); i++) { 20 | if (s[i] == '(') { 21 | stk.push(i); 22 | } else if (s[i] == ')' && stk.empty()) { 23 | last = i; // found a non-matched ')', therefore the begin of valid parentheses start from here 24 | } else if (s[i] == ')' && !stk.empty()) { 25 | stk.pop(); 26 | if (stk.empty()) len = i - last; 27 | else len = i - stk.top(); 28 | if (len > result) result = len; 29 | } 30 | } 31 | 32 | return result; 33 | } 34 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/hard/MaxPointsonaLine.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Max Points on a Line 3 | * Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. 4 | */ 5 | 6 | 7 | /** 8 | * Definition for a point. 9 | * struct Point { 10 | * int x; 11 | * int y; 12 | * Point() : x(0), y(0) {} 13 | * Point(int a, int b) : x(a), y(b) {} 14 | * }; 15 | */ 16 | class Solution { 17 | public: 18 | int maxPoints(vector &points) { 19 | if (points.size() < 3) return points.size(); 20 | int result = 0; 21 | unordered_map slope_count; 22 | 23 | int same = 0; // number of points at the same position 24 | int count = 0; // number of points in the same line with some slope 25 | int max_count = 1; // maximum of count 26 | for (int i = 0; i < points.size(); i++) { 27 | slope_count.clear(); 28 | 29 | same = 0; 30 | max_count = 1; 31 | for (int j = i+1; j < points.size(); j++) { 32 | double slope; 33 | if (points[i].x == points[j].x && points[i].y == points[j].y) { 34 | same++; 35 | continue; 36 | } 37 | 38 | if (points[i].x == points[j].x) { 39 | slope = numeric_limits::infinity(); 40 | } else { 41 | slope = 1.0 * (points[j].y - points[i].y) / (points[j].x - points[i].x); 42 | } 43 | 44 | count = 0; 45 | if (slope_count.find(slope) != slope_count.end()) { 46 | count = ++slope_count[slope]; 47 | } else { 48 | count = 2; 49 | slope_count[slope] = 2; 50 | } 51 | if (max_count < count) max_count = count; 52 | } 53 | if (max_count + same > result) result = max_count + same; 54 | } 55 | 56 | return result; 57 | } 58 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/hard/MedianofTwoSortedArrays.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Median of Two Sorted Arrays 3 | * There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). 4 | */ 5 | 6 | 7 | class Solution { 8 | public: 9 | double findMedianSortedArrays(int A[], int m, int B[], int n) { 10 | int total = m + n; 11 | if (total % 2 == 0) { 12 | return (findkth(A, m, B, n, total/2) + findkth(A, m, B, n, total/2+1)) / 2.0; 13 | } else { 14 | return findkth(A, m, B, n, total/2+1); 15 | } 16 | } 17 | 18 | private: 19 | int findkth(int A[], int m, int B[], int n, int k) { 20 | if (m > n) return findkth(B, n, A, m, k); 21 | if (m == 0) return B[k-1]; 22 | if (k == 1) return min(A[0], B[0]); 23 | 24 | // divide k into two parts 25 | int mida = min(k/2, m); 26 | int midb = k - mida; 27 | if (A[mida - 1] < B[midb - 1]) { 28 | return findkth(A+mida, m-mida, B, n, k-mida); 29 | } else if (A[mida - 1] > B[midb - 1]) { 30 | return findkth(A, m, B+midb, n-midb, k-midb); 31 | } else { 32 | return A[mida - 1]; 33 | } 34 | } 35 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/hard/PalindromePartitioningII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Palindrome Partitioning II 3 | * Given a string s, partition s such that every substring of the partition is a palindrome. 4 | * 5 | * Return the minimum cuts needed for a palindrome partitioning of s. 6 | * 7 | * For example, given s = "aab", 8 | * Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut. 9 | */ 10 | 11 | 12 | class Solution { 13 | public: 14 | int minCut(string s) { 15 | const int N = s.length(); 16 | if (N < 2) return 0; 17 | 18 | int cuts[N]; // cuts[i] is minmum cuts for [0, i] 19 | bool palin[N][N]; 20 | for (int i = 0; i < N; i++) { 21 | cuts[i] = i; // worst case 22 | for (int j = 0; j < N; j++) { 23 | palin[i][j] = false; 24 | } 25 | } 26 | 27 | for (int i = 0; i < N; i++) { 28 | for (int j = i; j >= 0; j--) { 29 | // if [j, i] is palindrome 30 | if ((s[j] == s[i]) && (i - j < 2 || palin[j+1][i-1])) { 31 | palin[j][i] = true; 32 | if (j == 0) cuts[i] = 0; 33 | else cuts[i] = min(cuts[i], cuts[j-1] + 1); 34 | } 35 | } 36 | } 37 | 38 | return cuts[N-1]; 39 | } 40 | 41 | private: 42 | int min (int a, int b) { 43 | return a <= b ? a : b; 44 | } 45 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/hard/README: -------------------------------------------------------------------------------- 1 | Hard 2 | AC rates: [10%, 20) 3 | 4 | -------------------------------------------------------------------------------- /leetcode/C&C++/hard/RegularExpressionMatching.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Regular Expression Matching 3 | * Implement regular expression matching with support for '.' and '*'. 4 | * 5 | * '.' Matches any single character. 6 | * '*' Matches zero or more of the preceding element. 7 | * 8 | * The matching should cover the entire input string (not partial). 9 | * 10 | * The function prototype should be: 11 | * bool isMatch(const char *s, const char *p) 12 | * 13 | * Some examples: 14 | * isMatch("aa","a") → false 15 | * isMatch("aa","aa") → true 16 | * isMatch("aaa","aa") → false 17 | * isMatch("aa", "a*") → true 18 | * isMatch("aa", ".*") → true 19 | * isMatch("ab", ".*") → true 20 | * isMatch("aab", "c*a*b") → true 21 | */ 22 | 23 | 24 | class Solution { 25 | public: 26 | bool isMatch(const char *s, const char *p) { 27 | if (*p == '\0') return *s == '\0'; 28 | 29 | // next char is not '*' 30 | if (*(p+1) != '*') { 31 | if (*s == *p || (*p == '.' && *s != '\0')) return isMatch(s+1, p+1); 32 | else return false; 33 | } else { 34 | while (*s == *p || (*p == '.' && *s != '\0')) { 35 | if (isMatch(s, p+2)) return true; 36 | s++; 37 | } 38 | return isMatch(s, p+2); 39 | } 40 | } 41 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/hard/SimplifyPath.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Simplify Path 3 | * Given an absolute path for a file (Unix-style), simplify it. 4 | * 5 | * For example, 6 | * path = "/home/", => "/home" 7 | * path = "/a/./b/../../c/", => "/c" 8 | * click to show corner cases. 9 | * 10 | * Corner Cases: 11 | * Did you consider the case where path = "/../"? 12 | * In this case, you should return "/". 13 | * Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/". 14 | * In this case, you should ignore redundant slashes and return "/home/foo". 15 | */ 16 | 17 | 18 | class Solution { 19 | public: 20 | string simplifyPath(string path) { 21 | vector result; 22 | string folder; 23 | if (path.size() == 0) return path; 24 | 25 | //result.push_back("/"); 26 | for (int i = 0; i < path.size(); i++) { 27 | if (path[i] == '/') { 28 | if (folder.size() == 0 || folder == ".") { 29 | folder = ""; 30 | } else if (folder == "..") { 31 | if (result.size()) result.pop_back(); 32 | folder = ""; 33 | } else { 34 | result.push_back(folder); 35 | folder = ""; 36 | } 37 | } else { 38 | folder += path[i]; 39 | } 40 | } 41 | 42 | if (folder.size() == 0 || folder == ".") { 43 | ; 44 | } else if (folder == "..") { 45 | if (result.size()) result.pop_back(); 46 | } else { 47 | result.push_back(folder); 48 | } 49 | 50 | string s_path; 51 | for (int i = 0; i < result.size(); i++) { 52 | s_path += "/"; 53 | s_path += result[i]; 54 | } 55 | 56 | if (s_path.size() == 0) s_path = "/"; 57 | return s_path; 58 | } 59 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/hard/WildcardMatching.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Wildcard Matching 3 | * Implement wildcard pattern matching with support for '?' and '*'. 4 | * 5 | * '?' Matches any single character. 6 | * '*' Matches any sequence of characters (including the empty sequence). 7 | * 8 | * The matching should cover the entire input string (not partial). 9 | * 10 | * The function prototype should be: 11 | * bool isMatch(const char *s, const char *p) 12 | * 13 | * Some examples: 14 | * isMatch("aa","a") → false 15 | * isMatch("aa","aa") → true 16 | * isMatch("aaa","aa") → false 17 | * isMatch("aa", "*") → true 18 | * isMatch("aa", "a*") → true 19 | * isMatch("ab", "?*") → true 20 | * isMatch("aab", "c*a*b") → false 21 | */ 22 | 23 | 24 | class Solution { 25 | public: 26 | bool isMatch(const char *s, const char *p) { 27 | bool star = false; 28 | const char *str, *ptr; 29 | 30 | for (str = s, ptr = p; *str != '\0';) { 31 | switch (*ptr) { 32 | case '?': 33 | str++; 34 | ptr++; 35 | break; 36 | case '*': 37 | star = true; 38 | s = str, p = ptr; 39 | while (*p == '*') p++; 40 | if (*p == '\0') return true; 41 | str = s, ptr = p; 42 | break; 43 | default: 44 | if (*str != *ptr) { 45 | if (!star) return false; 46 | s++; 47 | str = s; 48 | ptr = p; 49 | } else { 50 | str++; 51 | ptr++; 52 | } 53 | } 54 | } 55 | 56 | while (*ptr == '*') ptr++; 57 | 58 | return (*ptr == '\0'); 59 | } 60 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/3SumClosest.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3Sum Closest 3 | * Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. 4 | * 5 | * For example, given array S = {-1 2 1 -4}, and target = 1. 6 | * 7 | * The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 8 | */ 9 | 10 | 11 | class Solution { 12 | public: 13 | int threeSumClosest(vector &num, int target) { 14 | int min_gap = INT_MAX; 15 | int i, j, k; 16 | int result; 17 | 18 | sort(num.begin(), num.end()); 19 | 20 | for (i = 0; i < num.size() - 2; i++) { 21 | j = i+1; 22 | k = num.size() - 1; 23 | while (j < k) { 24 | int sum = num[i] + num[j] + num[k]; 25 | int gap = abs(sum - target); 26 | if (sum == target) return target; 27 | if (gap < min_gap) { 28 | result = sum; 29 | min_gap = gap; 30 | } 31 | 32 | if (sum > target) { 33 | k--; 34 | } else { 35 | j++; 36 | } 37 | } 38 | } 39 | 40 | return result; 41 | } 42 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/4Sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 4Sum 3 | * Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. 4 | * 5 | * Note: 6 | * Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d) 7 | * The solution set must not contain duplicate quadruplets. 8 | * For example, given array S = {1 0 -1 0 -2 2}, and target = 0. 9 | * 10 | * A solution set is: 11 | * (-1, 0, 0, 1) 12 | * (-2, -1, 1, 2) 13 | * (-2, 0, 0, 2) 14 | */ 15 | 16 | 17 | 18 | // TODO: learn more about STL in C++ 19 | 20 | class Solution { 21 | public: 22 | vector > fourSum(vector &num, int target) { 23 | vector > result; 24 | if (num.size() < 4) return result; 25 | sort(num.begin(), num.end()); 26 | unordered_map > > cache; 27 | 28 | for (int i = 0; i < num.size()-1; i++) { 29 | for (int j = i+1; j < num.size(); j++) { 30 | cache[num[i] + num[j]].push_back(pair(i, j)); 31 | } 32 | } 33 | 34 | for (int c = 0; c < num.size()-1; c++) { 35 | for (int d = c+1; d < num.size(); d++) { 36 | int key = target - num[c] - num[d]; 37 | if (cache.find(key) == cache.end()) continue; 38 | 39 | vector > candidates = cache[key]; 40 | for (int k = 0; k < candidates.size(); k++) { 41 | if (c <= candidates[k].second) continue; 42 | 43 | result.push_back( {num[candidates[k].first], num[candidates[k].second], num[c], num[d]} ); 44 | } 45 | } 46 | } 47 | 48 | sort(result.begin(), result.end()); 49 | result.erase(unique(result.begin(), result.end()), result.end()); 50 | return result; 51 | } 52 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/AddBinary.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Add Binary 3 | * Given two binary strings, return their sum (also a binary string). 4 | * 5 | * For example, 6 | * a = "11" 7 | * b = "1" 8 | * Return "100". 9 | */ 10 | 11 | 12 | class Solution { 13 | public: 14 | string addBinary(string a, string b) { 15 | string result; 16 | int la = a.size(); 17 | int lb = b.size(); 18 | const int N = la > lb ? la : lb; 19 | // reverse two adder 20 | reverse(a.begin(), a.end()); 21 | reverse(b.begin(), b.end()); 22 | 23 | int carry = 0, sum, ai, bi; 24 | for (int i = 0; i < N; i++) { 25 | ai = i < la ? a[i] - '0' : 0; 26 | bi = i < lb ? b[i] - '0' : 0; 27 | sum = (carry + ai + bi)%2; 28 | carry = (carry + ai + bi)/2; 29 | result.insert(result.begin(), sum + '0'); 30 | } 31 | if (carry == 1) { 32 | result.insert(result.begin(), '1'); 33 | } 34 | 35 | return result; 36 | } 37 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/AddTwoNumbers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Add Two Numbers 3 | * You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. 4 | * 5 | * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 6 | * Output: 7 -> 0 -> 8 7 | */ 8 | 9 | 10 | /** 11 | * Definition for singly-linked list. 12 | * struct ListNode { 13 | * int val; 14 | * ListNode *next; 15 | * ListNode(int x) : val(x), next(NULL) {} 16 | * }; 17 | */ 18 | class Solution { 19 | public: 20 | ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { 21 | if (l1 == NULL) return l2; 22 | if (l2 == NULL) return l1; 23 | 24 | ListNode dummy(-1); 25 | int carry = 0, sum = 0; 26 | ListNode *p = l1, *q = l2, *r = &dummy; 27 | 28 | while (p && q) { 29 | sum = (carry + p->val + q->val) % 10; 30 | carry = (carry + p->val + q->val) / 10; 31 | r->next = new ListNode(sum); 32 | r = r->next; 33 | p = p->next; 34 | q = q->next; 35 | } 36 | while (p) { 37 | sum= (carry + p->val) % 10; 38 | carry = (carry + p->val) /10; 39 | r->next = new ListNode(sum); 40 | r = r->next; 41 | p = p->next; 42 | } 43 | while (q) { 44 | sum= (carry + q->val) % 10; 45 | carry = (carry + q->val) /10; 46 | r->next = new ListNode(sum); 47 | r = r->next; 48 | q = q->next; 49 | } 50 | if (carry > 0) { 51 | r->next = new ListNode(carry); 52 | r = r->next; 53 | } 54 | r->next = NULL; 55 | return dummy.next; 56 | } 57 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/Anagrams.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Anagrams 3 | * Given an array of strings, return all groups of strings that are anagrams. 4 | * 5 | * Note: All inputs will be in lower-case. 6 | */ 7 | 8 | 9 | class Solution { 10 | public: 11 | vector anagrams(vector &strs) { 12 | unordered_map > group; 13 | for (auto s : strs) { 14 | string key = s; 15 | sort(key.begin(), key.end()); 16 | group[key].push_back(s); 17 | } 18 | 19 | vector result; 20 | for (auto it = group.cbegin(); it != group.cend(); it++) { 21 | if (it->second.size() > 1) { 22 | result.insert(result.end(), it->second.begin(), it->second.end()); 23 | } 24 | } 25 | 26 | return result; 27 | } 28 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/BestTimetoBuyandSellStockIII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Best Time to Buy and Sell Stock III 3 | * Say you have an array for which the ith element is the price of a given stock on day i. 4 | * 5 | * Design an algorithm to find the maximum profit. You may complete at most two transactions. 6 | * 7 | * Note: 8 | * You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 9 | */ 10 | 11 | 12 | class Solution { 13 | public: 14 | int maxProfit(vector &prices) { 15 | const int N = prices.size(); 16 | if (N < 2) return 0; 17 | vector left(N, 0); // left[i] is the max profit of [0, i] 18 | vector right(N, 0); // right[i] is the max profit of [i, N-1] 19 | int low = prices[0], high = prices[N-1], profit = 0; 20 | 21 | for (int i = 1; i < N; i++) { 22 | low = min(low, prices[i]); 23 | left[i] = max(left[i-1], prices[i] - low); 24 | } 25 | for (int i = N - 2; i >= 0; i--) { 26 | high = max(high, prices[i]); 27 | right[i] = max(right[i+1], high - prices[i]); 28 | } 29 | 30 | for (int mid = 0; mid < N; mid++) { // [0, mid], [mid, N) 31 | profit = max(profit, left[mid] + right[mid]); 32 | } 33 | 34 | return profit; 35 | } 36 | private: 37 | int min(int a, int b) { 38 | return a <= b ? a : b; 39 | } 40 | int max(int a, int b) { 41 | return a > b ? a : b; 42 | } 43 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/BinaryTreeLevelOrderTraversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Binary Tree Level Order Traversal 3 | * Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). 4 | */ 5 | 6 | 7 | /** 8 | * Definition for binary tree 9 | * struct TreeNode { 10 | * int val; 11 | * TreeNode *left; 12 | * TreeNode *right; 13 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 14 | * }; 15 | */ 16 | class Solution { 17 | public: 18 | vector > levelOrder(TreeNode *root) { 19 | vector > result; 20 | vector level; 21 | queue cur, next; 22 | TreeNode * p; 23 | if (root == NULL) return result; 24 | cur.push(root); 25 | 26 | while (!cur.empty()) { 27 | level.erase(level.begin(), level.end()); // clear 28 | while (!cur.empty()) { 29 | p = cur.front(); 30 | cur.pop(); 31 | 32 | level.push_back(p->val); 33 | if (p->left) next.push(p->left); 34 | if (p->right) next.push(p->right); 35 | } 36 | result.push_back(level); 37 | while (!next.empty()) { 38 | p = next.front(); 39 | next.pop(); 40 | cur.push(p); 41 | } 42 | } 43 | 44 | return result; 45 | } 46 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/BinaryTreeLevelOrderTraversalII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Binary Tree Level Order Traversal II 3 | * Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). 4 | * 5 | */ 6 | 7 | 8 | /** 9 | * Definition for binary tree 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 15 | * }; 16 | */ 17 | class Solution { 18 | public: 19 | vector > levelOrderBottom(TreeNode *root) { 20 | vector > result; 21 | traverse(root, 1, result); 22 | reverse(result.begin(), result.end()); 23 | 24 | return result; 25 | } 26 | private: 27 | void traverse(TreeNode *root, int level, vector > &result) { 28 | if (root == NULL) return; 29 | if (level > result.size()) { 30 | result.push_back(vector ()); 31 | } 32 | 33 | result[level-1].push_back(root->val); 34 | traverse(root->left, level + 1, result); 35 | traverse(root->right, level + 1, result); 36 | } 37 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/BinaryTreeZigzagLevelOrderTraversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Binary Tree Zigzag Level Order Traversal 3 | * Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). 4 | */ 5 | 6 | 7 | /** 8 | * Definition for binary tree 9 | * struct TreeNode { 10 | * int val; 11 | * TreeNode *left; 12 | * TreeNode *right; 13 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 14 | * }; 15 | */ 16 | class Solution { 17 | public: 18 | vector > zigzagLevelOrder(TreeNode *root) { 19 | vector > result; 20 | stack s; 21 | queue tmp; 22 | vector level; 23 | bool left_to_right = true; 24 | if (root == NULL) return result; 25 | 26 | s.push(root); 27 | TreeNode *cur; 28 | 29 | while (!s.empty()) { 30 | while (!s.empty()) { 31 | cur = s.top(); 32 | if (left_to_right) { 33 | // left then right 34 | if (cur->left) tmp.push(cur->left); 35 | if (cur->right) tmp.push(cur->right); 36 | } else { 37 | // right then left 38 | if (cur->right) tmp.push(cur->right); 39 | if (cur->left) tmp.push(cur->left); 40 | } 41 | s.pop(); 42 | level.push_back(cur->val); 43 | } 44 | result.push_back(level); 45 | level.clear(); 46 | 47 | // goto the next level 48 | while (!tmp.empty()) { 49 | cur = tmp.front(); 50 | tmp.pop(); 51 | s.push(cur); 52 | } 53 | left_to_right = !left_to_right; 54 | } 55 | 56 | return result; 57 | } 58 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/CombinationSum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Combination Sum 3 | * Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. 4 | * 5 | * The same repeated number may be chosen from C unlimited number of times. 6 | * 7 | * Note: 8 | * All numbers (including target) will be positive integers. 9 | * Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak). 10 | * The solution set must not contain duplicate combinations. 11 | * For example, given candidate set 2,3,6,7 and target 7, 12 | * A solution set is: 13 | * [7] 14 | * [2, 2, 3] 15 | */ 16 | 17 | 18 | class Solution { 19 | public: 20 | vector > combinationSum(vector &candidates, int target) { 21 | sort(candidates.begin(), candidates.end()); 22 | vector > result; 23 | vector combination; 24 | dfs(candidates, combination, target, result, 0); 25 | 26 | return result; 27 | } 28 | private: 29 | void dfs(vector &candidates, vector &combination, int target, 30 | vector > &result, int from) { 31 | if (target == 0) { 32 | result.push_back(combination); 33 | return; 34 | } 35 | 36 | for (int i = from; i < candidates.size(); i++) { 37 | if (candidates[i] > target) return; 38 | 39 | combination.push_back(candidates[i]); 40 | dfs(candidates, combination, target-candidates[i], result, i); 41 | combination.pop_back(); 42 | } 43 | } 44 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/CombinationSumII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Combination Sum II 3 | * Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. 4 | * 5 | * Each number in C may only be used once in the combination. 6 | * 7 | * Note: 8 | * All numbers (including target) will be positive integers. 9 | * Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak). 10 | * The solution set must not contain duplicate combinations. 11 | * For example, given candidate set 10,1,2,7,6,1,5 and target 8, 12 | * A solution set is: 13 | * [1, 7] 14 | * [1, 2, 5] 15 | * [2, 6] 16 | * [1, 1, 6] 17 | */ 18 | 19 | 20 | class Solution { 21 | public: 22 | vector > combinationSum2(vector &num, int target) { 23 | sort(num.begin(), num.end()); 24 | vector > result; 25 | vector combination; 26 | 27 | dfs(num, combination, result, target, 0); 28 | 29 | return result; 30 | } 31 | 32 | private: 33 | void dfs(vector &num, vector &combination, vector > &result, int target, int from) { 34 | if (target == 0) { 35 | result.push_back(combination); 36 | return; 37 | } 38 | 39 | int previous = -1; 40 | for (int i = from; i < num.size(); i++) { 41 | // if num[i] isn't choosed by the previous loop, 42 | // then don't choose num[i] in this loop 43 | if (num[i] == previous) continue; 44 | 45 | if (num[i] > target) return; 46 | previous = num[i]; 47 | combination.push_back(num[i]); 48 | dfs(num, combination, result, target - num[i], i+1); 49 | combination.pop_back(); 50 | } 51 | } 52 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/ConstructBinaryTreefromInorderandPostorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Construct Binary Tree from Inorder and Postorder Traversal 3 | * Given inorder and postorder traversal of a tree, construct the binary tree. 4 | * 5 | * Note: 6 | * You may assume that duplicates do not exist in the tree. 7 | */ 8 | 9 | // TODO: learn more about STL in C++ 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 *buildTree(vector &inorder, vector &postorder) { 23 | return buildTree(inorder.begin(), inorder.end(), postorder.begin(), postorder.end()); 24 | } 25 | 26 | template 27 | TreeNode *buildTree(buildit ifrom, buildit ito, buildit pfrom, buildit pto) { 28 | if (ifrom == ito) return NULL; 29 | 30 | TreeNode* root = new TreeNode(*prev(pto)); 31 | 32 | auto inrootpos = find(ifrom, ito, *prev(pto)); 33 | auto leftsize = distance(ifrom, inrootpos); 34 | auto post_left_to = next(pfrom, leftsize); 35 | 36 | root->left = buildTree(ifrom, inrootpos, pfrom, post_left_to); 37 | root->right = buildTree(next(inrootpos), ito, post_left_to, prev(pto)); 38 | 39 | return root; 40 | } 41 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/ConstructBinaryTreefromPreorderandInorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Construct Binary Tree from Preorder and Inorder Traversal 3 | * Given preorder and inorder traversal of a tree, construct the binary tree. 4 | * 5 | * Note: 6 | * You may assume that duplicates do not exist in the tree. 7 | */ 8 | 9 | 10 | /** 11 | * Definition for binary tree 12 | * struct TreeNode { 13 | * int val; 14 | * TreeNode *left; 15 | * TreeNode *right; 16 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | TreeNode *buildTree(vector &preorder, vector &inorder) { 22 | return buildTree(preorder.begin(), preorder.end(), inorder.begin(), inorder.end()); 23 | } 24 | template 25 | TreeNode *buildTree(InputIterator pfrom, InputIterator pto, InputIterator ifrom, InputIterator ito) { 26 | if (pfrom >= pto) return NULL; 27 | 28 | TreeNode *root = new TreeNode(*pfrom); 29 | auto inrootpos = find(ifrom, ito, *pfrom); 30 | auto leftsize = distance(ifrom, inrootpos); 31 | root->left = buildTree(next(pfrom), next(pfrom, leftsize + 1), ifrom, next(ifrom, leftsize)); 32 | root->right = buildTree(next(pfrom, leftsize+1), pto, next(inrootpos), ito); 33 | return root; 34 | } 35 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/ConvertSortedListtoBinarySearchTree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Convert Sorted List to Binary Search Tree 3 | * Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 4 | */ 5 | 6 | 7 | /** 8 | * Definition for singly-linked list. 9 | * struct ListNode { 10 | * int val; 11 | * ListNode *next; 12 | * ListNode(int x) : val(x), next(NULL) {} 13 | * }; 14 | */ 15 | /** 16 | * Definition for binary tree 17 | * struct TreeNode { 18 | * int val; 19 | * TreeNode *left; 20 | * TreeNode *right; 21 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 22 | * }; 23 | */ 24 | 25 | // reference: http://leetcode.com/2010/11/convert-sorted-list-to-balanced-binary.html 26 | class Solution { 27 | public: 28 | TreeNode *sortedListToBST(ListNode *head) { 29 | int len = 0; 30 | ListNode *p = head; 31 | while (p) { 32 | len++; 33 | p = p->next; 34 | } 35 | return sortedListToBST(head, 0, len); 36 | } 37 | private: 38 | TreeNode *sortedListToBST(ListNode *& cur, int begin, int end) { 39 | if (begin >= end) return NULL; 40 | 41 | int mid = begin + (end - begin)/2; 42 | TreeNode *left_child = sortedListToBST(cur, begin, mid); 43 | TreeNode *parent = new TreeNode(cur->val); 44 | cur = cur->next; // this step makes sure that cur is the root node 45 | parent->left = left_child; 46 | parent->right = sortedListToBST(cur, mid+1, end); 47 | 48 | return parent; 49 | } 50 | }; 51 | 52 | // other method: 53 | // convert list => vector array ==> binary-search-tree 54 | -------------------------------------------------------------------------------- /leetcode/C&C++/medium/CopyListwithRandomPointer.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copy List with Random Pointer 3 | * A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. 4 | * 5 | * Return a deep copy of the list. 6 | */ 7 | 8 | 9 | /** 10 | * Definition for singly-linked list with a random pointer. 11 | * struct RandomListNode { 12 | * int label; 13 | * RandomListNode *next, *random; 14 | * RandomListNode(int x) : label(x), next(NULL), random(NULL) {} 15 | * }; 16 | */ 17 | class Solution { 18 | public: 19 | RandomListNode *copyRandomList(RandomListNode *head) { 20 | if (head == NULL) return head; 21 | for (RandomListNode *cur = head; cur != NULL;) { 22 | RandomListNode *node = new RandomListNode(cur->label); 23 | node->next = cur->next; 24 | cur->next = node; 25 | cur = cur->next->next; 26 | } 27 | 28 | for (RandomListNode *cur = head; cur != NULL;) { 29 | if (cur->random) { 30 | cur->next->random = cur->random->next; 31 | } 32 | cur = cur->next->next; 33 | } 34 | 35 | RandomListNode dummy(-1); 36 | RandomListNode *h2 = &dummy; 37 | for (RandomListNode *cur = head; cur != NULL;) { 38 | h2->next = cur->next; 39 | cur->next = cur->next->next; 40 | 41 | h2 = h2->next; 42 | cur = cur->next; 43 | } 44 | 45 | return dummy.next; 46 | } 47 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/DistinctSubsequences.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Distinct Subsequences 3 | * Given a string S and a string T, count the number of distinct subsequences of T in S. 4 | * 5 | * A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not). 6 | * 7 | * Here is an example: 8 | * S = "rabbbit", T = "rabbit" 9 | * 10 | * Return 3. 11 | */ 12 | 13 | 14 | 15 | class Solution { 16 | public: 17 | int numDistinct(string S, string T) { 18 | vector f(T.size() + 1, 0); 19 | 20 | f[0] = 1; // if T.size() == 0, then should return 1; 21 | for (int i = 0; i < S.size(); i++) { 22 | for (int j = T.size()-1; j >= 0; j--) { 23 | if (S[i] == T[j]) f[j+1] += f[j]; 24 | } 25 | } 26 | 27 | return f[T.size()]; 28 | } 29 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/EditDistance.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Edit Distance 3 | * Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.) 4 | * 5 | * You have the following 3 operations permitted on a word: 6 | * 7 | * a) Insert a character 8 | * b) Delete a character 9 | * c) Replace a character 10 | */ 11 | 12 | 13 | class Solution { 14 | public: 15 | int minDistance(string word1, string word2) { 16 | const int len1 = word1.length(); 17 | const int len2 = word2.length(); 18 | 19 | if (len1 * len2 == 0) return len1 + len2; 20 | 21 | int dis[len1 + 1][len2 + 1]; 22 | 23 | for (int j = 0; j <= len2; j++) { 24 | dis[0][j] = j; 25 | } 26 | 27 | for (int i = 1; i <= len1; i++) { 28 | dis[i][0] = i; 29 | for (int j = 1; j <= len2; j++) { 30 | if (word1[i-1] == word2[j-1]) { 31 | dis[i][j] = dis[i-1][j-1]; 32 | } else { 33 | dis[i][j] = min(dis[i-1][j-1], min(dis[i-1][j], dis[i][j-1])) + 1; 34 | } 35 | } 36 | } 37 | 38 | return dis[len1][len2]; 39 | } 40 | private: 41 | int min(int a, int b) { 42 | return a <= b ? a : b; 43 | } 44 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/FirstMissingPositive.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * First Missing Positive 3 | * Given an unsorted integer array, find the first missing positive integer. 4 | * 5 | * For example, 6 | * Given [1,2,0] return 3, 7 | * and [3,4,-1,1] return 2. 8 | * 9 | * Your algorithm should run in O(n) time and uses constant space. 10 | */ 11 | 12 | 13 | class Solution { 14 | public: 15 | int firstMissingPositive(int A[], int n) { 16 | int i, tmp; 17 | 18 | for (i = 0; i < n; i++) { 19 | while (A[i] != i+1) { 20 | if (A[i] <=0 || A[i] > n || A[i] == A[A[i] - 1]) { 21 | break; 22 | } 23 | tmp = A[A[i] - 1]; 24 | A[A[i] - 1] = A[i]; 25 | A[i] = tmp; 26 | } 27 | } 28 | 29 | for (i = 0; i < n; i++) { 30 | if (A[i] != i+1) { 31 | break; 32 | } 33 | } 34 | 35 | return i+1; 36 | } 37 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/FlattenBinaryTreetoLinkedList.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Flatten Binary Tree to Linked List 3 | * Given a binary tree, flatten it to a linked list in-place. 4 | */ 5 | 6 | 7 | /** 8 | * Definition for binary tree 9 | * struct TreeNode { 10 | * int val; 11 | * TreeNode *left; 12 | * TreeNode *right; 13 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 14 | * }; 15 | */ 16 | class Solution { 17 | public: 18 | void flatten(TreeNode *root) { 19 | TreeNode *p, *q; 20 | if (root == NULL) return; 21 | 22 | p = root; 23 | while (p) { 24 | if (p->left == NULL) { 25 | p = p->right; 26 | } else { 27 | q = p->left; 28 | // morris: find the node before p->right; 29 | while (q && q->right) { 30 | q = q->right; 31 | } 32 | q->right = p->right; 33 | 34 | p->right = p->left; 35 | p->left = NULL; 36 | 37 | p = p->right; 38 | } 39 | } 40 | } 41 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/GasStation.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Gas Station 3 | * There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. 4 | * 5 | * You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations. 6 | * 7 | * Return the starting gas station's index if you can travel around the circuit once, otherwise return -1. 8 | * 9 | * Note: 10 | * The solution is guaranteed to be unique. 11 | */ 12 | 13 | 14 | class Solution { 15 | public: 16 | int canCompleteCircuit(vector &gas, vector &cost) { 17 | int start = 0, sum = 0, total = 0; 18 | const int N = gas.size(); 19 | if (N == 0) return -1; 20 | 21 | for (int i = 0; i < N; i++) { 22 | sum += gas[i] - cost[i]; 23 | total += gas[i] - cost[i]; 24 | if (sum < 0) { 25 | sum = 0; 26 | start = i+1; 27 | } 28 | } 29 | if (total < 0) return -1; 30 | else return start; 31 | } 32 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/InsertionSortList.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Insertion Sort List 3 | * Sort a linked list using insertion sort. 4 | */ 5 | 6 | /** 7 | * Definition for singly-linked list. 8 | * struct ListNode { 9 | * int val; 10 | * ListNode *next; 11 | * ListNode(int x) : val(x), next(NULL) {} 12 | * }; 13 | */ 14 | class Solution { 15 | public: 16 | ListNode *insertionSortList(ListNode *head) { 17 | ListNode dummy(-1); 18 | dummy.next = head; 19 | 20 | if (head == NULL) return head; 21 | 22 | ListNode *prev = head; 23 | ListNode *cur = head->next; 24 | ListNode *insrt; // the cur node should insert after this node 25 | 26 | while (cur) { 27 | insrt = &dummy; 28 | while (cur->val > insrt->next->val) insrt = insrt->next; 29 | 30 | if (insrt != prev) { 31 | prev->next = cur->next; 32 | cur->next = insrt->next; 33 | insrt->next = cur; 34 | cur = prev->next; 35 | } else { 36 | prev = cur; 37 | cur = cur->next; 38 | } 39 | } 40 | 41 | return dummy.next; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /leetcode/C&C++/medium/JumpGameII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Jump Game II 3 | * Given an array of non-negative integers, you are initially positioned at the first index of the array. 4 | * 5 | * Each element in the array represents your maximum jump length at that position. 6 | * 7 | * Your goal is to reach the last index in the minimum number of jumps. 8 | * 9 | * For example: 10 | * Given array A = [2,3,1,1,4] 11 | * 12 | * The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.) 13 | */ 14 | 15 | 16 | // reference: http://blog.csdn.net/linhuanmars/article/details/21356187 17 | 18 | class Solution { 19 | public: 20 | int jump(int A[], int n) { 21 | int last = 0; // the farest position can be reached by step 22 | int cur = 0; // the farest position can be reached by step+1 23 | int i, result = 0, farest; 24 | 25 | for (i = 0; i < n; i++) { 26 | if (i > last) { 27 | result++; 28 | last = cur; 29 | } 30 | farest = A[i] + i; 31 | cur = farest > cur ? farest : cur; 32 | } 33 | 34 | return result; 35 | } 36 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/LargestRectangleinHistogram.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Largest Rectangle in Histogram 3 | * Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. 4 | * For example, 5 | * Given height = [2,1,5,6,2,3], 6 | * return 10. 7 | */ 8 | 9 | 10 | class Solution { 11 | public: 12 | int largestRectangleArea(vector &height) { 13 | stack s; // index of item in height 14 | height.push_back(0); // added for coner case 15 | int result = 0; 16 | 17 | for (int i = 0; i < height.size();) { 18 | if (s.empty() || height[i] >= height[s.top()]) { 19 | s.push(i++); 20 | } else { 21 | int tmp = s.top(); 22 | s.pop(); 23 | // if s.empty(), then tmp is the smallest item, therefore area = height[tmp] * i; 24 | // if !s.empty(), then the area = length of [s.top()+1, i) * height[tmp]; 25 | result = max(result, height[tmp] * 26 | (s.empty() ? i : i - 1 - s.top())); 27 | } 28 | } 29 | 30 | return result; 31 | } 32 | private: 33 | int max (int a, int b) { 34 | return a > b ? a : b; 35 | } 36 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/LetterCombinationsofaPhoneNumber.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Letter Combinations of a Phone Number 3 | * Given a digit string, return all possible letter combinations that the number could represent. 4 | * 5 | * A mapping of digit to letters (just like on the telephone buttons) is given below. 6 | * vector keyboard{" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; 7 | */ 8 | 9 | 10 | class Solution { 11 | public: 12 | vector letterCombinations(string digits) { 13 | vector result; 14 | dfs(digits, 0, "", result); 15 | return result; 16 | } 17 | private: 18 | vector keyboard{" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; 19 | void dfs(string digits, int cur, string path, vector &result) { 20 | if (cur == digits.length()) { 21 | result.push_back(path); 22 | return; 23 | } 24 | 25 | // C style 26 | /* 27 | if (keyboard[digits[cur] - '0'].length() == 0) { // digits[cur] == '1' 28 | dfs(digits, cur+1, path, result); 29 | } else { 30 | for (int i = 0; i < keyboard[digits[cur] - '0'].length(); i++) { 31 | dfs(digits, cur+1, path+keyboard[digits[cur] - '0'][i], result); 32 | } 33 | } 34 | */ 35 | 36 | // C++ style 37 | for (auto c : keyboard[digits[cur] - '0']) { 38 | dfs(digits, cur+1, path + c, result); 39 | } 40 | } 41 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/LinkedListCycleII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Linked List Cycle II 3 | * Given a linked list, return the node where the cycle begins. If there is no cycle, return null. 4 | * 5 | * Follow up: 6 | * Can you solve it without using extra space? 7 | */ 8 | 9 | 10 | /** 11 | * Definition for singly-linked list. 12 | * struct ListNode { 13 | * int val; 14 | * ListNode *next; 15 | * ListNode(int x) : val(x), next(NULL) {} 16 | * }; 17 | */ 18 | class Solution { 19 | public: 20 | ListNode *detectCycle(ListNode *head) { 21 | ListNode *p, *q; 22 | p = q = head; 23 | if (head == NULL) return NULL; 24 | 25 | while (q && q->next) { 26 | p = p->next; 27 | q = q->next->next; 28 | if (p == q) { 29 | p = head; 30 | while (p != q) { 31 | p = p->next; 32 | q = q->next; 33 | } 34 | return q; 35 | } 36 | } 37 | 38 | return NULL; 39 | } 40 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/LongestCommonPrefix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Longest Common Prefix 3 | * Write a function to find the longest common prefix string amongst an array of strings. 4 | */ 5 | 6 | 7 | class Solution { 8 | public: 9 | string longestCommonPrefix(vector &strs) { 10 | string result; 11 | vector prefix; 12 | if (strs.size() == 0) return result; 13 | if (strs.size() == 1) return strs[0]; 14 | int len = strs[0].length(); // length of prefix; 15 | int i, j; 16 | int nums = strs.size(); // numbers of strings 17 | 18 | for (i = 0; i < len; i++) { 19 | prefix.push_back(strs[0][i]); 20 | } 21 | 22 | for (i = 1; i < nums; i++) { 23 | int len2 = strs[i].length(); 24 | for (j = 0; j < len2 && j < len; j++) { 25 | if (strs[i][j] != prefix[j]) { 26 | break; 27 | } 28 | } 29 | len = j; 30 | if (len == 0) return result; 31 | } 32 | 33 | for (i = 0; i < len; i++) { 34 | result += prefix[i]; 35 | } 36 | return result; 37 | } 38 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/LongestConsecutiveSequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Longest Consecutive Sequence 3 | * Given an unsorted array of integers, find the length of the longest consecutive elements sequence. 4 | * 5 | * For example, 6 | * Given [100, 4, 200, 1, 3, 2], 7 | * The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. 8 | * 9 | * Your algorithm should run in O(n) complexity. 10 | */ 11 | 12 | class Solution { 13 | public: 14 | int longestConsecutive(vector &num) { 15 | unordered_map used; 16 | int i, j, len = num.size(); 17 | int longest = 0, length = 0; 18 | 19 | for (i = 0; i < n; i++) { 20 | used[num[i]] = false; 21 | } 22 | 23 | for (i = 0; i < n; i++) { 24 | if (used[num[i]]) continue; 25 | length = 1; 26 | 27 | // find the leftest for num[i] 28 | for (j = num[i] - 1; used.find(j) != used.end(); j--) { 29 | used[j] = true; 30 | length++; 31 | } 32 | // find the rightest for num[i] 33 | for (j = num[i] + 1; used.find(j) != used.end(); j++) { 34 | used[j] = true; 35 | length++; 36 | } 37 | 38 | longest = length > longest ? length : longest; 39 | } 40 | 41 | return longest; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /leetcode/C&C++/medium/LongestSubstringWithoutRepeatingCharacters.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Longest Substring Without Repeating Characters 3 | * Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1. 4 | */ 5 | 6 | 7 | class Solution { 8 | public: 9 | int lengthOfLongestSubstring(string s) { 10 | const int N = s.size(); 11 | if (N < 2) return N; 12 | 13 | int start = 0, result = 0; 14 | int flag[256]; 15 | fill_n(&flag[0], 256, -1); 16 | 17 | for (int i = 0; i < N; i++) { 18 | if (flag[s[i]] >= start) { 19 | start = flag[s[i]] + 1; 20 | } 21 | flag[s[i]] = i; 22 | result = max(result, i - start + 1); 23 | } 24 | 25 | return result; 26 | } 27 | private: 28 | int max(int a, int b) { 29 | return a > b ? a : b; 30 | } 31 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/MaximalRectangle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Maximal Rectangle 3 | * Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area. 4 | */ 5 | 6 | 7 | class Solution { 8 | public: 9 | int maximalRectangle(vector > &matrix) { 10 | if (matrix.size() == 0) return 0; 11 | vector height; 12 | int result = 0; 13 | 14 | for (int i = 0; i < matrix.size(); i++) { 15 | for (int j = 0; j < matrix[0].size(); j++) { 16 | int tmp = matrix[i][j] - '0'; 17 | if (i == 0) { 18 | height.push_back(tmp); 19 | } else { 20 | height[j] = tmp == 0 ? 0 : height[j]+1; 21 | } 22 | } 23 | result = max(result, maximalRectangle(height)); 24 | } 25 | 26 | return result; 27 | } 28 | private: 29 | int max(int a, int b) { 30 | return a > b ? a : b; 31 | } 32 | 33 | int maximalRectangle(vector &height) { 34 | stack s; // index of item in height 35 | int result = 0, len, cur; 36 | 37 | for (int i = 0; i < height.size();) { 38 | if (s.empty() || height[i] >= height[s.top()]) { 39 | s.push(i++); 40 | } else { 41 | cur = s.top(); 42 | s.pop(); 43 | if (s.empty()) len = i; 44 | else len = i - (s.top() + 1); 45 | 46 | result = max(result, height[cur] * len); 47 | } 48 | } 49 | while (!s.empty()) { 50 | cur = s.top(); 51 | s.pop(); 52 | if (s.empty()) len = height.size(); 53 | else len = height.size() - (s.top() + 1); 54 | 55 | result = max (result, height[cur] * len); 56 | } 57 | 58 | return result; 59 | } 60 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/MergeIntervals.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Merge Intervals 3 | * Given a collection of intervals, merge all overlapping intervals. 4 | * 5 | * For example, 6 | * Given [1,3],[2,6],[8,10],[15,18], 7 | * return [1,6],[8,10],[15,18]. 8 | */ 9 | 10 | 11 | /** 12 | * Definition for an interval. 13 | * struct Interval { 14 | * int start; 15 | * int end; 16 | * Interval() : start(0), end(0) {} 17 | * Interval(int s, int e) : start(s), end(e) {} 18 | * }; 19 | */ 20 | class Solution { 21 | public: 22 | vector merge(vector &intervals) { 23 | vector result; 24 | if (intervals.size() == 0) return result; 25 | result.insert(result.begin(), intervals[0]); 26 | 27 | for (int i = 1; i < intervals.size(); i++) { 28 | insert(result, intervals[i]); 29 | } 30 | 31 | return result; 32 | } 33 | private: 34 | void insert(vector &intervals, Interval &newI) { 35 | vector::iterator it = intervals.begin(); 36 | while (it != intervals.end()) { 37 | if (newI.end < it->start) { 38 | intervals.insert(it, newI); 39 | return; 40 | } else if (newI.start > it->end) { 41 | it++; 42 | //continue; 43 | } else { 44 | newI.start = min(newI.start, it->start); 45 | newI.end = max(newI.end, it->end); 46 | it = intervals.erase(it); 47 | } 48 | } 49 | 50 | intervals.insert(intervals.end(), newI); 51 | return; 52 | } 53 | 54 | int max(int a, int b) { return a > b ? a : b;} 55 | int min(int a, int b) { return a < b ? a : b;} 56 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/MergekSortedLists.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Merge k Sorted Lists 3 | * Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 4 | */ 5 | 6 | 7 | /** 8 | * Definition for singly-linked list. 9 | * struct ListNode { 10 | * int val; 11 | * ListNode *next; 12 | * ListNode(int x) : val(x), next(NULL) {} 13 | * }; 14 | */ 15 | 16 | 17 | // divide-and-conquer 18 | class Solution_1 { 19 | public: 20 | ListNode *mergeKLists(vector &lists) { 21 | return mergeKlists(lists, 0, lists.size()); 22 | } 23 | private: 24 | ListNode *mergeKlists(vector &lists, int from, int to) { 25 | ListNode *l1, *l2; 26 | 27 | if (to - from == 0) return NULL; 28 | if (to - from == 1) return lists[from]; 29 | 30 | if (to - from > 2) { 31 | int mid = from + (to - from)/2; 32 | l1 = mergeKlists(lists, from, mid); 33 | l2 = mergeKlists(lists, mid, to); 34 | } else { // only two lists 35 | l1 = lists[from]; 36 | l2 = lists[to-1]; 37 | } 38 | 39 | // merge l1 and l2; 40 | ListNode dummy(-1); 41 | for (ListNode *cur = &dummy; l1 || l2; cur = cur->next) { 42 | int v1 = l1 == NULL ? INT_MAX : l1->val; 43 | int v2 = l2 == NULL ? INT_MAX : l2->val; 44 | if (v1 <= v2) { 45 | cur->next = l1; 46 | l1 = l1->next; 47 | } else { 48 | cur->next = l2; 49 | l2 = l2->next; 50 | } 51 | } 52 | 53 | return dummy.next; 54 | } 55 | }; 56 | 57 | // TODO: k-min-heap -------------------------------------------------------------------------------- /leetcode/C&C++/medium/MultiplyStrings.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Multiply Strings 3 | * Given two numbers represented as strings, return multiplication of the numbers as a string. 4 | * 5 | * Note: The numbers can be arbitrarily large and are non-negative. 6 | */ 7 | 8 | // TODO: learn overlapp of operator in C++ 9 | 10 | typedef vector bigint; 11 | 12 | class Solution { 13 | public: 14 | string multiply(string num1, string num2) { 15 | bigint x, y, z; 16 | string result; 17 | 18 | to_bigint(num1, x); 19 | to_bigint(num2, y); 20 | 21 | multiply(x, y, z); 22 | to_string(z, result); 23 | if (result.size() == 0) result += '0'; // result is zero 24 | return result; 25 | } 26 | 27 | private: 28 | void to_bigint(string &s, bigint &n) { 29 | for (int i = s.size()-1; i >= 0; i--) { 30 | n.push_back(s[i] - '0'); 31 | } 32 | } 33 | 34 | void to_string(bigint &n, string &s) { 35 | bool start = false; 36 | for (int i = n.size()-1; i >= 0; i--) { 37 | if (!start && n[i] != 0) start = true;; 38 | if (start) s += (char)(n[i] + '0'); 39 | } 40 | } 41 | 42 | void multiply(bigint &x, bigint &y, bigint &z) { 43 | z.resize(x.size() + y.size(), 0); 44 | 45 | for (int i = 0; i < x.size(); i++) { 46 | for (int j = 0; j < y.size(); j++) { 47 | z[i+j] += x[i] * y[j]; 48 | z[i+j+1] += z[i+j]/10; 49 | z[i+j] = z[i+j]%10; 50 | } 51 | } 52 | } 53 | }; 54 | -------------------------------------------------------------------------------- /leetcode/C&C++/medium/N-QueensII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * N-Queens II 3 | * Follow up for N-Queens problem. 4 | * 5 | * Now, instead outputting board configurations, return the total number of distinct solutions. 6 | */ 7 | 8 | 9 | class Solution { 10 | public: 11 | int totalNQueens(int n) { 12 | this->column = vector (n, 0); 13 | this->main_diag = vector (2*n, 0); 14 | this->anti_diag = vector (2*n, 0); 15 | this->counter = 0; 16 | dfs(n, 0); 17 | 18 | return this->counter; 19 | } 20 | 21 | private: 22 | vector column; 23 | vector main_diag; 24 | vector anti_diag; 25 | int counter; 26 | 27 | void dfs(int n, int row) { 28 | int result = 0; 29 | if (row == n) { 30 | counter++; 31 | return; 32 | } 33 | 34 | for (int j = 0; j < n; j++) { 35 | bool ok = !(column[j] || main_diag[row + j] || anti_diag[row -j + n]); 36 | if (!ok) continue; 37 | 38 | column[j] = main_diag[row + j] = anti_diag[row -j + n] = 1; 39 | dfs(n, row + 1); 40 | column[j] = main_diag[row + j] = anti_diag[row -j + n] = 0; 41 | } 42 | } 43 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/PalindromePartitioning.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Palindrome Partitioning 3 | * Given a string s, partition s such that every substring of the partition is a palindrome. 4 | * 5 | * Return all possible palindrome partitioning of s. 6 | * 7 | * For example, given s = "aab", 8 | * Return 9 | * 10 | * [ 11 | * ["aa","b"], 12 | * ["a","a","b"] 13 | * ] 14 | */ 15 | 16 | 17 | // recursive 18 | class Solution_1 { 19 | public: 20 | vector> partition(string s) { 21 | vector > result; 22 | vector path; 23 | if (s.size() == 0) return result; 24 | 25 | dfs(s, result, path, 0, 1); 26 | return result; 27 | } 28 | 29 | private: 30 | void dfs(string &s, vector > &result, vector &path, int from, int to) { 31 | if (to == s.size()) { 32 | if (ispalindrome(s, from, to)) { 33 | path.push_back(s.substr(from, to - from)); 34 | result.push_back(path); 35 | path.pop_back(); 36 | } 37 | return; 38 | } 39 | 40 | // don't cut 41 | dfs(s, result, path, from, to+1); 42 | // cut 43 | if (ispalindrome(s, from, to)) { 44 | path.push_back(s.substr(from, to - from)); 45 | dfs(s, result, path, to, to+1); 46 | path.pop_back(); 47 | } 48 | } 49 | 50 | bool ispalindrome(string &s, int from, int to) { 51 | while (s[from] == s[to-1] && from < to) { 52 | from++; 53 | to--; 54 | } 55 | return from >= to; 56 | } 57 | }; 58 | 59 | 60 | -------------------------------------------------------------------------------- /leetcode/C&C++/medium/PartitionList.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Partition List 3 | * Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. 4 | * 5 | * You should preserve the original relative order of the nodes in each of the two partitions. 6 | * 7 | * For example, 8 | * Given 1->4->3->2->5->2 and x = 3, 9 | * return 1->2->2->4->3->5. 10 | */ 11 | 12 | 13 | /** 14 | * Definition for singly-linked list. 15 | * struct ListNode { 16 | * int val; 17 | * ListNode *next; 18 | * ListNode(int x) : val(x), next(NULL) {} 19 | * }; 20 | */ 21 | class Solution { 22 | public: 23 | ListNode *partition(ListNode *head, int x) { 24 | ListNode dummy(-1); 25 | dummy.next = head; 26 | ListNode *left = &dummy; // point to the last node less than 'x' 27 | ListNode *prev, *cur; 28 | prev = &dummy; 29 | cur = head; 30 | 31 | while (cur) { 32 | if (cur->val >= x) { 33 | prev = cur; 34 | cur = cur->next; 35 | } else { 36 | if (prev == left) { // all the previous is less than 'x' 37 | left = left->next; 38 | prev = prev->next; 39 | cur = prev->next; 40 | } else { 41 | prev->next = cur->next; 42 | cur->next = left->next; 43 | left->next = cur; 44 | 45 | cur = prev->next; 46 | left = left->next; 47 | } 48 | } 49 | } 50 | 51 | return dummy.next; 52 | } 53 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/PascalsTriangleII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Pascal's Triangle II 3 | * Given an index k, return the kth row of the Pascal's triangle. 4 | * 5 | * For example, given k = 3, 6 | * Return [1,3,3,1]. 7 | * 8 | * Note: 9 | * Could you optimize your algorithm to use only O(k) extra space? 10 | */ 11 | 12 | // Note: 13 | // 1. it is C(k,i) for the ith item 14 | // 2. lookout overflow 15 | 16 | class Solution { 17 | public: 18 | vector getRow(int rowIndex) { 19 | int i, item = 1, a, b, c, d; 20 | vector result; 21 | for (i = 0; i <= rowIndex; i++) { 22 | result.push_back(item); 23 | a = (rowIndex-i)/(i+1); 24 | b = (rowIndex-i)%(i+1); 25 | c = item/(i+1); 26 | d = item%(i+1); 27 | item = a * item + b * c + (b * d)/(i+1); 28 | if (item == 0) item = 1; 29 | } 30 | 31 | return result; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /leetcode/C&C++/medium/PathSumII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Path Sum 3 | * Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. 4 | */ 5 | 6 | 7 | /** 8 | * Definition for binary tree 9 | * struct TreeNode { 10 | * int val; 11 | * TreeNode *left; 12 | * TreeNode *right; 13 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 14 | * }; 15 | */ 16 | class Solution { 17 | public: 18 | vector > pathSum(TreeNode *root, int sum) { 19 | vector path; 20 | vector > result, subresult; 21 | 22 | findpath(root, path, result, sum); 23 | return result; 24 | } 25 | private: 26 | void findpath(TreeNode *root, vector &path, vector > &result, int sum) { 27 | if (root == NULL) return; 28 | 29 | path.push_back(root->val); // add current node to path 30 | if (root->left == NULL && root->right == NULL && root->val == sum) { 31 | result.push_back(path); 32 | } 33 | 34 | findpath(root->left, path, result, sum - root->val); 35 | findpath(root->right, path, result, sum - root->val); 36 | 37 | path.pop_back(); // delete curent node from path 38 | } 39 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/PermutationSequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Permutation Sequence 3 | * The set [1,2,3,…,n] contains a total of n! unique permutations. 4 | * 5 | * By listing and labeling all of the permutations in order, 6 | * We get the following sequence (ie, for n = 3): 7 | * 8 | * "123" 9 | * "132" 10 | * "213" 11 | * "231" 12 | * "312" 13 | * "321" 14 | * Given n and k, return the kth permutation sequence. 15 | * 16 | * Note: Given n will be between 1 and 9 inclusive. 17 | */ 18 | 19 | 20 | class Solution { 21 | public: 22 | string getPermutation(int n, int k) { 23 | int map[10] = {0}; 24 | int factor = 1; 25 | int i; 26 | string result; 27 | string list; 28 | for (i = 1; i <= n; i++) { 29 | list += (char)(i + '0'); 30 | } 31 | 32 | for (i = 1; i < n; i++) { 33 | factor *= i; 34 | } 35 | k = k - 1; // This is very trick! 36 | for (i = 0; i < n; i++) { 37 | result += list[find(k/factor, n)]; 38 | k %= factor; 39 | if (i < n-1) factor /= (n-1) - i; 40 | } 41 | //result += '\0'; 42 | return result; 43 | } 44 | 45 | private: 46 | int map[10] = {0}; 47 | int find(int cnt, int n) { 48 | int i; 49 | for (i = 0; i < n; i++) { 50 | if (cnt == 0 && map[i] == 0) { 51 | map[i] = 1; 52 | return i; 53 | } 54 | if (map[i] == 0) cnt--; 55 | } 56 | } 57 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/Permutations.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Permutations 3 | * Given a collection of numbers, return all possible permutations. 4 | * 5 | * For example, 6 | * [1,2,3] have the following permutations: 7 | * [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1]. 8 | */ 9 | 10 | 11 | class Solution { 12 | public: 13 | vector > permute(vector &num) { 14 | vector > result; 15 | if (num.size() == 0) return result; 16 | sort(num.begin(), num.end()); 17 | 18 | result.push_back(num); 19 | while(next_permute(num) != -1) { 20 | result.push_back(num); 21 | } 22 | 23 | return result; 24 | } 25 | 26 | private: 27 | // Read NextPermutation.cpp, please ! 28 | int next_permute(vector &num) { 29 | int changefrom = -1, changeto; 30 | int i, j, tmp, len = num.size(); 31 | for (i = len-2; i >= 0; i--) { 32 | if (num[i] < num[i+1]) { 33 | changefrom = i; 34 | break; 35 | } 36 | } 37 | 38 | if (changefrom == -1) return -1; 39 | 40 | for (i = len-1; i >= 0; i--) { 41 | if (num[i] > num[changefrom]) { 42 | changeto = i; 43 | break; 44 | } 45 | } 46 | 47 | tmp = num[changefrom]; 48 | num[changefrom] = num[changeto]; 49 | num[changeto] = tmp; 50 | 51 | i = changefrom + 1; 52 | j = len - 1; 53 | while(i < j) { 54 | tmp = num[i]; 55 | num[i++] = num[j]; 56 | num[j--] = tmp; 57 | } 58 | 59 | return 0; 60 | } 61 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/PermutationsII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Permutations II 3 | * Given a collection of numbers that might contain duplicates, return all possible unique permutations. 4 | * 5 | * For example, 6 | * [1,1,2] have the following unique permutations: 7 | * [1,1,2], [1,2,1], and [2,1,1]. 8 | */ 9 | 10 | // The same code in Permutations.cpp works for this problem too. :) 11 | -------------------------------------------------------------------------------- /leetcode/C&C++/medium/PopulatingNextRightPointersinEachNodeII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Populating Next Right Pointers in Each Node II 3 | * Follow up for problem "Populating Next Right Pointers in Each Node". 4 | * 5 | * What if the given tree could be any binary tree? Would your previous solution still work? 6 | * 7 | * Note: 8 | * 9 | * You may only use constant extra space. 10 | */ 11 | 12 | 13 | /** 14 | * Definition for binary tree with next pointer. 15 | * struct TreeLinkNode { 16 | * int val; 17 | * TreeLinkNode *left, *right, *next; 18 | * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} 19 | * }; 20 | */ 21 | class Solution { 22 | public: 23 | void connect(TreeLinkNode *root) { 24 | TreeLinkNode *first; // first node in the same level 25 | TreeLinkNode *prev; // previous node 26 | TreeLinkNode *cur; 27 | 28 | cur = root; 29 | while (cur) { 30 | first = NULL; 31 | prev = NULL; 32 | while (cur) { 33 | if (!first) first = cur->left ? cur->left : cur->right; 34 | 35 | if (cur->left) { 36 | if (prev) prev->next = cur->left; 37 | prev = cur->left; 38 | } 39 | if (cur->right) { 40 | if (prev) prev->next = cur->right; 41 | prev = cur->right; 42 | } 43 | cur = cur->next; 44 | } 45 | 46 | cur = first; // goto the next level 47 | } 48 | } 49 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/README: -------------------------------------------------------------------------------- 1 | Medium 2 | AC rates: [20%, 30%) 3 | 4 | -------------------------------------------------------------------------------- /leetcode/C&C++/medium/RecoverBinarySearchTree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Recover Binary Search Tree 3 | * Two elements of a binary search tree (BST) are swapped by mistake. 4 | * 5 | * Recover the tree without changing its structure. 6 | * 7 | * Note: 8 | * A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? 9 | */ 10 | 11 | 12 | /** 13 | * Definition for binary tree 14 | * struct TreeNode { 15 | * int val; 16 | * TreeNode *left; 17 | * TreeNode *right; 18 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 19 | * }; 20 | */ 21 | class Solution { 22 | public: 23 | void recoverTree(TreeNode *root) { 24 | // morris inorder 25 | TreeNode *cur = root; 26 | TreeNode *prev = NULL; 27 | TreeNode *first = NULL, *second = NULL; 28 | 29 | while (cur) { 30 | if (cur->left == NULL) { 31 | if (prev && prev->val >= cur->val) { 32 | if (first == NULL) first = prev; 33 | second = cur; 34 | } 35 | prev = cur; 36 | cur = cur->right; 37 | } else { 38 | TreeNode *tmp = cur->left; 39 | while (tmp->right && tmp->right != cur) tmp = tmp->right; 40 | if (tmp->right == NULL) { 41 | tmp->right = cur; 42 | cur = cur->left; 43 | } else { 44 | if (prev && prev->val >= cur->val) { 45 | if (first == NULL) first = prev; 46 | second = cur; 47 | } 48 | tmp->right = NULL; 49 | prev = cur; 50 | cur = cur->right; 51 | } 52 | } 53 | } 54 | 55 | // swap first and second 56 | int tmpval = first->val; 57 | first->val = second->val; 58 | second->val = tmpval; 59 | 60 | } 61 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/RemoveDuplicatesfromSortedListII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Remove Duplicates from Sorted List II 3 | * Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. 4 | * 5 | * For example, 6 | * Given 1->2->3->3->4->4->5, return 1->2->5. 7 | * Given 1->1->1->2->3, return 2->3. 8 | */ 9 | 10 | 11 | /** 12 | * Definition for singly-linked list. 13 | * struct ListNode { 14 | * int val; 15 | * ListNode *next; 16 | * ListNode(int x) : val(x), next(NULL) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | ListNode *deleteDuplicates(ListNode *head) { 22 | if (head == NULL) return head; 23 | 24 | ListNode dummy(INT_MIN); 25 | dummy.next = head; 26 | ListNode *prev = &dummy, *cur = head; 27 | int dup; 28 | 29 | while (cur) { 30 | dup = 0; 31 | while (cur->next && cur->val == cur->next->val) { 32 | dup = 1; 33 | ListNode *tmp = cur; 34 | cur = cur->next; 35 | delete tmp; 36 | } 37 | if (dup) { // Because all the node need to be deleted, prev->next is still known 38 | ListNode *tmp = cur; 39 | cur = cur->next; 40 | delete tmp; 41 | } else { // prev can go to the next node which will be in the last result link 42 | prev->next = cur; 43 | prev = prev->next; 44 | cur = prev->next; 45 | } 46 | } 47 | 48 | prev->next = NULL; // prev->next should be NULL at the end; 49 | return dummy.next; 50 | } 51 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/ReorderList.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Reorder List 3 | * Given a singly linked list L: L0→L1→…→Ln-1→Ln, 4 | * reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… 5 | * 6 | * You must do this in-place without altering the nodes' values. 7 | * 8 | * For example, 9 | * Given {1,2,3,4}, reorder it to {1,4,2,3}. 10 | */ 11 | 12 | 13 | /** 14 | * Definition for singly-linked list. 15 | * struct ListNode { 16 | * int val; 17 | * ListNode *next; 18 | * ListNode(int x) : val(x), next(NULL) {} 19 | * }; 20 | */ 21 | class Solution { 22 | public: 23 | void reorderList(ListNode *head) { 24 | int len = 0; 25 | ListNode *p = head, *h2; 26 | while (p) { 27 | len++; 28 | p = p->next; 29 | } 30 | if (len < 3) return; 31 | 32 | // find the head of inserted nodes 33 | p = head; 34 | for (int i = 0; i < len/2; i++) { 35 | p = p->next; 36 | } 37 | h2 = p->next; 38 | p->next = NULL; 39 | 40 | // swap list of h2 41 | ListNode dummy(-1); 42 | dummy.next = h2; 43 | ListNode *cur = h2; 44 | while (cur->next) { 45 | ListNode *nxt = cur->next; 46 | cur->next = nxt->next; 47 | nxt->next = dummy.next; 48 | dummy.next = nxt; 49 | } 50 | 51 | // merge two list: head and h2 52 | cur = dummy.next; // node in h2 53 | p = head; 54 | while (cur) { 55 | dummy.next = cur->next; 56 | cur->next = p->next; 57 | p->next = cur; 58 | 59 | p = cur->next; 60 | cur = dummy.next; 61 | } 62 | } 63 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/RestoreIPAddresses.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Restore IP Addresses 3 | * Given a string containing only digits, restore it by returning all possible valid IP address combinations. 4 | * 5 | * For example: 6 | * Given "25525511135", 7 | * 8 | * return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) 9 | */ 10 | 11 | 12 | class Solution { 13 | public: 14 | vector restoreIpAddresses(string s) { 15 | vector result; 16 | string ip; 17 | dfs(s, 0, 0, ip, result); 18 | return result; 19 | } 20 | 21 | private: 22 | void dfs(string &s, int from, int field_id, string ip, vector &result) { 23 | if (field_id == 4 && from == s.size()) { 24 | ip.resize(ip.size()-1); 25 | result.push_back(ip); 26 | return; 27 | } 28 | 29 | if (s.size() - from > (4 - field_id) * 3) return; // too many 30 | if (s.size() - from < (4 - field_id)) return; // too lest 31 | 32 | int num = 0; 33 | for (int i = from; i < from+3; i++) { 34 | num = num*10 + (s[i] - '0'); 35 | if (num <= 255) { 36 | ip += s[i]; 37 | dfs(s, i+1, field_id+1, ip + '.', result); 38 | //ip.resize(ip.size()-1); 39 | } 40 | if (num == 0) break; // s[i] is '0', therefore stop trying 41 | } 42 | } 43 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/ReverseLinkedListII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Reverse Linked List II 3 | * Reverse a linked list from position m to n. Do it in-place and in one-pass. 4 | * 5 | * For example: 6 | * Given 1->2->3->4->5->NULL, m = 2 and n = 4, 7 | * 8 | * return 1->4->3->2->5->NULL. 9 | * 10 | * Note: 11 | * Given m, n satisfy the following condition: 12 | * 1 ≤ m ≤ n ≤ length of list. 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 | public: 26 | ListNode *reverseBetween(ListNode *head, int m, int n) { 27 | if (m == n) return head; 28 | ListNode dummy(-1); 29 | dummy.next = head; 30 | ListNode *p = &dummy; // p will pointer to the (m-1)th node 31 | 32 | for (int i = 0; i < m-1; i++) p = p->next; 33 | 34 | ListNode *q = p->next; 35 | for (int i = 0; i < n-m; i++) { 36 | ListNode *cur = q->next; 37 | q->next = cur->next; 38 | cur->next = p->next; // insert current node after p 39 | p->next = cur; 40 | } 41 | 42 | return dummy.next; 43 | } 44 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/ReverseNodesink-Group.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Reverse Nodes in k-Group 3 | * Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. 4 | * 5 | * If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. 6 | * 7 | * You may not alter the values in the nodes, only nodes itself may be changed. 8 | * 9 | * Only constant memory is allowed. 10 | * 11 | * For example, 12 | * Given this linked list: 1->2->3->4->5 13 | * 14 | * For k = 2, you should return: 2->1->4->3->5 15 | * 16 | * For k = 3, you should return: 3->2->1->4->5 17 | */ 18 | 19 | 20 | /** 21 | * Definition for singly-linked list. 22 | * struct ListNode { 23 | * int val; 24 | * ListNode *next; 25 | * ListNode(int x) : val(x), next(NULL) {} 26 | * }; 27 | */ 28 | class Solution { 29 | public: 30 | ListNode *reverseKGroup(ListNode *head, int k) { 31 | ListNode dummy(-1); 32 | dummy.next = head; 33 | if (k < 2) return head; 34 | 35 | ListNode *cur = head, *nxt; 36 | ListNode *nextGroup = &dummy; 37 | head = &dummy; 38 | for (int i = 0; i < k && nextGroup; i++) { 39 | nextGroup = nextGroup->next; 40 | } 41 | while (nextGroup) { 42 | // swap k nodes 43 | for (int i = 1; i < k; i++) { 44 | nxt = cur->next; 45 | cur->next = nxt->next; 46 | nxt->next = head->next; 47 | head->next = nxt; 48 | } 49 | 50 | head = nextGroup = cur; 51 | cur = cur->next; 52 | for (int i = 0; i < k && nextGroup; i++) { 53 | nextGroup = nextGroup->next; 54 | } 55 | } 56 | 57 | return dummy.next; 58 | } 59 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/RotateList.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Rotate List 3 | * Given a list, rotate the list to the right by k places, where k is non-negative. 4 | * 5 | * For example: 6 | * Given 1->2->3->4->5->NULL and k = 2, 7 | * return 4->5->1->2->3->NULL. 8 | */ 9 | 10 | 11 | /** 12 | * Definition for singly-linked list. 13 | * struct ListNode { 14 | * int val; 15 | * ListNode *next; 16 | * ListNode(int x) : val(x), next(NULL) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | ListNode *rotateRight(ListNode *head, int k) { 22 | if (head == NULL || k == 0) return head; 23 | 24 | ListNode dummy(-1); 25 | dummy.next = head; 26 | int len = 0; 27 | ListNode *cur = head, *new_head; 28 | while (cur) { 29 | len++; 30 | cur = cur->next; 31 | } 32 | k = k % len; // Lookout 33 | if (k == 0) return head; 34 | // find the node pointer to right-k-th node 35 | cur = &dummy; 36 | for (int i = 0; i < len - k; i++) { 37 | cur = cur->next; 38 | } 39 | new_head = cur->next; 40 | cur->next = NULL; 41 | dummy.next = new_head; 42 | // go to the last node of the original list 43 | while (new_head->next) { 44 | new_head = new_head->next; 45 | } 46 | new_head->next = head; 47 | 48 | return dummy.next; 49 | } 50 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/ScrambleString.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Scramble String 3 | * https://oj.leetcode.com/problems/scramble-string/ 4 | */ 5 | 6 | 7 | class Solution { 8 | public: 9 | bool isScramble(string s1, string s2) { 10 | // Dynamic Programming 11 | const int N = s1.size(); 12 | if (s2.size() != N) return false; 13 | if (N == 0) return true; 14 | 15 | // f[len][i][j] represents that whether 16 | // sub1[i, i+len) is scramble with sub2[j, j+len). 17 | bool f[N+1][N][N]; 18 | fill_n(&f[0][0][0], N*N*(N+1), false); 19 | for (int i = 0; i < N; i++) { 20 | for (int j = 0; j < N; j++) { 21 | f[0][i][j] = true; 22 | f[1][i][j] = s1[i] == s2[j]; 23 | } 24 | } 25 | 26 | for (int len = 2; len <= N; len++) { 27 | for (int i = 0; i + len <= N; i++) { 28 | for (int j = 0; j + len <= N; j++) { 29 | for (int k = 1; k < len; k++) { 30 | if ((f[k][i][j] && f[len-k][i+k][j+k]) 31 | || (f[k][i][j+len-k] && f[len-k][i+k][j])) { 32 | f[len][i][j] = true; 33 | break; 34 | } 35 | } 36 | } 37 | 38 | } 39 | } 40 | 41 | return f[N][0][0]; 42 | } 43 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/SearchinRotatedSortedArray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Search in Rotated Sorted Array 3 | * Suppose a sorted array is rotated at some pivot unknown to you beforehand. 4 | * 5 | * (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 6 | * 7 | * You are given a target value to search. If found in the array return its index, otherwise return -1. 8 | * 9 | * You may assume no duplicate exists in the array. 10 | */ 11 | 12 | 13 | class Solution { 14 | public: 15 | int search(int A[], int n, int target) { 16 | int from = 0, to = n, mid; 17 | 18 | if (n == 0) return -1; 19 | while (from < to) { 20 | mid = from + (to - from) / 2; 21 | if (target == A[mid]) return mid; 22 | if (target == A[from]) return from; 23 | 24 | if (A[mid] > A[from]) { // mid is in the first sorted slice 25 | if (target > A[mid] || target < A[from]) { 26 | from = mid + 1; 27 | } else { 28 | to = mid; 29 | } 30 | } else { // mid is in the second sorted slice 31 | if (target > A[from] || target < A[mid]) { 32 | to = mid; 33 | } else { 34 | from = mid + 1; 35 | } 36 | } 37 | } 38 | 39 | return -1; 40 | } 41 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/SearchinRotatedSortedArrayII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Search in Rotated Sorted Array II 3 | * Follow up for "Search in Rotated Sorted Array": 4 | * What if duplicates are allowed? 5 | * 6 | * Would this affect the run-time complexity? How and why? 7 | * 8 | * Write a function to determine if a given target is in the array. 9 | */ 10 | 11 | 12 | class Solution { 13 | public: 14 | bool search(int A[], int n, int target) { 15 | int from = 0, to = n, mid; 16 | 17 | while (from < to) { 18 | mid = from + (to - from)/2; 19 | if (target == A[mid]) return true; 20 | if (target == A[from]) return true; 21 | if (A[mid] > A[from]) { 22 | if (target > A[mid] || target < A[from]) { 23 | from = mid + 1; 24 | } else { 25 | to = mid; 26 | } 27 | } else if (A[mid] < A[from]) { 28 | if (target < A[mid] || target > A[from]) { 29 | to = mid; 30 | } else { 31 | from = mid + 1; 32 | } 33 | } else { 34 | from = from + 1; 35 | } 36 | } 37 | 38 | return false; 39 | } 40 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/SortList.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Sort List 3 | * Sort a linked list in O(n log n) time using constant space complexity. 4 | */ 5 | 6 | 7 | /** 8 | * Definition for singly-linked list. 9 | * struct ListNode { 10 | * int val; 11 | * ListNode *next; 12 | * ListNode(int x) : val(x), next(NULL) {} 13 | * }; 14 | */ 15 | class Solution { 16 | public: 17 | ListNode *sortList(ListNode *head) { 18 | // merge-sort 19 | ListNode *p = head; 20 | int len = 0; 21 | while (p) { 22 | len++; 23 | p = p->next; 24 | } 25 | if (len < 2) return head; 26 | 27 | p = head; 28 | ListNode *h2; 29 | for (int i = 0; i < len/2 - 1; i++) { 30 | p = p->next; 31 | } 32 | h2 = p->next; 33 | p->next = NULL; 34 | 35 | // sort 36 | head = sortList(head); 37 | h2 = sortList(h2); 38 | 39 | // merge 40 | ListNode dummy(-1); 41 | ListNode *cur = &dummy; 42 | for (ListNode *p = head, *q = h2; p || q; cur = cur->next) { 43 | int val1 = p == NULL ? INT_MAX : p->val; 44 | int val2 = q == NULL ? INT_MAX : q->val; 45 | 46 | if (val1 <= val2) { 47 | cur->next = p; 48 | p = p->next; 49 | } else { 50 | cur->next = q; 51 | q = q->next; 52 | } 53 | } 54 | 55 | return dummy.next; 56 | } 57 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/SpiralMatrix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Spiral Matrix 3 | * Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. 4 | * 5 | * For example, 6 | * Given the following matrix: 7 | * 8 | * [ 9 | * [ 1, 2, 3 ], 10 | * [ 4, 5, 6 ], 11 | * [ 7, 8, 9 ] 12 | * ] 13 | * You should return [1,2,3,6,9,8,7,4,5]. 14 | */ 15 | 16 | 17 | 18 | class Solution { 19 | public: 20 | vector spiralOrder(vector > &matrix) { 21 | vector result; 22 | if (matrix.empty()) return result; 23 | if (matrix[0].empty()) return result; 24 | 25 | int begin = 0; 26 | int endY = matrix[0].size() - 1; // column number for the cycle 27 | int endX = matrix.size() - 1; // row number for the cycle 28 | 29 | while (begin < endY && begin < endX) { 30 | for (int j = begin; j < endY; j++) result.push_back(matrix[begin][j]); 31 | for (int i = begin; i < endX; i++) result.push_back(matrix[i][endY]); 32 | for (int j = endY; j > begin; j--) result.push_back(matrix[endX][j]); 33 | for (int i = endX; i > begin; i--) result.push_back(matrix[i][begin]); 34 | begin++; 35 | endX--; 36 | endY--; 37 | } 38 | if (begin == endY && begin <= endX) { // left only one column 39 | while (begin <= endX) result.push_back(matrix[begin++][endY]); 40 | } 41 | if (begin == endX && begin <= endY) { // left only one row 42 | while (begin <= endY) result.push_back(matrix[endX][begin++]); 43 | } 44 | 45 | return result; 46 | } 47 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/SpiralMatrixII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Spiral Matrix II 3 | * Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. 4 | * 5 | * For example, 6 | * Given n = 3, 7 | * 8 | * You should return the following matrix: 9 | * [ 10 | * [ 1, 2, 3 ], 11 | * [ 8, 9, 4 ], 12 | * [ 7, 6, 5 ] 13 | * ] 14 | */ 15 | 16 | 17 | class Solution { 18 | public: 19 | vector > generateMatrix(int n) { 20 | vector > result(n, vector(n)); 21 | int begin = 0, end = n-1; 22 | int cnt = 1; 23 | 24 | while (begin < end) { 25 | for (int j = begin; j < end; j++) result[begin][j] = cnt++; 26 | for (int i = begin; i < end; i++) result[i][end] = cnt++; 27 | for (int j = end; j > begin; j--) result[end][j] = cnt++; 28 | for (int i = end; i > begin; i--) result[i][begin] = cnt++; 29 | begin++; 30 | end--; 31 | } 32 | if (begin == end) result[begin][begin] = cnt; 33 | 34 | return result; 35 | } 36 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/Sqrt(x).cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Sqrt(x) 3 | * Implement int sqrt(int x). 4 | * 5 | * Compute and return the square root of x. 6 | */ 7 | 8 | 9 | class Solution { 10 | public: 11 | int sqrt(int x) { 12 | if (x < 2) return x; 13 | int from = 1, to = x/2+1, mid, last_mid; 14 | 15 | while (from < to) { 16 | mid = from + (to - from)/2; 17 | if (x/mid > mid) { 18 | from = mid+1; 19 | last_mid = mid; 20 | } else if (x/mid < mid) { 21 | to = mid; 22 | } else { 23 | return mid; 24 | } 25 | } 26 | 27 | return last_mid; 28 | } 29 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/Subsets.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Subsets 3 | * Given a set of distinct integers, S, return all possible subsets. 4 | * 5 | * Note: 6 | * Elements in a subset must be in non-descending order. 7 | * The solution set must not contain duplicate subsets. 8 | */ 9 | 10 | 11 | class Solution { 12 | public: 13 | vector > subsets(vector &S) { 14 | sort(S.begin(), S.end()); 15 | vector > result; 16 | vector path; 17 | subsets(S, 0, path, result); 18 | return result; 19 | } 20 | private: 21 | void subsets(vector &S, int step, vector &path, vector > &result) { 22 | if (step == S.size()) { 23 | result.push_back(path); 24 | return; 25 | } 26 | 27 | // don't choose S[step] 28 | subsets(S, step + 1, path, result); 29 | // choose S[step] 30 | path.push_back(S[step]); 31 | subsets(S, step + 1, path, result); 32 | path.pop_back(); // clear S[step] 33 | return; 34 | } 35 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/SubsetsII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Subsets II 3 | * Given a collection of integers that might contain duplicates, S, return all possible subsets. 4 | * 5 | * Note: 6 | * Elements in a subset must be in non-descending order. 7 | * The solution set must not contain duplicate subsets. 8 | */ 9 | 10 | 11 | class Solution { 12 | public: 13 | vector > subsetsWithDup(vector &S) { 14 | vector sub; 15 | vector > result; 16 | sort(S.begin(), S.end()); 17 | subsets(S, 0, sub, result); 18 | 19 | return result; 20 | } 21 | private: 22 | void subsets(vector &S, int item_id, vector &sub, vector > &result) { 23 | if (item_id == S.size()) { 24 | result.push_back(sub); 25 | return; 26 | } 27 | if (sub.size() && S[item_id] == sub.back()) { 28 | sub.push_back(S[item_id]); 29 | subsets(S, item_id + 1, sub, result); 30 | sub.pop_back(); 31 | } else { 32 | subsets(S, item_id + 1, sub, result); 33 | sub.push_back(S[item_id]); 34 | subsets(S, item_id + 1, sub, result); 35 | sub.pop_back(); 36 | } 37 | } 38 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/SudokuSolver.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Sudoku Solver 3 | * Write a program to solve a Sudoku puzzle by filling the empty cells. 4 | * 5 | * Empty cells are indicated by the character '.'. 6 | * 7 | * You may assume that there will be only one unique solution. 8 | */ 9 | 10 | // Note: DFS 11 | 12 | 13 | class Solution { 14 | public: 15 | void solveSudoku(vector > &board) { 16 | solve(board); 17 | } 18 | 19 | private: 20 | bool solve(vector > &board) { 21 | for (int i = 0; i < 9; i++) { 22 | for (int j = 0; j < 9; j++) { 23 | if (board[i][j] == '.') { 24 | for (int k = 1; k <= 9; k++) { 25 | board[i][j] = k + '0'; 26 | if (valid(board, i, j) && solve(board)) { 27 | return true; 28 | } 29 | board[i][j] = '.'; 30 | } 31 | return false; 32 | } 33 | } 34 | } 35 | 36 | return true; 37 | } 38 | 39 | bool valid(vector > &board, int x, int y) { 40 | // column x 41 | for (int j = 0; j < 9; j++) { 42 | if (j != y && board[x][j] == board[x][y]) return false; 43 | } 44 | 45 | // row y 46 | for (int i = 0; i < 9; i++) { 47 | if (i != x && board[i][y] == board[x][y]) return false; 48 | } 49 | 50 | // check the block contains (x, y) 51 | int beg_x = 3 * (x/3); 52 | int beg_y = 3 * (y/3); 53 | for (int i = beg_x; i < beg_x + 3; i++) { 54 | for (int j = beg_y; j < beg_y + 3; j++) { 55 | if (i == x && j == y) continue; 56 | if (board[i][j] == board[x][y]) return false; 57 | } 58 | } 59 | 60 | return true; 61 | } 62 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/TrappingRainWater.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Trapping Rain Water 3 | * Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. 4 | * 5 | * For example, 6 | * Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. 7 | */ 8 | 9 | 10 | // Note: for each pillar, the water it can hold(above it) is: MAX(left_heighest, right_heightest) - height 11 | 12 | class Solution { 13 | public: 14 | int trap(int A[], int n) { 15 | int i, sum = 0; 16 | int *max_left = new int[n](); 17 | int *max_right = new int[n](); 18 | 19 | // find max_left, max_right for each pillar 20 | for (i = 1; i < n-1; i++) { 21 | max_left[i] = max(max_left[i-1], A[i-1]); 22 | max_right[n-i-1] = max(max_right[n-i], A[n-i]); 23 | } 24 | 25 | for (i = 1; i < n-1; i++) { 26 | sum += max( min(max_left[i], max_right[i]) - A[i], 0); 27 | } 28 | 29 | return sum; 30 | } 31 | 32 | private: 33 | int max(int a, int b) { 34 | return a > b ? a : b; 35 | } 36 | int min(int a, int b) { 37 | return a <= b ? a : b; 38 | } 39 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/Triangle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Triangle 3 | * Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. 4 | */ 5 | 6 | 7 | class Solution { 8 | public: 9 | int minimumTotal(vector > &triangle) { 10 | int row = triangle.size(); 11 | if (row == 0) return 0; 12 | if (triangle[0].size() == 0) return 0; 13 | int i, j; 14 | 15 | for (i = row-2; i >= 0; i--) { 16 | for (j = 0; j <= i; j++) { // i starts from 0, so there are (i+1) items in line i 17 | triangle[i][j] += min(triangle[i+1][j], triangle[i+1][j+1]); 18 | } 19 | } 20 | 21 | return triangle[0][0]; 22 | 23 | } 24 | private: 25 | int min(int a, int b) { 26 | return a <= b ? a : b; 27 | } 28 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/UniqueBinarySearchTreesII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Unique Binary Search Trees II 3 | * Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. 4 | */ 5 | 6 | 7 | /** 8 | * Definition for binary tree 9 | * struct TreeNode { 10 | * int val; 11 | * TreeNode *left; 12 | * TreeNode *right; 13 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 14 | * }; 15 | */ 16 | class Solution { 17 | public: 18 | vector generateTrees(int n) { 19 | return generateTrees(1, n); 20 | } 21 | private: 22 | vector generateTrees(int begin, int end) { 23 | vector result; 24 | if (begin > end) { 25 | result.push_back(NULL); 26 | return result; 27 | } 28 | 29 | for (int root = begin; root <= end; root++) { 30 | vector left = generateTrees(begin, root - 1); 31 | vector right = generateTrees(root + 1, end); 32 | for (auto i : left) { 33 | for (auto j : right) { 34 | TreeNode *cur = new TreeNode(root); 35 | cur->left = i; 36 | cur->right = j; 37 | result.push_back(cur); 38 | } 39 | } 40 | } 41 | 42 | return result; 43 | } 44 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/UniquePathsII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Unique Paths II 3 | * Follow up for "Unique Paths": 4 | * 5 | * Now consider if some obstacles are added to the grids. How many unique paths would there be? 6 | * 7 | * An obstacle and empty space is marked as 1 and 0 respectively in the grid. 8 | * 9 | */ 10 | 11 | 12 | class Solution { 13 | public: 14 | int uniquePathsWithObstacles(vector > &obstacleGrid) { 15 | int row = obstacleGrid.size(); 16 | if (row == 0) return 0; 17 | int col = obstacleGrid[0].size(); 18 | if (col == 0) return 0; 19 | int i, j; 20 | vector buf(row, 0); 21 | 22 | for (i = 0; i < row; i++) { 23 | if (obstacleGrid[i][0] == 0) { 24 | if (i == 0) buf[i] = 1; 25 | else buf[i] = buf[i-1]; 26 | } 27 | } 28 | 29 | for (j = 1; j < col; j++) { 30 | for (i = 0; i < row; i++) { 31 | if (obstacleGrid[i][j] == 1) { 32 | buf[i] = 0; 33 | } else { 34 | if (i > 0) buf[i] = buf[i] + buf[i-1]; 35 | } 36 | } 37 | } 38 | 39 | return buf[row-1]; 40 | } 41 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/ValidPalindrome.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Valid Palindrome 3 | * Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 4 | * 5 | * For example, 6 | * "A man, a plan, a canal: Panama" is a palindrome. 7 | * "race a car" is not a palindrome. 8 | * 9 | * Note: 10 | * Have you consider that the string might be empty? This is a good question to ask during an interview. 11 | * 12 | * For the purpose of this problem, we define empty string as valid palindrome. 13 | */ 14 | 15 | 16 | class Solution { 17 | public: 18 | bool isPalindrome(string s) { 19 | const int N = s.size(); 20 | if (N == 0) return true; 21 | transform(s.begin(), s.end(), s.begin(), ::tolower); 22 | 23 | auto first = s.begin(), last = prev(s.end()); 24 | while (first < last) { 25 | if (!isalnum(*first)) first++; 26 | else if (!isalnum(*last)) last--; 27 | else if (*first != *last) return false; 28 | else { 29 | first++; 30 | last--; 31 | } 32 | } 33 | return true; 34 | } 35 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/ValidataBinarySearchTree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Validate Binary Search Tree 3 | * Given a binary tree, determine if it is a valid binary search tree (BST). 4 | * 5 | * Assume a BST is defined as follows: 6 | * 7 | * The left subtree of a node contains only nodes with keys less than the node's key. 8 | * The right subtree of a node contains only nodes with keys greater than the node's key. 9 | * Both the left and right subtrees must also be binary search trees. 10 | */ 11 | 12 | 13 | /** 14 | * Definition for binary tree 15 | * struct TreeNode { 16 | * int val; 17 | * TreeNode *left; 18 | * TreeNode *right; 19 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 20 | * }; 21 | */ 22 | class Solution { 23 | public: 24 | bool isValidBST(TreeNode *root) { 25 | if (root == NULL) return true; 26 | // Use LLONG_MIN and LLONG_MAX 27 | //to avoid bug that there is node with INT_MIN or INT_MAX 28 | return isValid(root, LLONG_MIN, LLONG_MAX); 29 | } 30 | private: 31 | bool isValid(TreeNode *root, long long left, long long right) { 32 | if (root == NULL) return true; 33 | if (root->val >= right || root->val <= left) { 34 | return false; 35 | } 36 | 37 | return isValid(root->left, left, root->val) && isValid(root->right, root->val, right); 38 | } 39 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/WordBreak.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Word Break 3 | * Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. 4 | * 5 | * For example, given 6 | * s = "leetcode", 7 | * dict = ["leet", "code"]. 8 | * 9 | * Return true because "leetcode" can be segmented as "leet code". 10 | */ 11 | 12 | 13 | class Solution { 14 | public: 15 | bool wordBreak(string s, unordered_set &dict) { 16 | vector f(s.size() + 1, false); 17 | f[0] = true; // f[i] represent s[0, i) can be separated, therefore i is also the len of s[0, i) 18 | 19 | for (int i = 1; i <= s.size(); i++) { 20 | for (int j = i-1; j >= 0; j--) { 21 | if (f[j] && dict.find(s.substr(j, i-j)) != dict.end()) { 22 | f[i] = true; 23 | break; 24 | } 25 | } 26 | } 27 | 28 | return f[s.size()]; 29 | } 30 | }; -------------------------------------------------------------------------------- /leetcode/C&C++/medium/ZigZagConversion.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * ZigZag Conversion 3 | * The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) 4 | * 5 | * P A H N 6 | * A P L S I I G 7 | * Y I R 8 | * And then read line by line: "PAHNAPLSIIGYIR" 9 | * Write the code that will take a string and make this conversion given a number of rows: 10 | * 11 | * string convert(string text, int nRows); 12 | * convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". 13 | */ 14 | 15 | 16 | class Solution { 17 | public: 18 | string convert(string s, int nRows) { 19 | string result; 20 | int tmp; 21 | if (nRows <= 1) return s; // why is this needed ? becaused you will use (nRows - 1) 22 | 23 | for (int i = 0; i < nRows; i++) { 24 | for (int j = i; j < s.size(); j += 2*(nRows - 1)) { 25 | if (i == 0 || i == nRows - 1) { // for the first and last row 26 | result.append(1, s[j]); 27 | } else { 28 | result.append(1, s[j]); 29 | tmp = j + 2*(nRows - i - 1); // the letter in the diagonal 30 | if (tmp < s.size()) { 31 | result.append(1, s[tmp]); 32 | } 33 | } 34 | } 35 | } 36 | return result; 37 | } 38 | }; -------------------------------------------------------------------------------- /leetcode/README: -------------------------------------------------------------------------------- 1 | ###Leetcode 2 | 3 | [Problem list](https://oj.leetcode.com/problems/) 4 | 5 | 6 | --------------------------------------------------------------------------------