├── .classpath ├── .gitignore ├── .idea ├── compiler.xml ├── kotlinc.xml ├── misc.xml ├── modules.xml ├── uiDesigner.xml └── vcs.xml ├── .project ├── .settings └── org.eclipse.jdt.core.prefs ├── LeeCode.iml └── src ├── Array ├── arrayPairSum.java ├── buildTree.java ├── buildTree1.java ├── canJump.java ├── combinationSum.java ├── combinationSum2.java ├── combinationSum3.java ├── exist.java ├── findDisappearedNumbers.java ├── findDuplicate.java ├── findDuplicates.java ├── findLadders.java ├── findMaxConsecutiveOnes.java ├── findMedianSortedArrays.java ├── findMin.java ├── findMin2.java ├── findPairs.java ├── findPeakElement.java ├── findPoisonedDuration.java ├── firstMissingPositive.java ├── gameOfLife.java ├── generate.java ├── generateMatrix.java ├── getRow.java ├── insert.java ├── jump.java ├── largestRectangleArea.java ├── longestConsecutive.java ├── majorityElement.java ├── matrixReshape.java ├── maxArea.java ├── maxProduct.java ├── maxProfit.java ├── maxProfit2.java ├── maxProfit3.java ├── maxSubArray.java ├── merge.java ├── merge_intervals.java ├── minPathSum.java ├── minSubArrayLen.java ├── minimumTotal.java ├── missingNumber.java ├── moveZeroes.java ├── nextPermutation.java ├── plusOne.java ├── productExceptSelf.java ├── removeDuplicates.java ├── removeDuplicates1.java ├── removeElement.java ├── rotate.java ├── search.java ├── search2.java ├── searchInsert.java ├── searchMatrix.java ├── searchRange.java ├── setZeroes.java ├── sortColors.java ├── spiralOrder.java ├── subarraySum.java ├── subsets.java ├── subsetsWithDup.java ├── summaryRanges.java ├── test.java ├── thirdMax.java ├── threeSum.java ├── threeSumClosest.java ├── trap.java ├── twoSum.java ├── uniquePaths.java └── uniquePathsWithObstacles.java ├── Backtracking ├── Lee216_combinationSum3.java ├── Lee39_combinationSum.java ├── Lee40_combinationSum2.java ├── combine.java ├── getPermutation.java ├── permute.java ├── permuteUnique.java ├── solveNQueens.java ├── subsets.java ├── subsetsWithDup.java └── totalNQueens.java ├── BinarySearch ├── arrangeCoins.java ├── calculateMinimumHP.java ├── divide.java ├── findClosestElements.java ├── findKthNumber.java ├── findRadius.java ├── findRightInterval.java ├── firstBadVersion.java ├── guessNumber.java ├── intersection.java ├── isPerfectSquare.java ├── isSubsequence.java ├── kthSmallest.java ├── lengthOfLIS.java ├── maxEnvelopes.java ├── maxSumSubmatrix.java ├── myPow.java ├── mySqrt.java ├── search.java ├── searchInsert.java ├── searchMatrix.java ├── searchMatrix2.java ├── searchRange.java ├── smallestDistancePair.java ├── smallestGoodBase.java ├── splitArray.java └── twoSum.java ├── DFS_xunlian ├── MiGong.java └── sixFillNumber.java ├── Dynamic_Programming ├── Leet494_findTargetSumWays.java ├── NumArray.java ├── NumMatrix.java ├── PredictTheWinner.java ├── climbStairs.java ├── combinationSum4.java ├── countBits.java ├── countNumbersWithUniqueDigits.java ├── countPalindromicSubsequences.java ├── countSubstrings.java ├── findLongestChain.java ├── generateTrees.java ├── integerBreak.java ├── longestPalindrome.java ├── longestPalindromeSubseq.java ├── maxProfit1.java ├── maxProfit2.java ├── maxProfit3.java ├── maxProfit4.java ├── maxProfit5.java ├── maxSubArray.java ├── minCostClimbingStairs.java ├── numDecodings.java ├── numTrees.java ├── numberOfArithmeticSlices.java ├── numberOfArithmeticSlices1.java ├── rob.java ├── rob1.java ├── rob2.java ├── wordBreak.java └── wordBreak1.java ├── HashTable ├── Codec.java ├── Intersection.java ├── Intersection2.java ├── RandomizedCollection.java ├── RandomizedSet.java ├── Twitter.java ├── Two_Sum.java ├── Valid_Sudoku.java ├── combinationSum.java ├── containsDuplicate.java ├── containsNearbyDuplicate.java ├── copyRandomList.java ├── countPrimes.java ├── findAnagrams.java ├── findFrequentTreeSum.java ├── findMaxLength.java ├── findRepeatedDnaSequences.java ├── findSubstring.java ├── findTheDifference.java ├── fourSum.java ├── fourSumCount.java ├── frequencySort.java ├── getHint.java ├── groupAnagrams.java ├── hIndex.java ├── inorderTraversal.java ├── isAnagram.java ├── isHappy.java ├── isIsomorphic.java ├── islandPerimeter.java ├── largestRectangleArea.java ├── lengthOfLongestSubstring.java ├── longestPalindrome.java ├── maxPoints.java ├── maximalRectangle.java ├── mergeKLists.java ├── minWindow.java ├── numberOfBoomerangs.java ├── palindromePairs.java ├── singleNumber.java ├── solveSudoku.java ├── topKFrequent.java └── wordPattern.java ├── July.java ├── LinkedList ├── addTwoNumbers.java ├── copyRandomList.java ├── deleteDuplicates.java ├── deleteDuplicates1.java ├── deleteNode.java ├── detectCycle.java ├── getIntersectionNode.java ├── hasCycle.java ├── insertionSortList.java ├── isPalindrome.java ├── mergeKLists.java ├── mergeTwoLists.java ├── oddEvenList.java ├── partition.java ├── removeElements.java ├── removeNthFromEnd.java ├── reorderList.java ├── reverseBetween.java ├── reverseKGroup.java ├── reverseList.java ├── rotateRight.java ├── sortList.java ├── sortedListToBST.java └── swapPairs.java ├── MSRA_100 ├── T001_TreeToList.java ├── T002_MinStack.java ├── T003_maxSubArray.java ├── T004_FindPath.java ├── T005_GetLastNumber.java ├── T007_ListJoined.java ├── T009_isPostOrder.java ├── T010_reverseWord.java ├── T011_maxDistance.java ├── T012_Sum.java ├── T013_lastKNode.java ├── T014_twoSum.java ├── T015_Mirror.java ├── T016_Print.java ├── T017_firstSingle.java ├── T018_LastRemaining.java ├── T019_fibonacci.java └── T020_findCombination.java ├── Sort_func └── arraySort │ ├── arraySort │ ├── BubbleSort.java │ ├── HeapSort.java │ ├── InsertionSort.java │ ├── QuickSort.java │ ├── SelectionSort.java │ ├── ShellSort.java │ └── merge_sort.java │ └── linkSort │ ├── insertionSortList.java │ └── sortList.java ├── String ├── addBinary.java ├── canConstruct.java ├── checkRecord.java ├── compress.java ├── convert.java ├── countAndSay.java ├── countBinarySubstrings.java ├── countSegments.java ├── countSubstrings.java ├── findLUSlength.java ├── findLUSlength1.java ├── intToRoman.java ├── isPalindrome.java ├── isValid.java ├── judgeCircle.java ├── lengthOfLastWord.java ├── longestPalindrome.java ├── minDistance.java ├── multiply.java ├── myAtoi.java ├── repeatedStringMatch.java ├── repeatedSubstringPattern.java ├── reverseStr.java ├── reverseString.java ├── reverseVowels.java ├── reverseWords.java ├── reverseWords1.java ├── simplifyPath.java ├── strStr.java ├── tree2str.java ├── validIPAddress.java └── validPalindrome.java ├── Tree ├── hasPathSum.java ├── pathSum.java └── pathSum1.java ├── com └── chenlei │ ├── array │ ├── FindTheKMin.java │ ├── FindTheSumOfMany.java │ ├── FindTheSumOfTwo.java │ ├── HollandFlag.java │ ├── MatrixMultiply.java │ ├── MaxSumOfContinueSubArray.java │ ├── OddEvenSort.java │ ├── PerfectShuffle.java │ ├── UpStep.java │ ├── back │ │ ├── Coin.java │ │ ├── FindSumOfManyInKNum.java │ │ ├── FindTheSumOfManyOnce.java │ │ ├── FindTheSumOfTreeTrace.java │ │ ├── FindTheSumOfTwoAll.java │ │ ├── MaxProductOfContinueSubArray.java │ │ ├── MaxSumOfSubMatrix.java │ │ ├── PerfectShuffleReverse.java │ │ ├── PosiNegaResort.java │ │ └── ShortestSubStringOfSumS.java │ └── practice │ │ ├── ArrayPerGroup.java │ │ ├── ArraySplit.java │ │ ├── CoincideInterval.java │ │ ├── ColorGrid.java │ │ ├── CommonStrOfArrays.java │ │ ├── DistanceOfStation.java │ │ ├── DoubleLS.java │ │ ├── EggAndBasket.java │ │ ├── FindContinueSeqSumOfTarget.java │ │ ├── FindNumsCloseOne.java │ │ ├── FindTheMaxRectangle.java │ │ ├── FindTheMiddleOfTwoNoSortArray.java │ │ ├── FindThePair.java │ │ ├── FindTheTwoOfMaxIndexReduce.java │ │ ├── FindTheTwoProperNum.java │ │ ├── HardnessOfEgg.java │ │ ├── InvertedPair.java │ │ ├── JosephProblem.java │ │ ├── LS.java │ │ ├── LimitResourcesTask.java │ │ ├── MaxReduceOfCloseNum.java │ │ ├── MinAbs.java │ │ ├── MinOfRotateNum.java │ │ ├── NotDivisionConquer.java │ │ ├── OneOccurrence.java │ │ ├── PascalTriangle.java │ │ ├── SortArrayMinNum.java │ │ ├── SortByZero.java │ │ ├── ThreeOnceAppeared.java │ │ └── TwoOnceAppeared.java │ ├── dp │ ├── EditDistance.java │ ├── MergeString.java │ └── practice │ │ ├── ActivityArrange.java │ │ ├── MaxLengthCommonSeq.java │ │ └── SubSeqCount.java │ ├── find │ ├── BinarySearch.java │ ├── FindInRotateArray.java │ ├── NumTimesOverHalf.java │ ├── StringMatch.java │ └── YoungTableau.java │ ├── other │ └── list │ │ ├── EntryOfCircleInList.java │ │ ├── LinkListWithCircle.java │ │ └── Node.java │ ├── sort │ ├── BubbleSort.java │ ├── HeapSort.java │ ├── InsertSort.java │ ├── MergeSort.java │ ├── QuickSort.java │ └── SelectSort.java │ ├── string │ ├── MaxPalindrome.java │ ├── Palindrome.java │ ├── RotateString.java │ ├── StrToInt.java │ ├── StringContain.java │ ├── StringPerm.java │ ├── back │ │ ├── AnyPerm.java │ │ ├── BrotherWord.java │ │ ├── ListPalindrome.java │ │ ├── PrintCombination.java │ │ ├── PrintMaxPalindrome.java │ │ ├── ReverseWord.java │ │ ├── StackPalindrome.java │ │ └── StrCombination.java │ └── practice │ │ ├── FiveCode.java │ │ ├── MaxCommonSubString.java │ │ ├── MaxContinueCharLength.java │ │ ├── MaxRepeatSubString.java │ │ ├── MergeCompo.java │ │ ├── MinimumSubstring.java │ │ └── Per01.java │ └── tree │ ├── BSTNode.java │ ├── DepthOfTree.java │ ├── IsPostOrder.java │ ├── MaxDistanceInBinaryTree.java │ ├── MoveNode.java │ ├── PNext.java │ └── RevertBSTtoDouLink.java ├── segment_tree ├── NumArray.java └── countSmaller.java └── util ├── CollectionUtils.java ├── LocalCache ├── CacheObject.java ├── LRUMap.java └── LocalCache.java ├── NumberUtils.java ├── StringUtils.java └── tuple ├── Tuple.java ├── Tuple2.java ├── Tuple3.java ├── Tuple4.java └── Tuple5.java /.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /bin/ 2 | -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/kotlinc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | LeeCode 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 5 | org.eclipse.jdt.core.compiler.compliance=1.8 6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 11 | org.eclipse.jdt.core.compiler.source=1.8 12 | -------------------------------------------------------------------------------- /LeeCode.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/Array/arrayPairSum.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Created by liuchong on 2017/4/24. 7 | */ 8 | public class arrayPairSum { 9 | public int arrayPairSum(int[] nums) { 10 | Arrays.sort(nums); 11 | int sum = 0; 12 | for(int i=0; i= preorder.length || start > end) { 19 | return null; 20 | } 21 | TreeNode root = new TreeNode(preorder[idx]); 22 | int i; 23 | for (i = end; i >= start; i--) { 24 | if (preorder[idx] == inorder[i]) { 25 | break; 26 | } 27 | } 28 | root.left = buildTree(preorder, idx + 1, inorder, i - 1, start); 29 | root.right = buildTree(preorder, idx + i - start + 1, inorder, end, i+1); 30 | return root; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Array/canJump.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | /** 4 | * Created by liuchong on 2017/5/8. 5 | */ 6 | public class canJump { 7 | public boolean canJump(int[] nums) { 8 | int max_right=0; 9 | for(int i=0; i=0;curr--){ 21 | if(nums[curr] == 0){ 22 | int neededJumps = 1; 23 | while(neededJumps > nums[curr]){ 24 | neededJumps++; 25 | curr--; 26 | if(curr < 0) return false; 27 | } 28 | } 29 | } 30 | return true; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Array/findDuplicate.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | /** 4 | * Created by liuchong on 2017/4/15. 5 | */ 6 | public class findDuplicate { 7 | public int findDuplicate(int[] nums) { 8 | for(int i=0; i mid) 27 | high = mid; 28 | else 29 | low = mid + 1; 30 | } 31 | return low; 32 | } 33 | 34 | public static int findDuplicate2(int[] nums) { 35 | int n = nums.length; 36 | int slow = n; 37 | int fast = n; 38 | do{ 39 | slow = nums[slow-1]; 40 | fast = nums[nums[fast-1]-1]; 41 | }while(slow != fast); 42 | slow = n; 43 | while(slow != fast){ 44 | slow = nums[slow-1]; 45 | fast = nums[fast-1]; 46 | } 47 | return slow; 48 | } 49 | 50 | public static void main(String[] args){ 51 | int[] nums = {1,2,4,3,7,6,8,5,5}; 52 | int num = findDuplicate2(nums); 53 | System.out.println(num); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/Array/findDuplicates.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | 4 | import java.util.ArrayList; 5 | import java.util.Arrays; 6 | import java.util.Map; 7 | import java.util.HashMap; 8 | import java.util.List; 9 | 10 | /** 11 | * Created by liuchong on 2017/5/4. 12 | */ 13 | public class findDuplicates { 14 | public List findDuplicates(int[] nums) { 15 | List res = new ArrayList<>(); 16 | Arrays.sort(nums); 17 | for(int i=0; i findDuplicates1(int[] nums) { 27 | List res = new ArrayList<>(); 28 | Map map = new HashMap<>(); 29 | for(int num : nums){ 30 | if(map.containsKey(num)) 31 | res.add(num); 32 | else 33 | map.put(num, 1); 34 | } 35 | return res; 36 | } 37 | 38 | public List findDuplicates2(int[] nums) { 39 | List res = new ArrayList<>(); 40 | int index; 41 | for(int i=0; i nums[i+1]) 10 | return nums[i+1]; 11 | } 12 | return nums[0]; 13 | } 14 | 15 | public int findMin1(int[] nums){ 16 | int left=0, right=nums.length-1, mid; 17 | while(left < right){ 18 | mid = (left + right)/2; 19 | if(nums[mid] > nums[right]) { 20 | if(mid < nums.length-1 && nums[mid] > nums[mid+1]) 21 | return nums[mid+1]; 22 | left = mid+1; 23 | } 24 | else{ 25 | if(mid >0 && nums[mid] < nums[mid-1]) 26 | return nums[mid]; 27 | right = mid-1; 28 | } 29 | } 30 | return nums[0]; 31 | } 32 | 33 | public int findMin2(int[] nums) { 34 | int start = 0, end = nums.length - 1, mid; 35 | while (start < end) { 36 | mid = (start + end) / 2; 37 | if (nums[mid] > nums[end]) 38 | start = mid + 1; 39 | else 40 | end = mid; 41 | } 42 | return nums[start]; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/Array/findMin2.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | /** 4 | * Created by liuchong on 2017/6/15. 5 | */ 6 | public class findMin2 { 7 | public int findMin(int[] nums) { 8 | for(int i=0; i nums[i+1]) 10 | return nums[i+1]; 11 | } 12 | return nums[0]; 13 | } 14 | 15 | public int findMin1(int[] nums){ 16 | int left=0, right=nums.length, mid; 17 | while(left < right){ 18 | mid = (left + right)/2; 19 | if(nums[mid] >= nums[left]){ 20 | left = mid + 1; 21 | }else{ 22 | right = mid; 23 | } 24 | } 25 | return 1; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Array/findPeakElement.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | /** 4 | * Created by liuchong on 2017/5/21. 5 | */ 6 | public class findPeakElement { 7 | public int findPeakElement(int[] nums) { 8 | if(nums.length <=1 || nums[0] > nums[1]) 9 | return 0; 10 | for(int i=1; i nums[i+1]) 12 | return i; 13 | } 14 | return nums.length-1; 15 | } 16 | 17 | public int findPeakElement1(int[] nums) { 18 | int n = nums.length; 19 | int lo = 0, hi = n - 1; 20 | while(lo < hi) { 21 | int mid = lo + (hi - lo) / 2; 22 | if(nums[mid] < nums[mid+1]) { 23 | lo = mid + 1; 24 | } else { 25 | hi = mid; 26 | } 27 | } 28 | return lo; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Array/findPoisonedDuration.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | /** 4 | * Created by liuchong on 2017/5/3. 5 | */ 6 | public class findPoisonedDuration { 7 | public int findPoisonedDuration(int[] timeSeries, int duration) { 8 | int sum = 0; 9 | if(timeSeries.length<=0) 10 | return sum; 11 | for(int i=1; i= duration) 13 | sum += duration; 14 | else{ 15 | sum +=timeSeries[i] - timeSeries[i-1]; 16 | } 17 | } 18 | return sum+duration; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Array/generate.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Created by liuchong on 2017/4/8. 8 | */ 9 | public class generate { 10 | public List> generate(int numRows) { 11 | List> res = new ArrayList>(); 12 | List row, pre = null; 13 | for (int i = 0; i < numRows; ++i) { 14 | row = new ArrayList(); 15 | for (int j = 0; j <= i; ++j) 16 | if (j == 0 || j == i) 17 | row.add(1); 18 | else 19 | row.add(pre.get(j - 1) + pre.get(j)); 20 | pre = row; 21 | res.add(row); 22 | } 23 | return res; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Array/generateMatrix.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | 4 | /** 5 | * Created by liuchong on 2017/5/5. 6 | */ 7 | public class generateMatrix { 8 | public int[][] generateMatrix(int n) { 9 | int [][] res = new int[n][n]; 10 | int count=1; 11 | for(int i=0; i= left; j--) { 41 | ret[down][j] = count++; 42 | } 43 | down--; 44 | for (int i = down; i >= top; i--) { 45 | ret[i][left] = count++; 46 | } 47 | left++; 48 | } 49 | return ret; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/Array/longestConsecutive.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashSet; 5 | import java.util.Set; 6 | 7 | /** 8 | * Created by liuchong on 2017/6/17. 9 | */ 10 | public class longestConsecutive { 11 | public int longestConsecutive(int[] nums) { 12 | if(nums.length == 0 || nums == null) 13 | return 0; 14 | if(nums.length == 1) 15 | return 1; 16 | Arrays.sort(nums); 17 | int max = 0, tmp = 1; 18 | for(int i=0; i set = new HashSet<>(); 33 | 34 | for(int n: nums) set.add(n); 35 | 36 | int max = 0; 37 | 38 | for(int n: nums){ 39 | int count = 0; 40 | if(set.isEmpty()) break; 41 | 42 | int val = n; 43 | while(set.remove(val--)) 44 | count ++; 45 | 46 | val = n; 47 | while(set.remove(++val)) 48 | count ++; 49 | 50 | max = Math.max(count,max); 51 | } 52 | 53 | return max; 54 | 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/Array/majorityElement.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Created by liuchong on 2017/4/10. 7 | */ 8 | public class majorityElement { 9 | public int majorityElement(int[] nums) { 10 | Arrays.sort(nums); 11 | for(int i=0; i result) { 17 | result = max; 18 | } 19 | } 20 | return result; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/Array/maxProfit.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | /** 4 | * Created by liuchong on 2017/4/9. 5 | */ 6 | public class maxProfit { 7 | public int maxProfit(int[] prices) { 8 | int left = 0, max = 0; 9 | for(int i=0; i prices[left]) 11 | max = Math.max(max, prices[i] - prices[left]); 12 | else 13 | left = i; 14 | } 15 | return max; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Array/maxProfit2.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | /** 4 | * Created by liuchong on 2017/4/9. 5 | */ 6 | public class maxProfit2 { 7 | public int maxProfit(int[] prices) { 8 | int len = prices.length; 9 | int profit = 0; 10 | for(int i = 1; i < len ; i++){ 11 | if(prices[i]-prices[i-1] <= 0){ 12 | continue; 13 | } 14 | profit += prices[i]-prices[i-1]; 15 | } 16 | return profit; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Array/maxSubArray.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | /** 4 | * Created by liuchong on 2017/4/12. 5 | */ 6 | public class maxSubArray { 7 | public int maxSubArray(int[] A) { 8 | int max = Integer.MIN_VALUE, sum = 0; 9 | for (int i = 0; i < A.length; i++) { 10 | if (sum < 0) 11 | sum = A[i]; 12 | else 13 | sum += A[i]; 14 | if (sum > max) 15 | max = sum; 16 | } 17 | return max; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Array/minPathSum.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | /** 4 | * Created by liuchong on 2017/4/25. 5 | */ 6 | public class minPathSum { 7 | public int minPathSum(int[][] grid) { 8 | for(int i=0; i= s) { 14 | min = Math.min(min, i - left + 1); 15 | sum -= nums[left++]; 16 | } 17 | } 18 | if(min == Integer.MAX_VALUE) 19 | return 0; 20 | return min ; 21 | } 22 | 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/Array/minimumTotal.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * Created by liuchong on 2017/4/17. 7 | */ 8 | public class minimumTotal { 9 | public int minimumTotal(List> triangle) { 10 | int row = triangle.size(); 11 | int [] res = new int[row+1]; 12 | 13 | for (int i=row-1; i>=0; i--){ 14 | List tmp = triangle.get(i); 15 | for(int j=0; j> triangle) { 22 | for(int i=triangle.size()-2; i>=0; i--) 23 | for(int j=0; j<=i; j++) 24 | triangle.get(i).set(j, triangle.get(i).get(j)+Math.min(triangle.get(i+1).get(j), triangle.get(i+1).get(j+1))); 25 | return triangle.get(0).get(0); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Array/missingNumber.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Created by liuchong on 2017/4/8. 7 | */ 8 | public class missingNumber { 9 | public int missingNumber(int[] nums) { 10 | Arrays.sort(nums); 11 | for(int i=0; imid) right = mid; 25 | else left = mid+1; 26 | } 27 | return left; 28 | } 29 | 30 | public int missingNumber1(int[] nums){ 31 | int sum = 0; 32 | for(int num : nums){ 33 | sum += num; 34 | } 35 | return nums.length*(nums.length+1)/2 - sum; 36 | } 37 | 38 | public int missingNumber2(int[] nums) { 39 | //a^b^b=a。所以本例中可以使用异或操作 40 | int xor = 0, i = 0; 41 | for (i = 0; i < nums.length; i++) { 42 | xor = xor ^ i ^ nums[i]; 43 | } 44 | 45 | return xor ^ i; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/Array/moveZeroes.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | /** 4 | * Created by liuchong on 2017/4/14. 5 | */ 6 | public class moveZeroes { 7 | public static void moveZeroes(int[] nums) { 8 | int count=0, left=0; 9 | for(int i=0; i=0; j--){ 9 | if(digits[j] != 9){ 10 | digits[j] += 1; 11 | return digits; 12 | }else 13 | digits[j] = 0; 14 | } 15 | int [] res = new int[digits.length +1]; 16 | res[0] = 1; 17 | return res; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Array/productExceptSelf.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | /** 4 | * Created by liuchong on 2017/5/15. 5 | */ 6 | public class productExceptSelf { 7 | public int[] productExceptSelf(int[] nums) { 8 | int[] res = new int[nums.length]; 9 | int mul = 1; 10 | for(int num : nums) 11 | mul *= num; 12 | for(int i=0; i= 0; i--) { 41 | res[i] *= right; 42 | right *= nums[i]; 43 | } 44 | return res; 45 | } 46 | 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/Array/removeDuplicates.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | /** 4 | * Created by liuchong on 2017/4/9. 5 | */ 6 | public class removeDuplicates { 7 | public static int removeDuplicates(int[] nums) { 8 | int len = nums.length > 0 ? 1 : 0; 9 | for(int n:nums){ 10 | if(n > nums[len-1]) 11 | nums[len++] = n; 12 | } 13 | return len; 14 | } 15 | 16 | public static void main(String [] args){ 17 | int [] nums = {1,2}; 18 | removeDuplicates(nums); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/Array/removeElement.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | /** 4 | * Created by liuchong on 2017/4/9. 5 | */ 6 | public class removeElement { 7 | public int removeElement(int[] nums, int val) { 8 | int res = 0; 9 | for(int i=0; i=0; i--) 17 | nums[i+step] = nums[i]; 18 | for(int i=0; i= nums[start]) 17 | end = mid - 1; 18 | else 19 | start = mid + 1; 20 | } 21 | 22 | if (nums[mid] <= nums[end]){ 23 | if (target > nums[mid] && target <= nums[end]) 24 | start = mid + 1; 25 | else 26 | end = mid - 1; 27 | } 28 | } 29 | return -1; 30 | } 31 | 32 | public static void main(String[] args){ 33 | int[] nums = {1}; 34 | search(nums, 0); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/Array/search2.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | /** 4 | * Created by liuchong on 2017/4/20. 5 | */ 6 | public class search2 { 7 | public boolean search(int[] nums, int target) { 8 | int left=0, right=nums.length-1, mid; 9 | 10 | while(left <= right){ 11 | mid = (left+right)/2; 12 | if(nums[mid] == target) 13 | return true; 14 | 15 | if(nums[mid] < nums[left] || nums[mid] < nums[right]){ 16 | if(target > nums[mid] && target <= nums[right]) 17 | left = mid+1; 18 | else 19 | right = mid -1; 20 | }else if(nums[mid] > nums[left] || nums[mid] > nums[right]){ 21 | if(target < nums[mid] && target >= nums[left]) 22 | right = mid-1; 23 | else 24 | left = mid + 1; 25 | }else 26 | right--; 27 | 28 | } 29 | return false; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Array/searchInsert.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | /** 4 | * Created by liuchong on 2017/3/29. 5 | */ 6 | public class searchInsert { 7 | public int searchInsert(int[] nums, int target) { 8 | if(target < nums[0]) return 0; 9 | for(int i=0; i= target){ 13 | for(int j=0; j<=n; j++){ 14 | if(matrix[i][j] == target) 15 | return true; 16 | } 17 | break; 18 | } 19 | } 20 | return false; 21 | } 22 | 23 | public boolean searchMatrix1(int[][] matrix, int target) { 24 | if(matrix == null || matrix.length == 0 || matrix[0].length == 0) 25 | return false; 26 | int row_num = matrix.length; 27 | int col_num = matrix[0].length; 28 | 29 | int begin = 0, end = row_num * col_num - 1; 30 | 31 | while(begin <= end){ 32 | int mid = (begin + end) / 2; 33 | int mid_value = matrix[mid/col_num][mid%col_num]; 34 | 35 | if( mid_value == target){ 36 | return true; 37 | 38 | }else if(mid_value < target){ 39 | //Should move a bit further, otherwise dead loop. 40 | begin = mid+1; 41 | }else{ 42 | end = mid-1; 43 | } 44 | } 45 | 46 | return false; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/Array/subarraySum.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | import java.util.Map; 3 | import java.util.HashMap; 4 | 5 | /** 6 | * Created by liuchong on 2017/5/3. 7 | */ 8 | public class subarraySum { 9 | public int subarraySum(int[] nums, int k) { 10 | int sum=0, count=0; 11 | Map map = new HashMap<>(); 12 | map.put(0, 1); 13 | for(int i=0; i> subsets(int[] nums) { 12 | List> res = new ArrayList<>(); 13 | Arrays.sort(nums); 14 | res.add(new ArrayList()); 15 | 16 | for(int num :nums){ 17 | List> tmp = new ArrayList<>(); 18 | for(List list : res){ 19 | List aa = new ArrayList<>(list); 20 | aa.add(num); 21 | tmp.add(aa); 22 | } 23 | res.addAll(tmp); 24 | } 25 | 26 | return res; 27 | } 28 | 29 | public static List> subsets1(int[] nums) { 30 | List> res = new ArrayList<>(); 31 | Arrays.sort(nums); 32 | backtrack(res, new ArrayList<>(), nums, 0); 33 | return res; 34 | } 35 | 36 | public static void backtrack(List> res, List tmp, int[] nums, int start){ 37 | res.add(new ArrayList<>(tmp)); 38 | for(int i=start; i summaryRanges(int[] nums) { 11 | List res = new ArrayList<>(); 12 | if(nums.length == 0) 13 | return res; 14 | int left = nums[0]; 15 | for(int i=0; i" + nums[i]); 21 | left = nums[i+1]; 22 | } 23 | } 24 | if(nums[nums.length-1] == left) 25 | res.add("" + left); 26 | else 27 | res.add(left + "->" + nums[nums.length-1]); 28 | //res.add(); 29 | return res; 30 | } 31 | 32 | public List summaryRanges1(int[] nums){ 33 | List list=new ArrayList(); 34 | if(nums.length==1){ 35 | list.add(nums[0]+""); 36 | return list; 37 | } 38 | for(int i=0;i"+nums[i]); 45 | }else{ 46 | list.add(a+""); 47 | } 48 | } 49 | return list; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/Array/threeSumClosest.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Created by liuchong on 2017/5/23. 7 | */ 8 | public class threeSumClosest { 9 | public int threeSumClosest(int[] nums, int target) { 10 | Arrays.sort(nums); 11 | int diff = Integer.MAX_VALUE, closest = 0; 12 | for (int k=0; k target) { 17 | if (sum-target < diff) { 18 | diff = sum-target; 19 | closest = sum; 20 | } 21 | --j; 22 | } else { 23 | if (target-sum < diff) { 24 | diff = target-sum; 25 | closest = sum; 26 | } 27 | ++i; 28 | } 29 | } 30 | } 31 | return closest; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Array/twoSum.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * Created by liuchong on 2017/4/11. 8 | */ 9 | public class twoSum { 10 | public int[] twoSum(int[] numbers, int target) { 11 | int [] res = new int [2]; 12 | int left = 0, right = numbers.length-1; 13 | while(left < right){ 14 | int tmp = numbers[left] + numbers[right]; 15 | if(tmp == target){ 16 | res[0] = left + 1; 17 | res[1] = right + 1; 18 | break; 19 | }else if(tmp < target) 20 | left ++; 21 | else 22 | right --; 23 | } 24 | return res; 25 | } 26 | 27 | public int[] twoSum1(int[] numbers, int target) { 28 | Map map = new HashMap<>(); 29 | int [] res = new int[2]; 30 | for(int i=0; i 0) 16 | dp[j] += dp[j - 1]; 17 | } 18 | } 19 | return dp[width - 1]; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/Backtracking/Lee216_combinationSum3.java: -------------------------------------------------------------------------------- 1 | package Backtracking; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | 8 | 216. Combination Sum III 9 | Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used 10 | 11 | and each combination should be a unique set of numbers. 12 | 13 | 14 | Example 1: 15 | 16 | Input: k = 3, n = 7 17 | 18 | Output: 19 | 20 | [[1,2,4]] 21 | 22 | Example 2: 23 | 24 | Input: k = 3, n = 9 25 | 26 | Output: 27 | 28 | [[1,2,6], [1,3,5], [2,3,4]] 29 | */ 30 | 31 | public class Lee216_combinationSum3 { 32 | public static List> combinationSum3(int k, int n) { 33 | List> res = new ArrayList<>(); 34 | help(k, n, res, new ArrayList(), 1); 35 | return res; 36 | } 37 | 38 | public static void help(int k, int n, List> res, ArrayList path, int start){ 39 | if(k == 0 && n == 0) 40 | res.add(new ArrayList<>(path)); 41 | else if(k > 0 && n >0){ 42 | for(int i=start; i<=9; i++){ 43 | if(i > n) 44 | break; 45 | path.add(i); 46 | help(k-1, n-i, res, path, i+1); 47 | path.remove(path.size()-1); 48 | } 49 | } 50 | } 51 | 52 | public static void main(String[] args){ 53 | List> res = combinationSum3(3,7); 54 | System.out.println("dd"); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/Backtracking/subsets.java: -------------------------------------------------------------------------------- 1 | package Backtracking; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | 7 | /** 8 | 78. Subsets 9 | 10 | Given a set of distinct integers, nums, return all possible subsets (the power set). 11 | 12 | Note: The solution set must not contain duplicate subsets. 13 | 14 | For example, 15 | If nums = [1,2,3], a solution is: 16 | 17 | [ 18 | [3], 19 | [1], 20 | [2], 21 | [1,2,3], 22 | [1,3], 23 | [2,3], 24 | [1,2], 25 | [] 26 | ] 27 | */ 28 | 29 | public class subsets { 30 | 31 | //97.5% 32 | public List> subsets(int[] nums) { 33 | List> res = new ArrayList<>(); 34 | ArrayList tmp = new ArrayList<>(); 35 | Arrays.sort(nums); 36 | res.add(tmp); 37 | help(nums, res, tmp, 0); 38 | return res; 39 | } 40 | 41 | public void help(int [] nums, List> res, ArrayList tmp, int start){ 42 | if(start == nums.length) 43 | return; 44 | for(int i=start; i(tmp)); 47 | help(nums, res, tmp, i+1); 48 | tmp.remove(tmp.size()-1); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/BinarySearch/arrangeCoins.java: -------------------------------------------------------------------------------- 1 | package BinarySearch; 2 | 3 | /** 4 | * Created by liuchong on 2017/7/21. 5 | 6 | 441. Arranging Coins 7 | 8 | You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins. 9 | 10 | Given n, find the total number of full staircase rows that can be formed. 11 | 12 | n is a non-negative integer and fits within the range of a 32-bit signed integer. 13 | 14 | Example 1: 15 | 16 | n = 5 17 | 18 | The coins can form the following rows: 19 | ¤ 20 | ¤ ¤ 21 | ¤ ¤ 22 | 23 | Because the 3rd row is incomplete, we return 2. 24 | Example 2: 25 | 26 | n = 8 27 | 28 | The coins can form the following rows: 29 | ¤ 30 | ¤ ¤ 31 | ¤ ¤ ¤ 32 | ¤ ¤ 33 | 34 | Because the 4th row is incomplete, we return 3. 35 | */ 36 | public class arrangeCoins { 37 | public int arrangeCoins(int n) { 38 | //convert int to long to prevent integer overflow 39 | long nLong = (long)n; 40 | 41 | long st = 0; 42 | long ed = nLong; 43 | 44 | long mid = 0; 45 | 46 | while (st <= ed){ 47 | mid = st + (ed - st) / 2; 48 | 49 | if (mid * (mid + 1) <= 2 * nLong){ 50 | st = mid + 1; 51 | }else{ 52 | ed = mid - 1; 53 | } 54 | } 55 | 56 | return (int)(st - 1); 57 | } 58 | 59 | public int arrangeCoins1(int n) { 60 | return (int) ((Math.sqrt(1 + 8.0 * n) - 1) / 2); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/BinarySearch/guessNumber.java: -------------------------------------------------------------------------------- 1 | package BinarySearch; 2 | 3 | /** 4 | * Created by liuchong on 2017/7/18. 5 | 6 | We are playing the Guess Game. The game is as follows: 7 | 8 | I pick a number from 1 to n. You have to guess which number I picked. 9 | 10 | Every time you guess wrong, I'll tell you whether the number is higher or lower. 11 | 12 | You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0): 13 | 14 | -1 : My number is lower 15 | 1 : My number is higher 16 | 0 : Congrats! You got it! 17 | Example: 18 | n = 10, I pick 6. 19 | 20 | Return 6. 21 | 22 | 猜数字游戏==每猜一个数字都会提示猜到了或者裁小了,根据提示再进行猜。注意整数求和溢出问题即可 23 | */ 24 | public class guessNumber { 25 | public int guessNumber(int n) { 26 | int start=0, end=n, mid; 27 | while(start <= end){ 28 | //下面这两种方法都是避免整数溢出的解决方法。若直接使用(end+start)/2会溢出 29 | mid = start + (end - start) / 2; 30 | //mid = (start & end) + ((start ^ end) >> 1); 31 | int res = 1;//guess(mid); 32 | if(res == 0) 33 | return mid; 34 | else if(res == -1){ 35 | end = mid -1; 36 | }else 37 | start = mid +1; 38 | } 39 | return end; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/BinarySearch/isPerfectSquare.java: -------------------------------------------------------------------------------- 1 | package BinarySearch; 2 | 3 | /** 4 | * Created by liuchong on 2017/7/21. 5 | 6 | 367. Valid Perfect Square 7 | 8 | Given a positive integer num, write a function which returns True if num is a perfect square else False. 9 | 10 | Note: Do not use any built-in library function such as sqrt. 11 | 12 | Example 1: 13 | 14 | Input: 16 15 | Returns: True 16 | Example 2: 17 | 18 | Input: 14 19 | Returns: False 20 | */ 21 | public class isPerfectSquare { 22 | 23 | 24 | public static boolean isPerfectSquare(int num) { 25 | if (num < 1) return false; 26 | for (int i = 1; num > 0; i += 2) 27 | num -= i; 28 | return num == 0; 29 | } 30 | 31 | public boolean isPerfectSquare1(int num) { 32 | if (num < 1) return false; 33 | long left = 1, right = num;// long type to avoid 2147483647 case 34 | 35 | while (left <= right) { 36 | long mid = left + (right - left) / 2; 37 | long t = mid * mid; 38 | if (t > num) { 39 | right = mid - 1; 40 | } else if (t < num) { 41 | left = mid + 1; 42 | } else { 43 | return true; 44 | } 45 | } 46 | 47 | return false; 48 | } 49 | 50 | boolean isPerfectSquare2(int num) { 51 | if (num < 1) return false; 52 | long t = num / 2; 53 | while (t * t > num) { 54 | t = (t + num / t) / 2; 55 | } 56 | return t * t == num; 57 | } 58 | 59 | public static void main(String[] args){ 60 | isPerfectSquare(16); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/BinarySearch/myPow.java: -------------------------------------------------------------------------------- 1 | package BinarySearch; 2 | 3 | /* 4 | 5 | 题目: 6 | 7 | Implement pow(x, n). 8 | 9 | */ 10 | 11 | 12 | public class myPow { 13 | public double pow(double x, int m) { 14 | double temp = x; 15 | if (m == 0) 16 | return 1; 17 | temp = pow(x, m / 2); 18 | if (m % 2 == 0) 19 | return temp * temp; 20 | else { 21 | if (m > 0) 22 | return x * temp * temp; 23 | else 24 | return (temp * temp) / x; 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/BinarySearch/mySqrt.java: -------------------------------------------------------------------------------- 1 | package BinarySearch; 2 | 3 | /** 4 | * Created by liuchong on 2017/7/19. 5 | * 6 | 69. Sqrt(x) 7 | 8 | Implement int sqrt(int x). 9 | 10 | Compute and return the square root of x. 11 | */ 12 | public class mySqrt { 13 | 14 | public int sqrt(int x) { 15 | if (x == 0) 16 | return 0; 17 | int left = 1, right = Integer.MAX_VALUE; 18 | while (true) { 19 | int mid = left + (right - left)/2; 20 | if (mid > x/mid) { 21 | right = mid - 1; 22 | } else { 23 | if (mid + 1 > x/(mid + 1)) 24 | return mid; 25 | left = mid + 1; 26 | } 27 | } 28 | } 29 | 30 | int sqrt1(int x) { 31 | if(x == 0 || x == 1){ 32 | return x; 33 | } 34 | int l = 1, r = x, res=1; 35 | while(l <= r){ 36 | int m = (l + r)/2; 37 | if(m == x / m){ 38 | return m; 39 | }else if(m > x / m){ 40 | r = m - 1; 41 | }else{ 42 | l = m + 1; 43 | res = m; 44 | } 45 | } 46 | return res; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/BinarySearch/search.java: -------------------------------------------------------------------------------- 1 | package BinarySearch; 2 | 3 | /* 4 | 题目: 5 | 6 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 7 | 8 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 9 | 10 | You are given a target value to search. If found in the array return its index, otherwise return -1. 11 | 12 | You may assume no duplicate exists in the array. 13 | 14 | */ 15 | 16 | public class search { 17 | public static int search(int[] nums, int target) { 18 | int start = 0; 19 | int end = nums.length - 1; 20 | while (start <= end){ 21 | int mid = (start + end) / 2; 22 | if (nums[mid] == target) 23 | return mid; 24 | 25 | if (nums[start] <= nums[mid]){ 26 | if (target < nums[mid] && target >= nums[start]) 27 | end = mid - 1; 28 | else 29 | start = mid + 1; 30 | } 31 | 32 | if (nums[mid] <= nums[end]){ 33 | if (target > nums[mid] && target <= nums[end]) 34 | start = mid + 1; 35 | else 36 | end = mid - 1; 37 | } 38 | } 39 | return -1; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/BinarySearch/searchInsert.java: -------------------------------------------------------------------------------- 1 | package BinarySearch; 2 | 3 | /** 4 | * Created by liuchong on 2017/7/18. 5 | */ 6 | public class searchInsert { 7 | 8 | public int searchInsert(int[] nums, int target) { 9 | int low=0, mid=0, high=nums.length-1; 10 | while(low<=high){ 11 | mid = (low+high)/2; 12 | if(target == nums[mid]) 13 | return mid; 14 | else if(target < nums[mid]) 15 | high = mid-1; 16 | else 17 | low = mid+1; 18 | } 19 | return low; 20 | } 21 | 22 | public int searchInsert1(int[] nums, int target) { 23 | int low = 0, high = nums.length; 24 | while(low < high) { 25 | int mid = low + (high - low) / 2; 26 | if(nums[mid] < target) 27 | low = mid + 1; 28 | else 29 | high = mid; 30 | } 31 | return low; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/BinarySearch/searchMatrix.java: -------------------------------------------------------------------------------- 1 | package BinarySearch; 2 | 3 | /** 4 | * Created by liuchong on 2017/10/13. 5 | 6 | 74. Search a 2D Matrix 7 | 8 | Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 9 | 10 | Integers in each row are sorted from left to right. 11 | The first integer of each row is greater than the last integer of the previous row. 12 | For example, 13 | 14 | Consider the following matrix: 15 | 16 | [ 17 | [1, 3, 5, 7], 18 | [10, 11, 16, 20], 19 | [23, 30, 34, 50] 20 | ] 21 | Given target = 3, return true. 22 | 23 | */ 24 | public class searchMatrix { 25 | public boolean searchMatrix(int[][] matrix, int target) { 26 | if(matrix == null || matrix.length == 0 || matrix[0].length == 0) 27 | return false; 28 | int left = 0, right = matrix.length*matrix[0].length-1, num = matrix[0].length, mid; 29 | while(left <= right){ 30 | mid = (left + right)/2; 31 | if(matrix[mid/num][mid%num] == target) 32 | return true; 33 | else if(matrix[mid/num][mid%num] > target) 34 | right = mid - 1; 35 | else 36 | left = mid + 1; 37 | 38 | } 39 | return false; 40 | } 41 | 42 | //还可以先遍历每行第一个元素,找到第一个比target大的,说明再起上一行。然后再遍历改行即可。 43 | } 44 | -------------------------------------------------------------------------------- /src/BinarySearch/searchMatrix2.java: -------------------------------------------------------------------------------- 1 | package BinarySearch; 2 | 3 | /** 4 | * Created by liuchong on 2017/10/13. 5 | 6 | 240. Search a 2D Matrix II 7 | 8 | Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 9 | 10 | Integers in each row are sorted in ascending from left to right. 11 | Integers in each column are sorted in ascending from top to bottom. 12 | For example, 13 | 14 | Consider the following matrix: 15 | 16 | [ 17 | [1, 4, 7, 11, 15], 18 | [2, 5, 8, 12, 19], 19 | [3, 6, 9, 16, 22], 20 | [10, 13, 14, 17, 24], 21 | [18, 21, 23, 26, 30] 22 | ] 23 | Given target = 5, return true. 24 | 25 | Given target = 20, return false. 26 | 27 | */ 28 | public class searchMatrix2 { 29 | public boolean searchMatrix(int[][] matrix, int target) { 30 | if(matrix == null || matrix.length < 1 || matrix[0].length < 1) 31 | return false; 32 | int row = 0, col = matrix[0].length-1; 33 | while(row < matrix.length && col >= 0){ 34 | if(matrix[row][col] == target) 35 | return true; 36 | else if(matrix[row][col] > target) 37 | col --; 38 | else 39 | row ++; 40 | } 41 | return false; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/BinarySearch/searchRange.java: -------------------------------------------------------------------------------- 1 | package BinarySearch; 2 | 3 | /* 4 | 题目: 5 | 6 | Given an array of integers sorted in ascending order, find the starting and ending position of a given target value. 7 | 8 | Your algorithm's runtime complexity must be in the order of O(log n). 9 | 10 | If the target is not found in the array, return [-1, -1]. 11 | 12 | For example, 13 | Given [5, 7, 7, 8, 8, 10] and target value 8, 14 | return [3, 4]. 15 | 16 | */ 17 | 18 | public class searchRange { 19 | public int[] searchRange(int[] nums, int target) { 20 | int left=0, right=nums.length-1, mid; 21 | while(left <= right){ 22 | mid = (left + right)/2; 23 | if(nums[mid] < target) 24 | left = mid + 1; 25 | else if(nums[mid] > target) 26 | right = mid - 1; 27 | else{ 28 | int [] res = new int[2]; 29 | int a=mid, b=mid; 30 | while(a >= 0 && nums[a] == target) 31 | a -= 1; 32 | res[0] = Math.max(0, a+1); 33 | while(b <= nums.length-1 && nums[b] == target) 34 | b += 1; 35 | res[1] = Math.min(nums.length-1, b-1); 36 | return res; 37 | } 38 | } 39 | int [] res = {-1 ,-1}; 40 | return res; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/BinarySearch/twoSum.java: -------------------------------------------------------------------------------- 1 | package BinarySearch; 2 | 3 | /** 4 | * Created by liuchong on 2017/7/18. 5 | */ 6 | public class twoSum { 7 | public int[] twoSum(int[] numbers, int target) { 8 | if(numbers == null || numbers.length == 0) 9 | return new int [2]; 10 | 11 | int start = 0, end = numbers.length-1; 12 | while(start < end){ 13 | if(numbers[start] + numbers[end] == target) 14 | return new int[]{start+1, end+1}; 15 | else if(numbers[start] + numbers[end] > target) 16 | end = largestSmallerOrLastEqual(numbers, start, end, target); 17 | else 18 | start = smallestLargerOrFirstEqual(numbers, start, end, target); 19 | } 20 | return new int [2]; 21 | 22 | } 23 | 24 | private int largestSmallerOrLastEqual(int [] numbers, int start, int end, int target){ 25 | int left = start, right = end; 26 | while(left <= right){ 27 | int mid = (left + right)/2; 28 | if(numbers[mid] > target) 29 | left = mid+1; 30 | else 31 | right = mid-1; 32 | } 33 | return left; 34 | } 35 | 36 | private int smallestLargerOrFirstEqual(int [] numbers, int start, int end, int target){ 37 | int left = start, right = end; 38 | while(left <= right){ 39 | int mid = (left + right)/2; 40 | if(numbers[mid] < target) 41 | left = mid+1; 42 | else 43 | right = mid-1; 44 | } 45 | return left; 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/DFS_xunlian/MiGong.java: -------------------------------------------------------------------------------- 1 | package DFS_xunlian; 2 | 3 | public class MiGong { 4 | public static void main(String[] args) { 5 | int [][]maze = { 6 | {0, 1, 0, 0, 0}, 7 | {0, 1, 0, 1, 0}, 8 | {0, 0, 0, 0, 0}, 9 | {0, 1, 1, 1, 0}, 10 | {0, 0, 0, 1, 0}}; 11 | int [][] migong = {{0, 0, 0, 0, 0}, 12 | {0, 1, 1, 1, 0}, 13 | {0, 1, 0, 0, 0}, 14 | {0, 1, 1, 0, 1}, 15 | {0, 0, 0, 0, 0}}; 16 | dfs(migong, 0, 0); 17 | } 18 | 19 | public static void dfs(int [][] migong, int i, int j){ 20 | if(i<0 || j<0 || i>=5 || j>=5) 21 | return; 22 | if(migong[i][j] == 1) 23 | return; 24 | if(migong[i][j] == -1) 25 | return; 26 | 27 | if(migong[i][j] == 0) 28 | migong[i][j] = -1; 29 | 30 | dfs(migong, i-1, j); 31 | dfs(migong, i, j-1); 32 | dfs(migong, i+1, j); 33 | dfs(migong, i, j+1); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/DFS_xunlian/sixFillNumber.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lc222/LeeCode/c2c980c854c62660123a63c95faab132e1135337/src/DFS_xunlian/sixFillNumber.java -------------------------------------------------------------------------------- /src/Dynamic_Programming/NumArray.java: -------------------------------------------------------------------------------- 1 | package Dynamic_Programming; 2 | 3 | /** 4 | 5 | 303. Range Sum Query - Immutable 6 | 7 | Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. 8 | 9 | Example: 10 | Given nums = [-2, 0, 3, -5, 2, -1] 11 | 12 | sumRange(0, 2) -> 1 13 | sumRange(2, 5) -> -1 14 | sumRange(0, 5) -> -3 15 | Note: 16 | You may assume that the array does not change. 17 | There are many calls to sumRange function. 18 | 19 | */ 20 | 21 | 22 | public class NumArray { 23 | //95% 24 | int[] nums; 25 | public NumArray(int[] nums) { 26 | for(int i = 1; i < nums.length; i++) 27 | nums[i] += nums[i - 1]; 28 | 29 | this.nums = nums; 30 | } 31 | 32 | public int sumRange(int i, int j) { 33 | if(i == 0) 34 | return nums[j]; 35 | 36 | return nums[j] - nums[i - 1]; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/Dynamic_Programming/countSubstrings.java: -------------------------------------------------------------------------------- 1 | package Dynamic_Programming; 2 | 3 | /** 4 | * 5 | 647. Palindromic Substrings 6 | 7 | Given a string, your task is to count how many palindromic substrings in this string. 8 | 9 | The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters. 10 | 11 | Example 1: 12 | Input: "abc" 13 | Output: 3 14 | Explanation: Three palindromic strings: "a", "b", "c". 15 | Example 2: 16 | Input: "aaa" 17 | Output: 6 18 | Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". 19 | Note: 20 | The input string length won't exceed 1000. 21 | */ 22 | 23 | 24 | public class countSubstrings { 25 | int count = 0; 26 | 27 | public int countSubstrings(String s) { 28 | if (s == null || s.length() == 0) return 0; 29 | 30 | for (int i = 0; i < s.length(); i++) { // i is the mid point 31 | extendPalindrome(s, i, i); // odd length; 32 | extendPalindrome(s, i, i + 1); // even length 33 | } 34 | 35 | return count; 36 | } 37 | 38 | private void extendPalindrome(String s, int left, int right) { 39 | while (left >=0 && right < s.length() && s.charAt(left) == s.charAt(right)) { 40 | count++; left--; right++; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/Dynamic_Programming/integerBreak.java: -------------------------------------------------------------------------------- 1 | package Dynamic_Programming; 2 | 3 | /** 4 | 5 | 343. Integer Break 6 | 7 | Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those 8 | 9 | integers. Return the maximum product you can get. 10 | 11 | For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4). 12 | 13 | Note: You may assume that n is not less than 2 and not larger than 58. 14 | 15 | */ 16 | 17 | public class integerBreak { 18 | 19 | public int integerBreak(int n) { 20 | if(n == 2 || n== 3) return n-1; 21 | if(n == 4) return 4; 22 | int [] dp = new int [n+1]; 23 | dp[1] = 1; 24 | dp[2] = 1; 25 | dp[3] = 2; 26 | dp[4] = 4; 27 | for(int i=5; i<=n; i++){ 28 | for(int j=1; j<=i/2; j++) 29 | dp[i] = Math.max(dp[i], (Math.max(j,dp[j])) * (Math.max(i - j, dp[i - j]))); 30 | } 31 | return dp[n]; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Dynamic_Programming/longestPalindrome.java: -------------------------------------------------------------------------------- 1 | package Dynamic_Programming; 2 | 3 | /** 4 | 5 | 5. Longest Palindromic Substring 6 | 7 | Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. 8 | 9 | Example: 10 | 11 | Input: "babad" 12 | 13 | Output: "bab" 14 | 15 | Note: "aba" is also a valid answer. 16 | 17 | 18 | Example: 19 | 20 | Input: "cbbd" 21 | 22 | Output: "bb" 23 | */ 24 | 25 | 26 | public class longestPalindrome { 27 | public String longestPalindrome(String s) { 28 | if(s == null || s.equals("")) 29 | return ""; 30 | char [] ch = s.toCharArray(); 31 | int max = 1, left=0, right=0; 32 | for(int i=0; i=0 && i+j max){ 36 | max = 2*j+1; 37 | left = i-j; 38 | right = i+j; 39 | } 40 | } 41 | if(ch[i-j] != ch[i+j+1]){ 42 | if(2*j > max){ 43 | max = 2*j+1; 44 | left = i-j; 45 | right = i+j; 46 | } 47 | } 48 | } 49 | } 50 | return s.substring(left, right); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/Dynamic_Programming/maxProfit1.java: -------------------------------------------------------------------------------- 1 | package Dynamic_Programming; 2 | 3 | /** 4 | 5 | 121. Best Time to Buy and Sell Stock 6 | 7 | Say you have an array for which the ith element is the price of a given stock on day i. 8 | 9 | If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design 10 | 11 | an algorithm to find the maximum profit. 12 | 13 | Example 1: 14 | Input: [7, 1, 5, 3, 6, 4] 15 | Output: 5 16 | 17 | max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price) 18 | Example 2: 19 | Input: [7, 6, 4, 3, 1] 20 | Output: 0 21 | 22 | In this case, no transaction is done, i.e. max profit = 0. 23 | 24 | */ 25 | 26 | public class maxProfit1 { 27 | 28 | //DP算法 29 | public int maxProfit(int[] prices) { 30 | if(prices == null || prices.length <= 0) 31 | return 0; 32 | int min = prices[0]; 33 | int max = Integer.MIN_VALUE; 34 | for(int num : prices){ 35 | if(min > num) 36 | min = num; 37 | max = Math.max(max, num - min); 38 | } 39 | return max; 40 | } 41 | 42 | public int maxProfit1(int[] prices) { 43 | int maxCur = 0, maxSoFar = 0; 44 | for(int i = 1; i < prices.length; i++) { 45 | maxCur = Math.max(0, maxCur += prices[i] - prices[i-1]); 46 | maxSoFar = Math.max(maxCur, maxSoFar); 47 | } 48 | return maxSoFar; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/Dynamic_Programming/maxProfit2.java: -------------------------------------------------------------------------------- 1 | package Dynamic_Programming; 2 | 3 | /** 4 | 5 | 122. Best Time to Buy and Sell Stock II 6 | 7 | Say you have an array for which the ith element is the price of a given stock on day i. 8 | 9 | Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and 10 | 11 | sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time 12 | 13 | (ie, you must sell the stock before you buy again). 14 | 15 | 16 | */ 17 | 18 | 19 | public class maxProfit2 { 20 | //每次只要可以赚钱就卖 21 | public int maxProfit(int[] prices) { 22 | int sum = 0; 23 | for(int i=1; i prices[i-1]) 25 | sum += prices[i] - prices[i-1]; 26 | } 27 | return sum; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Dynamic_Programming/maxProfit5.java: -------------------------------------------------------------------------------- 1 | package Dynamic_Programming; 2 | 3 | 4 | /** 5 | 309. Best Time to Buy and Sell Stock with Cooldown 6 | 7 | Say you have an array for which the ith element is the price of a given stock on day i. 8 | 9 | Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and 10 | 11 | sell one share of the stock multiple times) with the following restrictions: 12 | 13 | You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 14 | After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day) 15 | Example: 16 | 17 | prices = [1, 2, 3, 0, 2] 18 | maxProfit = 3 19 | transactions = [buy, sell, cooldown, buy, sell] 20 | 21 | */ 22 | public class maxProfit5 { 23 | public int maxProfit(int[] prices) { 24 | int profit1=0, profit2=0; 25 | for(int i=1; i wordBreak(String s, List wordDict) { 29 | List [] dp = new List[s.length()+1]; 30 | dp[0] = new ArrayList<>(); 31 | for(int i=1; i<=s.length(); i++){ 32 | dp[i] = new ArrayList<>(); 33 | for(int j=0; j 0 && dp[j].size() > 0 && wordDict.contains(ss)){ 38 | for(String sss : dp[j]) 39 | dp[i].add(sss+" " +ss); 40 | } 41 | } 42 | } 43 | return dp[s.length()]; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/HashTable/RandomizedSet.java: -------------------------------------------------------------------------------- 1 | package HashTable; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | import java.util.Random; 7 | 8 | public class RandomizedSet { 9 | ArrayList nums = new ArrayList<>(); 10 | HashMap map = new HashMap<>(); //stores indices 11 | /** Initialize your data structure here. */ 12 | public RandomizedSet() { 13 | } 14 | 15 | /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ 16 | public boolean insert(int val) { 17 | if(!map.containsKey(val)){ 18 | nums.add(val); 19 | map.put(val, nums.size()-1); 20 | return true; 21 | } 22 | return false; 23 | } 24 | 25 | /** Removes a value from the set. Returns true if the set contained the specified element. */ 26 | public boolean remove(int val) { 27 | if(map.containsKey(val)){ 28 | int last = nums.get(nums.size()-1); 29 | int removePos = map.get(val); 30 | nums.set(removePos, last); //replace the removed number with the last number 31 | nums.remove(nums.size()-1); //always remove the last element, takes O(1) 32 | map.put(last, removePos); //upadate index 33 | map.remove(val); 34 | return true; 35 | } 36 | return false; 37 | } 38 | 39 | /** Get a random element from the set. */ 40 | public int getRandom() { 41 | int index = (int)(Math.random() * nums.size()); 42 | return nums.get(index); 43 | } 44 | } -------------------------------------------------------------------------------- /src/HashTable/Two_Sum.java: -------------------------------------------------------------------------------- 1 | package HashTable; 2 | 3 | import java.util.HashMap; 4 | 5 | public class Two_Sum { 6 | 7 | public static int[] twoSum(int[] nums, int target) 8 | { 9 | int [] result = new int[2]; 10 | HashMap res = new HashMap<>(); 11 | for(int i=0; i map = new HashMap(); 12 | for (int i = 0; i < nums.length; i++) { 13 | if (map.containsKey(nums[i])) { 14 | if (i - map.get(nums[i]) <= k) return true; 15 | } 16 | map.put(nums[i], i); 17 | } 18 | return false; 19 | } 20 | 21 | //90%�Ļ����� 22 | //ʹ�û������ڵķ�����������������������set������K������ 23 | public boolean containsNearbyDuplicate1(int[] nums, int k) { 24 | Set tmp = new HashSet<>(); 25 | for(int i=0; ik) tmp.remove(nums[i-k-1]); 28 | 29 | if(!tmp.add(nums[i])) return true; 30 | } 31 | return false; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/HashTable/countPrimes.java: -------------------------------------------------------------------------------- 1 | package HashTable; 2 | 3 | public class countPrimes { 4 | public int countPrimes(int n) { 5 | int count = 0; 6 | for (int i = 1; i < n; i++) { 7 | if (isPrime(i)) count++; 8 | } 9 | return count; 10 | } 11 | 12 | private boolean isPrime(int num) { 13 | if (num <= 1) return false; 14 | // Loop's ending condition is i * i <= num instead of i <= sqrt(num) 15 | // to avoid repeatedly calling an expensive function sqrt(). 16 | for (int i = 2; i * i <= num; i++) { 17 | if (num % i == 0) return false; 18 | } 19 | return true; 20 | } 21 | 22 | public int countPrimes1(int n){ 23 | boolean [] isPrime = new boolean[n]; 24 | for(int i=2; i findAnagrams(String s, String p) { 8 | List list = new ArrayList(); 9 | if(s == null || p == null || s.length() < p.length()) return list; 10 | int lengthp = p.length(); 11 | int lengths = s.length(); 12 | int[] hash = new int[26]; 13 | for(char c : p.toCharArray()){ 14 | ++hash[c - 'a']; 15 | } 16 | int left = 0, right = 0; 17 | while(right < lengths){ 18 | if(hash[s.charAt(right++) - 'a']-- > 0) lengthp--; 19 | if(lengthp == 0) list.add(left); 20 | if(right - left == p.length() && hash[s.charAt(left++) - 'a']++ >= 0) lengthp++; 21 | } 22 | return list; 23 | } 24 | 25 | public boolean isAnagram1(String s, String t) { 26 | int [] tmp = new int[26]; 27 | for(char c : s.toCharArray()) 28 | tmp[c-'a'] ++; 29 | for(char c:t.toCharArray()) 30 | tmp[c-'a'] --; 31 | for(int a:tmp) 32 | if(a!=0) 33 | return false; 34 | return true; 35 | } 36 | 37 | public static void main(String[] args){ 38 | String s = "cbaebabacd"; 39 | String p = "abc"; 40 | List res = findAnagrams(s, p); 41 | System.out.println(res); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/HashTable/findFrequentTreeSum.java: -------------------------------------------------------------------------------- 1 | package HashTable; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | 7 | public class findFrequentTreeSum { 8 | 9 | int maxCount = 0; 10 | public class TreeNode { 11 | int val; 12 | TreeNode left; 13 | TreeNode right; 14 | TreeNode(int x) { val = x; } 15 | } 16 | 17 | public int[] findFrequentTreeSum(TreeNode root) { 18 | HashMap tmp = new HashMap<>(); 19 | dfs(root, tmp); 20 | List res = new ArrayList<>(); 21 | for (int key : tmp.keySet()) { 22 | if (tmp.get(key) == maxCount) { 23 | res.add(key); 24 | } 25 | } 26 | 27 | int[] result = new int[res.size()]; 28 | for (int i = 0; i < res.size(); i++) { 29 | result[i] = res.get(i); 30 | } 31 | return result; 32 | } 33 | 34 | public int dfs(TreeNode node, HashMap res){ 35 | if(node == null) return 0; 36 | int left = 0, right = 0, sum = 0; 37 | if(node.left != null) 38 | left = dfs(node.left, res); 39 | if(node.right != null) 40 | right = dfs(node.right, res); 41 | sum = left + right + node.val; 42 | int count = res.getOrDefault(sum, 0) + 1; 43 | res.put(sum, count); 44 | maxCount = Math.max(maxCount, count); 45 | return sum; 46 | } 47 | 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/HashTable/fourSumCount.java: -------------------------------------------------------------------------------- 1 | package HashTable; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class fourSumCount { 7 | public int fourSumCount(int[] A, int[] B, int[] C, int[] D) { 8 | Map map = new HashMap<>(); 9 | for(int i=0; i map = new HashMap<>(); 23 | for(int a : A ) 24 | for(int b : B) 25 | map.put(a+b, map.getOrDefault(a+b, 0)+1); 26 | int res = 0; 27 | for(int c : C) 28 | for(int d : D){ 29 | if(map.containsKey(-c-d)) 30 | res += map.get(-c-d); 31 | } 32 | return res; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/HashTable/hIndex.java: -------------------------------------------------------------------------------- 1 | package HashTable; 2 | 3 | import java.util.Arrays; 4 | 5 | public class hIndex { 6 | public static int hIndex(int[] citations) { 7 | int n = citations.length, tot=0; 8 | int[] arr = new int[n+1]; 9 | for (int i=0; i=n) arr[n]++; 11 | else arr[citations[i]]++; 12 | } 13 | for (int i=n; i>=0; i--) { 14 | tot += arr[i]; 15 | if (tot>=i) return i; 16 | } 17 | return 0; 18 | } 19 | 20 | public int hIndex1(int[] citations) { 21 | if (citations == null || citations.length == 0) return 0; 22 | Arrays.sort(citations); 23 | int len = citations.length; 24 | for (int i = 0; i < citations.length; i++) { 25 | if (len <= citations[i]) 26 | return len; 27 | else 28 | len--; 29 | } 30 | return len; 31 | } 32 | 33 | //�������� 34 | public int hIndex2(int[] citations) { 35 | Arrays.sort(citations); 36 | 37 | int n = citations.length; 38 | int i = 0, j = n - 1; 39 | 40 | while (i <= j) { 41 | int k = (i + j) / 2; 42 | int v = citations[k]; 43 | int h = n - k; 44 | if (v >= h) { 45 | j = k - 1; 46 | } else { 47 | i = k + 1; 48 | } 49 | } 50 | 51 | return n - j - 1; 52 | } 53 | 54 | public static void main(String[] args) { 55 | int [] tmp = {3, 0, 6, 1, 5}; 56 | int res = hIndex(tmp); 57 | 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/HashTable/inorderTraversal.java: -------------------------------------------------------------------------------- 1 | package HashTable; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Stack; 6 | 7 | public class inorderTraversal { 8 | public class TreeNode { 9 | int val; 10 | TreeNode left; 11 | TreeNode right; 12 | TreeNode(int x) { val = x; } 13 | } 14 | public List inorderTraversal(TreeNode root) { 15 | List list = new ArrayList<>(); 16 | Stack stack = new Stack<>(); 17 | TreeNode cur = root; 18 | while(cur!=null || !stack.empty()){ 19 | while(cur != null){ 20 | stack.add(cur); 21 | cur = cur.left; 22 | } 23 | cur = stack.pop(); 24 | list.add(cur.val); 25 | cur = cur.right; 26 | } 27 | return list; 28 | } 29 | 30 | 31 | public List inorderTraversal1(TreeNode root) { 32 | List res = new ArrayList<>(); 33 | // method 1: recursion 34 | 35 | helper(root, res); 36 | return res; 37 | } 38 | //helper function for method 1 39 | private void helper(TreeNode root, List res) { 40 | if (root != null) { 41 | if (root.left != null) { 42 | helper(root.left, res); 43 | } 44 | res.add(root.val); 45 | if (root.right != null) { 46 | helper(root.right, res); 47 | } 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/HashTable/isAnagram.java: -------------------------------------------------------------------------------- 1 | package HashTable; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class isAnagram { 7 | public boolean isAnagram(String s, String t) { 8 | Map tmp = new HashMap<>(); 9 | char [] ss = s.toCharArray(); 10 | char [] tt = t.toCharArray(); 11 | for(int i=0; i tmp = new HashSet<>(); 9 | while(true){ 10 | int sum = 0; 11 | while(n!=0){ 12 | sum += (n%10)*(n%10); 13 | n /= 10; 14 | } 15 | if(sum == 1) 16 | return true; 17 | else if(tmp.add(sum)) 18 | n = sum; 19 | else 20 | return false; 21 | } 22 | } 23 | 24 | public boolean isHappy1(int n) { 25 | int x = n; 26 | int y = n; 27 | while(x>1){ 28 | x = cal(x) ; 29 | if(x==1) return true ; 30 | y = cal(cal(y)); 31 | if(y==1) return true ; 32 | 33 | if(x==y) return false; 34 | } 35 | return true ; 36 | } 37 | public int cal(int n){ 38 | int x = n; 39 | int s = 0; 40 | while(x>0){ 41 | s = s+(x%10)*(x%10); 42 | x = x/10; 43 | } 44 | return s ; 45 | } 46 | 47 | public static void main(String[] args){ 48 | boolean aa = isHappy(18); 49 | System.out.println(aa); 50 | System.out.println((3%10)^2); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/HashTable/isIsomorphic.java: -------------------------------------------------------------------------------- 1 | package HashTable; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class isIsomorphic { 7 | public boolean isIsomorphic(String s, String t) { 8 | Map tmp = new HashMap<>(); 9 | char[] ss = s.toCharArray(); 10 | char[] tt = t.toCharArray(); 11 | for(int i=0; i=0 && k < heights.length && heights[j] <= heights[i] && heights[k] <= heights[i]){ 9 | if(heights[j] <= heights[i]) 10 | j--; 11 | if(heights[k] <= heights[i]) 12 | k++; 13 | } 14 | tmp = heights[i] * (k-j); 15 | res = Math.max(res, tmp); 16 | } 17 | 18 | return res; 19 | } 20 | 21 | public static void main(String [] args){ 22 | int [] heights = {2,1,5,6,2,3}; 23 | int res = largestRectangleArea(heights); 24 | System.out.println(res); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/HashTable/maximalRectangle.java: -------------------------------------------------------------------------------- 1 | package HashTable; 2 | 3 | import java.util.Stack; 4 | 5 | public class maximalRectangle { 6 | public int maximalRectangle(char[][] matrix) { 7 | if(matrix == null || matrix.length == 0 || matrix[0].length == 0) 8 | return 0; 9 | int rLen = matrix.length; 10 | int cLen = matrix[0].length; 11 | int [] h = new int[cLen+1]; 12 | h[cLen] = 0; 13 | int max = 0; 14 | 15 | for(int i=0; i stack = new Stack<>(); 17 | for(int j=0; jmax) 31 | max = area; 32 | } 33 | stack.push(i); 34 | } 35 | } 36 | } 37 | 38 | return max; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/HashTable/wordPattern.java: -------------------------------------------------------------------------------- 1 | package HashTable; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class wordPattern { 7 | public boolean wordPattern(String pattern, String str) { 8 | Map tmp = new HashMap<>(); 9 | String [] ss = str.split(" "); 10 | if(pattern.length() != ss.length) 11 | return false; 12 | for(int i=0; i n+1) 26 | slow = slow.next; 27 | }else{ //总长度为2*i+1 28 | while(i -- > n) 29 | slow = slow.next; 30 | } 31 | slow.next = slow.next.next; 32 | return head; 33 | } 34 | 35 | public ListNode removeNthFromEnd1(ListNode head, int n) { 36 | 37 | ListNode start = new ListNode(0); 38 | ListNode slow = start, fast = start; 39 | slow.next = head; 40 | 41 | //Move fast in front so that the gap between slow and fast becomes n 42 | for(int i=1; i<=n+1; i++) { 43 | fast = fast.next; 44 | } 45 | //Move fast to the end, maintaining the gap 46 | while(fast != null) { 47 | slow = slow.next; 48 | fast = fast.next; 49 | } 50 | //Skip the desired node 51 | slow.next = slow.next.next; 52 | return start.next; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/LinkedList/reverseList.java: -------------------------------------------------------------------------------- 1 | package LinkedList; 2 | 3 | /** 4 | * Created by liuchong on 2017/6/22. 5 | */ 6 | public class reverseList { 7 | public static class ListNode { 8 | int val; 9 | ListNode next; 10 | ListNode(int x) { 11 | val = x; 12 | } 13 | } 14 | 15 | public ListNode reverseList(ListNode head) { 16 | ListNode cur=head, next=head, pre=null; 17 | while(cur != null){ 18 | next = cur.next; 19 | cur.next = pre; 20 | pre = cur; 21 | cur = next; 22 | } 23 | return pre; 24 | } 25 | 26 | public static ListNode reverseList1(ListNode head){ 27 | ListNode cur = head; 28 | return dfs(cur, null); 29 | } 30 | 31 | public static ListNode dfs(ListNode cur, ListNode pre){ 32 | if(cur == null) 33 | return pre; 34 | ListNode next = cur.next; 35 | cur.next = pre; 36 | pre = cur; 37 | cur = next; 38 | return dfs(cur, pre); 39 | } 40 | 41 | public static void main(String[] args){ 42 | ListNode head = new ListNode(1); 43 | head.next = null; 44 | reverseList1(head); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/LinkedList/sortedListToBST.java: -------------------------------------------------------------------------------- 1 | package LinkedList; 2 | 3 | /** 4 | * Created by liuchong on 2017/7/9. 5 | */ 6 | public class sortedListToBST { 7 | 8 | public class ListNode { 9 | int val; 10 | ListNode next; 11 | ListNode(int x) { val = x; } 12 | } 13 | 14 | public class TreeNode { 15 | int val; 16 | TreeNode left; 17 | TreeNode right; 18 | TreeNode(int x) { val = x; } 19 | } 20 | public TreeNode sortedListToBST(ListNode head) { 21 | TreeNode res = new TreeNode(0); 22 | 23 | return res; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/LinkedList/swapPairs.java: -------------------------------------------------------------------------------- 1 | package LinkedList; 2 | 3 | /** 4 | * Created by liuchong on 2017/7/16. 5 | */ 6 | public class swapPairs { 7 | 8 | public static class ListNode { 9 | int val; 10 | ListNode next; 11 | ListNode(int x) { 12 | val = x; 13 | } 14 | } 15 | 16 | 17 | public ListNode swapPairs(ListNode head) { 18 | ListNode pHead = new ListNode(0); 19 | pHead.next = head; 20 | ListNode cur = pHead, next; 21 | while(head != null && head.next != null){ 22 | next = head.next; 23 | head.next = next.next; 24 | cur.next = next; 25 | next.next = head;cur = head; 26 | head = head.next; 27 | } 28 | return pHead.next; 29 | } 30 | 31 | public ListNode swapPairs1(ListNode head) { 32 | if ((head == null)||(head.next == null)) 33 | return head; 34 | ListNode n = head.next; 35 | head.next = swapPairs1(head.next.next); 36 | n.next = head; 37 | return n; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/MSRA_100/T001_TreeToList.java: -------------------------------------------------------------------------------- 1 | package MSRA_100; 2 | 3 | public class T001_TreeToList { 4 | public class TreeNode { 5 | int val = 0; 6 | TreeNode left = null; 7 | TreeNode right = null; 8 | 9 | public TreeNode(int val) { 10 | this.val = val; 11 | 12 | } 13 | } 14 | 15 | public TreeNode TreeToList(TreeNode root){ 16 | if(root == null) 17 | return null; 18 | if(root.left == null && root.right == null) 19 | return root; 20 | TreeNode left = TreeToList(root.left); 21 | TreeNode p = left; 22 | while(p != null && p.right != null) 23 | p = p.right; 24 | if(left != null){ 25 | left.right = root; 26 | root.left = p; 27 | } 28 | 29 | TreeNode right = TreeToList(root.right); 30 | if(right != null){ 31 | right.left = root; 32 | root.right = right; 33 | } 34 | 35 | return left != null ? left : root; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/MSRA_100/T002_MinStack.java: -------------------------------------------------------------------------------- 1 | package MSRA_100; 2 | 3 | import java.util.Stack; 4 | 5 | public class T002_MinStack { 6 | Stack s1 = new Stack<>(); 7 | Stack s2 = new Stack<>(); 8 | 9 | public void push(int node){ 10 | s1.push(node); 11 | if(s2.isEmpty() || s2.peek() >= node) 12 | s2.push(node); 13 | else 14 | s2.push(s2.peek()); 15 | } 16 | 17 | public void pop(){ 18 | s1.pop(); 19 | s2.pop(); 20 | } 21 | 22 | public int top(){ 23 | return s1.peek(); 24 | } 25 | 26 | public int min(){ 27 | return s2.peek(); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/MSRA_100/T003_maxSubArray.java: -------------------------------------------------------------------------------- 1 | package MSRA_100; 2 | 3 | public class T003_maxSubArray { 4 | public int maxSubArray(int [] array){ 5 | if(array == null || array.length == 0) 6 | return 0; 7 | int sum = array[0], max = array[0]; 8 | for(int i=1; i max) 14 | max = sum; 15 | } 16 | return max; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/MSRA_100/T004_FindPath.java: -------------------------------------------------------------------------------- 1 | package MSRA_100; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class T004_FindPath { 6 | 7 | public class TreeNode { 8 | int val = 0; 9 | TreeNode left = null; 10 | TreeNode right = null; 11 | public TreeNode(int val) {this.val = val;} 12 | } 13 | 14 | public ArrayList> FindPath(TreeNode root, int target) { 15 | ArrayList> res = new ArrayList<>(); 16 | if(root == null) 17 | return res; 18 | ArrayList path = new ArrayList<>(); 19 | int sum = 0; 20 | dfs(root, res, path, sum, target); 21 | return res; 22 | } 23 | 24 | public void dfs(TreeNode root, ArrayList> res, ArrayList path, int sum, int target){ 25 | if(root == null) 26 | return; 27 | sum += root.val; 28 | //说明已经是叶节点,判断sum是否等于target,如果等于则将path添加到res 29 | if(root.left == null && root.right == null){ 30 | if(sum == target){ 31 | path.add(root.val); 32 | res.add(new ArrayList(path)); 33 | path.remove(path.size()-1); 34 | } 35 | return; 36 | }else{ 37 | path.add(root.val); 38 | dfs(root.left, res, path, sum, target); 39 | dfs(root.right, res, path, sum, target); 40 | path.remove(path.size()-1); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/MSRA_100/T009_isPostOrder.java: -------------------------------------------------------------------------------- 1 | package MSRA_100; 2 | 3 | public class T009_isPostOrder { 4 | public boolean VerifySquenceOfBST(int [] sequence) { 5 | if(sequence == null || sequence.length == 0) return false; 6 | return help(sequence, 0, sequence.length-1); 7 | } 8 | 9 | public boolean help(int [] sequence, int start, int end){ 10 | if(start <= end) 11 | return true; 12 | int i = start; 13 | while(sequence[i] < sequence[end]) i++; 14 | int tmp = i; 15 | while(i < end){ 16 | if(sequence[i] < sequence[end]) 17 | return false; 18 | i++; 19 | } 20 | return help(sequence, start, tmp-1) && help(sequence, tmp, end-1); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/MSRA_100/T010_reverseWord.java: -------------------------------------------------------------------------------- 1 | package MSRA_100; 2 | 3 | public class T010_reverseWord { 4 | public String rotateString(String obj, Integer n) { 5 | if(obj == null || n < 0) 6 | return ""; 7 | char [] res = obj.toCharArray(); 8 | reverseCharArray(res, 0, n-1); 9 | reverseCharArray(res, n, res.length-1); 10 | reverseCharArray(res, 0, res.length-1); 11 | return String.valueOf(res); 12 | } 13 | 14 | public void reverseCharArray(char []chars, int first, int second) { 15 | while(first < second){ 16 | char tmp = chars[first]; 17 | chars[first++] = chars[second]; 18 | chars[second--] = tmp; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/MSRA_100/T012_Sum.java: -------------------------------------------------------------------------------- 1 | package MSRA_100; 2 | 3 | public class T012_Sum { 4 | //不甩乘除法、for、while循环、if、switch等关键字实现1,2.。。n求和 5 | public int sun(int n){ 6 | return 0; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/MSRA_100/T013_lastKNode.java: -------------------------------------------------------------------------------- 1 | package MSRA_100; 2 | 3 | import java.util.List; 4 | 5 | public class T013_lastKNode { 6 | public class ListNode { 7 | int val; 8 | ListNode next = null; 9 | 10 | ListNode(int val) { 11 | this.val = val; 12 | } 13 | } 14 | public ListNode FindKthToTail(ListNode head,int k) { 15 | int i=0; 16 | ListNode cur = head, second = head; 17 | while(cur.next != null){ 18 | i++; 19 | cur = cur.next; 20 | if(i>=k) 21 | second = second.next; 22 | } 23 | if(i > k) 24 | return null; 25 | return second; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/MSRA_100/T014_twoSum.java: -------------------------------------------------------------------------------- 1 | package MSRA_100; 2 | 3 | public class T014_twoSum { 4 | public int[] twoSum(int [] nums, int target){ 5 | int [] res = new int[2]; 6 | if(nums == null || nums.length < 2) 7 | return res; 8 | int i=0, j=nums.length-1; 9 | 10 | while(i> Print(TreeNode pRoot) { 20 | ArrayList> res = new ArrayList<>(); 21 | if(pRoot == null) 22 | return res; 23 | Queue q = new LinkedList<>(); 24 | int cur=1, next=0; 25 | q.add(pRoot); 26 | while(!q.isEmpty()){ 27 | ArrayList tmp = new ArrayList<>(); 28 | while(cur != 0){ 29 | TreeNode tr = q.poll(); 30 | cur --; 31 | tmp.add(tr.val); 32 | if(tr.left != null){ 33 | q.add(tr.left); 34 | next ++; 35 | } 36 | if(tr.right != null){ 37 | q.add(tr.right); 38 | next ++; 39 | } 40 | } 41 | 42 | res.add(new ArrayList(tmp)); 43 | cur = next; 44 | next = 0; 45 | } 46 | return res; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/MSRA_100/T017_firstSingle.java: -------------------------------------------------------------------------------- 1 | package MSRA_100; 2 | 3 | public class T017_firstSingle { 4 | 5 | public char firstSingle(String s){ 6 | int [] count = new int[256]; 7 | char[] ch = s.toCharArray(); 8 | for (int i=0; i= 1) 12 | count[ch[i]] = -1; 13 | } 14 | 15 | int min = s.length(); 16 | char res = ch[s.length()-1]; 17 | for(int i=0; i<256; i++){ 18 | if(count[i] >= 1 && min > count[i]) { 19 | min = count[i] - 1; 20 | res = (char)i; 21 | } 22 | } 23 | return res; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/MSRA_100/T018_LastRemaining.java: -------------------------------------------------------------------------------- 1 | package MSRA_100; 2 | 3 | public class T018_LastRemaining { 4 | public int LastRemaining_Solution(int n, int m) { 5 | if(n < 1 || m < 1) 6 | return -1; 7 | int last = 0; 8 | for(int i=2; i<=n; i++) 9 | last = (last + m)%i; 10 | return last; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/MSRA_100/T019_fibonacci.java: -------------------------------------------------------------------------------- 1 | package MSRA_100; 2 | 3 | public class T019_fibonacci { 4 | public int fibonacci(int n){ 5 | if(n <= 0) 6 | return 0; 7 | if(n == 1 || n == 2) 8 | return 1; 9 | int a=1, b=1, c=0; 10 | for(int i=3; i<=n; i++){ 11 | c = a+b; 12 | b=a; 13 | a=c; 14 | } 15 | return c; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/MSRA_100/T020_findCombination.java: -------------------------------------------------------------------------------- 1 | package MSRA_100; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class T020_findCombination { 6 | public void findCombination(int n,int m,int flagI[]){ 7 | if (n<1||m<1) { 8 | return; 9 | } 10 | if (n>m) { 11 | n=m; 12 | } 13 | if (n==m) { 14 | flagI[n-1]=1; 15 | for (int i = 0; i < flagI.length; i++) { 16 | if (flagI[i]==1) { 17 | System.out.print(i+1+" "); 18 | } 19 | 20 | } 21 | System.out.println(); 22 | flagI[n-1]=0; 23 | } 24 | 25 | flagI[n-1]=1; 26 | findCombination(n-1, m-n, flagI); 27 | 28 | flagI[n-1]=0; 29 | findCombination(n-1, m, flagI); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Sort_func/arraySort/arraySort/BubbleSort.java: -------------------------------------------------------------------------------- 1 | package Sort_func.arraySort.arraySort; 2 | 3 | /** 4 | * 冒泡排序 5 | * 比较相邻的元素。如果第一个比第二个大,就交换他们两个。 6 | * 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。 7 | * 针对所有的元素重复以上的步骤,除了最后一个。 8 | * 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。 9 | * Created by liuchong on 2017/6/27. 10 | */ 11 | public class BubbleSort { 12 | 13 | public void BubbleSort(int[] nums){ 14 | for(int i=0; i nums[j]) 17 | swap(nums, j); 18 | } 19 | } 20 | } 21 | 22 | public void swap(int[] nums, int i){ 23 | int tmp = nums[i]; 24 | nums[i] = nums[i+1]; 25 | nums[i+1] = tmp; 26 | } 27 | 28 | 29 | //冒泡排序算法有两种改进方式: 30 | //1,如果又一次循环,并未发生任何交换,则说明数组已经排序完成。可以设置一个标志来表示 31 | //2,记录某次遍历时最后发生数据交换的位置,这个位置之后的数据显然已经有序,不用再排序了。因此通过记录最后发生数据交换的位置就可以确定下次循环的范围了。 32 | public void BubbleSort1(int[] nums){ 33 | //最后发生交换的标志位 34 | int last = nums.length; 35 | for(int i=0; i nums[j]) { 39 | swap(nums, j); 40 | last = j; 41 | flag = false; 42 | } 43 | } 44 | if(flag) 45 | break; 46 | } 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/Sort_func/arraySort/arraySort/HeapSort.java: -------------------------------------------------------------------------------- 1 | package Sort_func.arraySort.arraySort; 2 | 3 | /** 4 | * Created by liuchong on 2017/6/28. 5 | */ 6 | public class HeapSort { 7 | } 8 | -------------------------------------------------------------------------------- /src/Sort_func/arraySort/arraySort/InsertionSort.java: -------------------------------------------------------------------------------- 1 | package Sort_func.arraySort.arraySort; 2 | 3 | /** 4 | * 从第一个元素开始,该元素可以认为已经被排序 5 | 取出下一个元素,在已经排序的元素序列中从后向前扫描 6 | 如果被扫描的元素(已排序)大于新元素,将该元素后移一位 7 | 重复步骤3,直到找到已排序的元素小于或者等于新元素的位置 8 | 将新元素插入到该位置后 9 | 重复步骤2~5 10 | * Created by liuchong on 2017/6/27. 11 | */ 12 | public class InsertionSort { 13 | 14 | public void InsertionSort(int[] nums){ 15 | for(int i=1; i=0; j--){ 20 | if(nums[j] > nums[i]) { 21 | nums[index] = nums[j]; 22 | index = j; 23 | }else 24 | break; 25 | } 26 | nums[index] = tmp; 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Sort_func/arraySort/arraySort/QuickSort.java: -------------------------------------------------------------------------------- 1 | package Sort_func.arraySort.arraySort; 2 | 3 | /** 4 | * 对于一个数组,我们选定一个基准数据(例如:数组中的最后一个或者第一个元素), 5 | * 剩下的数据组成一个新的数组,然后遍历这个新数组中的每一个元素, 6 | * 分别与基准元素进行对比,分别将小于基准元素和不小于基准元素的数据区分开来, 7 | * 这个时候基准元素在总的数组中的位置就确定了。然后, 8 | * 在分别对这个两个数组进行相同的操作,直到每一个元素的位置都唯一确定下来。 9 | * Created by liuchong on 2017/6/28. 10 | */ 11 | public class QuickSort { 12 | 13 | public void QuickSort(int[] nums){ 14 | sort(nums,0,nums.length-1); 15 | } 16 | 17 | private void sort(int[] a,int low,int high){ 18 | //左 19 | int l =low; 20 | //右 21 | int h = high; 22 | //基准值 23 | int k = a[low]; 24 | //判断一趟是否完成 25 | while(l=k) 28 | h--; 29 | if(llow) sort(a,low,l-1); 45 | if(h 0){ 18 | for(int i=gap; i=gap; j-=gap){ 20 | if(nums[j] < nums[j-gap]) 21 | swap(nums, j, j-gap); 22 | else 23 | break; 24 | } 25 | } 26 | gap = gap/2; 27 | } 28 | } 29 | 30 | public void swap(int[] nums, int i, int j){ 31 | int tmp = nums[i]; 32 | nums[i] = nums[j]; 33 | nums[j] = tmp; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/String/addBinary.java: -------------------------------------------------------------------------------- 1 | package String; 2 | 3 | /** 4 | * 5 | * 67. Add Binary 6 | 7 | Given two binary strings, return their sum (also a binary string). 8 | 9 | For example, 10 | a = "11" 11 | b = "1" 12 | Return "100". 13 | 14 | */ 15 | 16 | 17 | public class addBinary { 18 | 19 | //46% 20 | public String addBinary(String a, String b) { 21 | StringBuilder sb = new StringBuilder(); 22 | int i = a.length() - 1, j = b.length() -1, carry = 0; 23 | while (i >= 0 || j >= 0) { 24 | int sum = carry; 25 | if (j >= 0) sum += b.charAt(j--) - '0'; 26 | if (i >= 0) sum += a.charAt(i--) - '0'; 27 | sb.append(sum % 2); 28 | carry = sum / 2; 29 | } 30 | if (carry != 0) sb.append(carry); 31 | return sb.reverse().toString(); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/String/canConstruct.java: -------------------------------------------------------------------------------- 1 | package String; 2 | 3 | /** 4 | 5 | 383. Ransom Note 6 | 7 | Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false. 8 | 9 | Each letter in the magazine string can only be used once in your ransom note. 10 | 11 | Note: 12 | You may assume that both strings contain only lowercase letters. 13 | 14 | canConstruct("a", "b") -> false 15 | canConstruct("aa", "ab") -> false 16 | canConstruct("aa", "aab") -> true 17 | 18 | */ 19 | 20 | 21 | public class canConstruct { 22 | 23 | //45% 24 | public boolean canConstruct(String ransomNote, String magazine) { 25 | if(ransomNote.length() > magazine.length()) 26 | return false; 27 | int [] count = new int [26]; 28 | for(int i=0; i 0) 36 | return false; 37 | 38 | return true; 39 | } 40 | 41 | //87% 42 | public boolean canConstruct2(String ransomNote, String magazine) { 43 | int[] table = new int[26]; 44 | for (char c : magazine.toCharArray()) table[c - 'a']++; 45 | for (char c : ransomNote.toCharArray()) 46 | if (--table[c - 'a'] < 0) return false; 47 | return true; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/String/checkRecord.java: -------------------------------------------------------------------------------- 1 | package String; 2 | 3 | 4 | /* 5 | 6 | 551. Student Attendance Record I 7 | 8 | You are given a string representing an attendance record for a student. The record only contains the following three characters: 9 | 10 | 'A' : Absent. 11 | 'L' : Late. 12 | 'P' : Present. 13 | A student could be rewarded if his attendance record doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late). 14 | 15 | You need to return whether the student could be rewarded according to his attendance record. 16 | 17 | Example 1: 18 | Input: "PPALLP" 19 | Output: True 20 | Example 2: 21 | Input: "PPALLL" 22 | Output: False 23 | 24 | */ 25 | 26 | public class checkRecord { 27 | 28 | public static boolean checkRecord(String s) { 29 | char [] res = s.toCharArray(); 30 | int a=0, l=0; 31 | for(int i=0; i 0) 34 | return false; 35 | }else if(res[i] == 'L'){ 36 | if(res[i+1] == 'L' && res[i+2] == 'L') 37 | return false; 38 | } 39 | } 40 | return true; 41 | } 42 | 43 | public boolean checkRecord1(String s) { 44 | return !s.matches(".*LLL.*|.*A.*A.*"); 45 | } 46 | 47 | public boolean checkRecord2(String s) { 48 | return !s.contains("LLL") && (s.indexOf("A") == s.lastIndexOf("A")); 49 | } 50 | 51 | public static void main(String [] args){ 52 | checkRecord("LALL"); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/String/compress.java: -------------------------------------------------------------------------------- 1 | package String; 2 | 3 | public class compress { 4 | 5 | //46% 6 | public static int compress(char[] chars) { 7 | if(chars == null || chars.length <= 0) 8 | return 0; 9 | 10 | char var = chars[0]; 11 | int left=0, right=0; 12 | for(int i=0; i= chars.length) 23 | break; 24 | i = right; 25 | var = chars[right]; 26 | } 27 | return left; 28 | } 29 | 30 | public static void main(String[]args){ 31 | char[] s = {'a','a','b','b','c','c','c'}; 32 | System.out.println(compress(s)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/String/countSegments.java: -------------------------------------------------------------------------------- 1 | package String; 2 | 3 | /** 4 | 5 | 434. Number of Segments in a String 6 | 7 | Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters. 8 | 9 | Please note that the string does not contain any non-printable characters. 10 | 11 | Example: 12 | 13 | Input: "Hello, my name is John" 14 | Output: 5 15 | 16 | */ 17 | 18 | 19 | public class countSegments { 20 | 21 | //10% 22 | public static int countSegments(String s) { 23 | if(s == null || s.equals("") || s.trim().equals("")) 24 | return 0; 25 | String[] res = s.trim().split(" +"); 26 | return res.length; 27 | } 28 | 29 | //28% 30 | public int countSegments1(String s) { 31 | int res=0; 32 | for(int i=0; i= values[i]) { 24 | num -= values[i]; 25 | sb.append(strs[i]); 26 | } 27 | } 28 | return sb.toString(); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/String/lengthOfLastWord.java: -------------------------------------------------------------------------------- 1 | package String; 2 | 3 | /** 4 | 5 | 58. Length of Last Word 6 | 7 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. 8 | 9 | If the last word does not exist, return 0. 10 | 11 | Note: A word is defined as a character sequence consists of non-space characters only. 12 | 13 | Example: 14 | 15 | Input: "Hello World" 16 | Output: 5 17 | 18 | 19 | */ 20 | 21 | public class lengthOfLastWord { 22 | 23 | //59% 24 | public int lengthOfLastWord(String s) { 25 | return s.trim().length()-s.trim().lastIndexOf(" ")-1; 26 | } 27 | 28 | //59% 29 | public int lengthOfLastWord1(String s){ 30 | int count = -1, i = s.length(); 31 | while (--i >= 0 && s.charAt(i) == ' '); 32 | while (i - ++count >= 0 && s.charAt(i - count) != ' '); 33 | return count; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/String/reverseString.java: -------------------------------------------------------------------------------- 1 | package String; 2 | 3 | /** 4 | * Created by liuchong on 2017/11/9. 5 | 6 | 344. Reverse String 7 | 8 | Write a function that takes a string as input and returns the string reversed. 9 | ' 10 | Example: 11 | Given s = "hello", return "olleh". 12 | 13 | */ 14 | public class reverseString { 15 | 16 | public String reverseString(String s) { 17 | StringBuilder res = new StringBuilder(s); 18 | return res.reverse().toString(); 19 | } 20 | 21 | public String reverseString1(String s) { 22 | char[] word = s.toCharArray(); 23 | int i = 0; 24 | int j = s.length() - 1; 25 | while (i < j) { 26 | char temp = word[i]; 27 | word[i] = word[j]; 28 | word[j] = temp; 29 | i++; 30 | j--; 31 | } 32 | return new String(word); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Tree/pathSum.java: -------------------------------------------------------------------------------- 1 | package Tree; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | 113. Path Sum II 8 | Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. 9 | 10 | For example: 11 | Given the below binary tree and sum = 22, 12 | 5 13 | / \ 14 | 4 8 15 | / / \ 16 | 11 13 4 17 | / \ / \ 18 | 7 2 5 1 19 | return 20 | [ 21 | [5,4,11,2], 22 | [5,8,4,5] 23 | ] 24 | */ 25 | 26 | 27 | public class pathSum { 28 | 29 | public class TreeNode { 30 | int val; 31 | TreeNode left; 32 | TreeNode right; 33 | TreeNode(int x) { val = x; } 34 | } 35 | 36 | public List> pathSum(TreeNode root, int sum) { 37 | List> res = new ArrayList<>(); 38 | help(root, sum, res, new ArrayList()); 39 | return res; 40 | } 41 | 42 | public void help(TreeNode root, int sum, List> res ,List path){ 43 | if(root == null) 44 | return; 45 | if(root.left == null && root.right == null){ 46 | if(sum == root.val) { 47 | path.add(root.val); 48 | res.add(new ArrayList<>(path)); 49 | path.remove(path.size()-1); 50 | } 51 | return; 52 | } 53 | path.add(root.val); 54 | help(root.left, sum - root.val, res, path); 55 | help(root.right, sum - root.val, res, path); 56 | path.remove(path.size()-1); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/com/chenlei/array/FindTheKMin.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array; 2 | 3 | import com.chenlei.sort.QuickSort; 4 | 5 | /** 6 | * 2.1 寻找最小的k个数 7 | * @author chenlei 8 | * @since 2016 - 09 - 11 17:30 9 | */ 10 | public class FindTheKMin { 11 | 12 | private static int findK(int []a, int low, int high, int k) { 13 | int index = QuickSort.partition(a, low, high); 14 | if(k == (index - low + 1)) { 15 | return a[index]; 16 | } 17 | if(k < (index - low + 1)) { 18 | return findK(a, low, index - 1, k); 19 | } else { 20 | return findK(a, index + 1, high, k - (index - low + 1)); 21 | } 22 | } 23 | 24 | private static int findK(int []a, int k) { 25 | return findK(a, 0, a.length - 1, k); 26 | } 27 | 28 | public static void main(String[] args) { 29 | int[] a = {3,6,2,1,5,7}; 30 | System.out.println(findK(a,2)); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/com/chenlei/array/FindTheSumOfTwo.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array; 2 | 3 | import com.chenlei.sort.QuickSort; 4 | 5 | /** 6 | * 2.2 寻找和为定值的两个数 7 | * @author chenlei 8 | * @since 2016 - 09 - 11 20:16 9 | */ 10 | public class FindTheSumOfTwo { 11 | 12 | private static void findTheSumOfTwo(int a[], int sum) { 13 | QuickSort.quickSort(a, 0, a.length - 1); 14 | int low = 0, high = a.length - 1; 15 | while (low < high) { 16 | int currentSum = a[low] + a[high]; 17 | if (currentSum == sum) { 18 | System.out.println(a[low] + "+" + a[high] + "=" + sum); 19 | break; 20 | } 21 | if (currentSum > sum) { 22 | high--; 23 | } else { 24 | low++; 25 | } 26 | } 27 | } 28 | 29 | public static void main(String[] args) { 30 | // int a[] = {1, 2, 3, 5, 6, 8, 9}; 31 | int a[] = {3, 8, 1, 5, 9, 2, 6}; 32 | findTheSumOfTwo(a, 6); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/com/chenlei/array/HollandFlag.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array; 2 | 3 | import util.NumberUtils; 4 | 5 | /** 6 | * 2.7 荷兰国旗 7 | * @author chenlei 8 | * @since 2016 - 11 - 30 20:27 9 | */ 10 | public class HollandFlag { 11 | 12 | private static void improve(int[] arr) { 13 | int left = 0, current = 0, right = arr.length - 1; 14 | while(current <= right) { 15 | if(arr[current] == 0) { 16 | NumberUtils.swapInt(arr, left, current); 17 | left++; 18 | current++; 19 | } else if(arr[current] == 1) { 20 | current++; 21 | } else { 22 | NumberUtils.swapInt(arr, current, right); 23 | right--; 24 | } 25 | } 26 | NumberUtils.printInArray(arr); 27 | } 28 | 29 | public static void main(String[] args) { 30 | int[] array1 = {2, 0, 1, 0, 0, 2, 1, 1, 2}; 31 | improve(array1); 32 | int[] array2 = {0, 1, 2, 1, 1, 2, 0, 2, 1, 0}; 33 | improve(array2); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/com/chenlei/array/MatrixMultiply.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array; 2 | 3 | import util.NumberUtils; 4 | 5 | /** 6 | * 2.8 矩阵乘法 7 | * @author chenlei 8 | * @since 2016 - 12 - 03 12:51 9 | */ 10 | public class MatrixMultiply { 11 | 12 | private static void matrixMultiply(int[][] matrix1, int[][] matrix2, int [][] matrixMultiply) { 13 | for(int i = 0; i < matrix1.length; i++) { 14 | for(int j = 0; j < matrix2[0].length; j++) { 15 | int sum = 0; 16 | for(int k = 0; k < matrix2.length; k++) { 17 | sum += matrix1[i][k] * matrix2[k][j]; 18 | } 19 | matrixMultiply[i][j] = sum; 20 | } 21 | } 22 | } 23 | 24 | public static void main(String[] args) { 25 | int[][] matrix1 = new int[2][3]; 26 | matrix1[0][0] = 0; 27 | matrix1[0][1] = 1; 28 | matrix1[0][2] = 2; 29 | matrix1[1][0] = 3; 30 | matrix1[1][1] = 4; 31 | matrix1[1][2] = 5; 32 | int[][] matrix2 = new int[3][2]; 33 | matrix2[0][0] = 0; 34 | matrix2[0][1] = 1; 35 | matrix2[1][0] = 2; 36 | matrix2[1][1] = 3; 37 | matrix2[2][0] = 4; 38 | matrix2[2][1] = 5; 39 | int [][] multiplyResult = new int [2][2]; 40 | matrixMultiply(matrix1, matrix2, multiplyResult); 41 | NumberUtils.printInMatrix(multiplyResult); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/com/chenlei/array/MaxSumOfContinueSubArray.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array; 2 | 3 | /** 4 | * 2.4 最大连续子数组的和 5 | * @author chenlei 6 | * @since 2016 - 11 - 21 20:01 7 | */ 8 | public class MaxSumOfContinueSubArray { 9 | 10 | public static Integer maxSum(int array[]) { 11 | Integer lastSum = array[0]; 12 | Integer maxSum = array[0]; 13 | 14 | for(int i = 1; i < array.length; i++) { 15 | if(lastSum > 0) { 16 | lastSum = lastSum + array[i]; 17 | } else { 18 | lastSum = array[i]; 19 | } 20 | if(lastSum > maxSum) { 21 | maxSum = lastSum; 22 | } 23 | } 24 | return maxSum; 25 | } 26 | 27 | public static void main(String[] args) { 28 | int array[] = {1, -2, 3, 10, -4, 7, 2, -5}; 29 | System.out.println(maxSum(array)); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/com/chenlei/array/OddEvenSort.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array; 2 | 3 | import util.NumberUtils; 4 | 5 | /** 6 | * 2.6 奇偶数排序 7 | * @author chenlei 8 | * @since 2016 - 11 - 29 20:32 9 | */ 10 | public class OddEvenSort { 11 | 12 | private static void byMiddle(int []array) { 13 | int before = 0, after = array.length - 1; 14 | while (true) { 15 | while(before <= after && NumberUtils.isOdd(array[before])) before++; 16 | while(before <= after && !NumberUtils.isOdd(array[after])) after--; 17 | if(before > after) { 18 | break; 19 | } 20 | NumberUtils.swapInt(array, before, after); 21 | } 22 | NumberUtils.printInArray(array); 23 | } 24 | 25 | private static void byLeft(int []array) { 26 | int before = 0, after; 27 | while(true) { 28 | while(before < array.length && NumberUtils.isOdd(array[before])) before++; 29 | after = before + 1; 30 | while(after < array.length && !NumberUtils.isOdd(array[after])) after++; 31 | if(after >= array.length) { 32 | break; 33 | } 34 | NumberUtils.swapInt(array, before, after); 35 | } 36 | NumberUtils.printInArray(array); 37 | } 38 | 39 | 40 | public static void main(String[] args) { 41 | int []array = {3, 2, 4, 5, 7, 6}; 42 | byMiddle(array); 43 | byLeft(array); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/com/chenlei/array/UpStep.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * 2.5 跳台阶问题 8 | * @author chenlei 9 | * @since 2016 - 11 - 28 20:53 10 | */ 11 | public class UpStep { 12 | 13 | public static int ways(int n) { 14 | if(n < 3) { 15 | return n; 16 | } 17 | List list = new ArrayList<>(); 18 | list.add(1); 19 | list.add(2); 20 | for(int i = 2; i < n; i++) { 21 | list.add(list.get(i - 1) + list.get(i - 2)); 22 | } 23 | return list.get(list.size() - 1); 24 | } 25 | 26 | public static void main(String[] args) { 27 | System.out.println(ways(4)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/com/chenlei/array/back/FindSumOfManyInKNum.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array.back; 2 | 3 | import com.chenlei.sort.QuickSort; 4 | import util.NumberUtils; 5 | 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | 9 | /** 10 | * 2.3.3 寻找和为S的K个数的组合 11 | * @author chenlei 12 | * @since 2017 - 03 - 01 20:46 13 | */ 14 | public class FindSumOfManyInKNum { 15 | 16 | private static void findTheSumOfManyByCut(int a[], int s, int k, int index, List list, int leftTotal) { 17 | if(s == 0 && list.size() == k) { 18 | System.out.println(list); 19 | return; 20 | } 21 | if(index >= a.length || list.size() > k) { 22 | return; 23 | } 24 | if(s - a[index] >= 0) { 25 | list.add(a[index]); 26 | findTheSumOfManyByCut(a, s - a[index], k, index + 1, list, leftTotal - a[index]); 27 | list.remove(list.size() - 1); 28 | } 29 | 30 | if(leftTotal - a[index] >= s) { 31 | while((index + 1) < a.length && a[index] == a[index+1]) { 32 | index++; 33 | } 34 | findTheSumOfManyByCut(a, s, k, index + 1, list, leftTotal - a[index]); 35 | } 36 | } 37 | 38 | public static void main(String[] args) { 39 | int a[] = {0, 1, 1, 1, 2, 3}; 40 | QuickSort.quickSort(a, 0, a.length - 1); 41 | NumberUtils.printInArray(a); 42 | findTheSumOfManyByCut(a, 3, 2, 0, new ArrayList<>(), NumberUtils.sum(a)); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/com/chenlei/array/back/FindTheSumOfManyOnce.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array.back; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * 2.3.2 寻找和为定值的若干个数 8 | * @author chenlei 9 | * @since 2017 - 03 - 01 20:40 10 | */ 11 | public class FindTheSumOfManyOnce { 12 | 13 | private static boolean findTheSumOfManyByCut(int target, int i, int nowValue, List list) { 14 | if(nowValue == target) { 15 | System.out.println(list); 16 | return true; 17 | } 18 | if(i < 1) { 19 | return false; 20 | } 21 | boolean result = false; 22 | if(nowValue + i <= target) { 23 | list.add(i); 24 | result = findTheSumOfManyByCut(target, i - 1, nowValue + i, list); 25 | list.remove(list.size() - 1); 26 | } 27 | if(!result) { 28 | if ((1 + i - 1) * (i - 1) / 2 >= target - nowValue) { 29 | result = findTheSumOfManyByCut(target, i - 1, nowValue, list); 30 | } 31 | } 32 | return result; 33 | } 34 | 35 | public static void main(String[] args) { 36 | findTheSumOfManyByCut(15, 10, 0, new ArrayList<>()); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/com/chenlei/array/back/FindTheSumOfTwoAll.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array.back; 2 | 3 | import com.chenlei.sort.QuickSort; 4 | 5 | /** 6 | * 2.2.2 找到所有满足和为定值的整数对 7 | * 8 | * @author chenlei 9 | * @since 2016 - 11 - 19 11:58 10 | */ 11 | public class FindTheSumOfTwoAll { 12 | 13 | private static void findTheSumOfTwoAll(int a[], int sum) { 14 | QuickSort.quickSort(a, 0, a.length - 1); 15 | int low = 0, high = a.length - 1; 16 | while (low < high) { 17 | int currentSum = a[low] + a[high]; 18 | if (currentSum == sum) { 19 | System.out.println(a[low] + "+" + a[high] + "=" + sum); 20 | low++; 21 | high--; 22 | continue; 23 | } 24 | if (currentSum > sum) { 25 | high--; 26 | } else { 27 | low++; 28 | } 29 | } 30 | } 31 | 32 | public static void main(String[] args) { 33 | int a[] = {3, 4, 1, 5, 9, 2, 6}; 34 | findTheSumOfTwoAll(a, 6); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/com/chenlei/array/back/MaxProductOfContinueSubArray.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array.back; 2 | 3 | import util.NumberUtils; 4 | 5 | /** 6 | * 2.4.4 连续子数组的最大乘积 7 | * @author chenlei 8 | * @since 2017 - 03 - 03 20:41 9 | */ 10 | public class MaxProductOfContinueSubArray { 11 | 12 | private static int maxProduct(int a[]) { 13 | int maxProductEver = a[0]; 14 | int maxProductForNow = a[0], minProductForNow = a[0]; 15 | for(int i = 1; i < a.length; i++) { 16 | maxProductForNow = NumberUtils.maxOfThree(a[i], maxProductForNow * a[i], minProductForNow*a[i]); 17 | minProductForNow = NumberUtils.minOfThree(a[i], maxProductForNow * a[i], minProductForNow*a[i]); 18 | if(maxProductForNow > maxProductEver) { 19 | maxProductEver = maxProductForNow; 20 | } 21 | } 22 | return maxProductEver; 23 | } 24 | 25 | public static void main(String[] args) { 26 | int a[] = {1, -2, 3, 10, -4, 7, 2, -5}; 27 | System.out.println(maxProduct(a)); 28 | int b[] = {2, 3, -2, 4}; 29 | System.out.println(maxProduct(b)); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/com/chenlei/array/back/MaxSumOfSubMatrix.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array.back; 2 | 3 | import com.chenlei.array.MaxSumOfContinueSubArray; 4 | 5 | /** 6 | * 2.4.6 最大子矩阵和 7 | * @author chenlei 8 | * @since 2017 - 03 - 04 10:55 9 | */ 10 | public class MaxSumOfSubMatrix { 11 | 12 | //O(n^3) 13 | private static int maxSum(int a[][],int b[]) { 14 | int maxValue = 0; 15 | for(int i = 0; i < a.length; i++) { 16 | init(b); 17 | for(int j = i; j < a.length; j++) { 18 | add(a[j], b); 19 | int currentMax = MaxSumOfContinueSubArray.maxSum(b); 20 | if(currentMax > maxValue) { 21 | maxValue = currentMax; 22 | } 23 | } 24 | } 25 | return maxValue; 26 | } 27 | 28 | private static void init(int b[]) { 29 | for(int i = 0; i < b.length; i++) { 30 | b[i] = 0; 31 | } 32 | } 33 | 34 | private static void add(int a[], int b[]) { 35 | for(int i = 0; i < a.length; i++) { 36 | b[i] = a[i] + b[i]; 37 | } 38 | } 39 | 40 | public static void main(String[] args) { 41 | int a[][] = { 42 | {0, -2, -7, 0}, 43 | {9, 2, -6, 2}, 44 | {-4, 1, -4, 1}, 45 | {-1, 8, 0, -2} 46 | }; 47 | int b[] = {0, 0, 0, 0}; 48 | System.out.println(maxSum(a, b)); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/com/chenlei/array/back/PosiNegaResort.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array.back; 2 | 3 | import util.NumberUtils; 4 | 5 | /** 6 | * 2.6.1 正负数重新排序(不改变相对顺序) 7 | * @author chenlei 8 | * @since 2017 - 03 - 04 21:39 9 | */ 10 | public class PosiNegaResort { 11 | 12 | private static void resort(int[] a) { 13 | int nega = 0, posi = 0; 14 | int negaEnd; 15 | while (posi < a.length && nega < a.length) { 16 | while(posi < a.length && a[posi] < 0) { 17 | posi++; 18 | } 19 | if(posi >= a.length) { 20 | break; 21 | } 22 | nega = posi + 1; 23 | while(nega < a.length && a[nega] >= 0) { 24 | nega++; 25 | } 26 | if(nega >= a.length) { 27 | break; 28 | } 29 | negaEnd = nega + 1; 30 | while(negaEnd < a.length && a[negaEnd] < 0) { 31 | negaEnd++; 32 | } 33 | NumberUtils.reverseNoChanged(a, posi, nega, negaEnd - 1); 34 | posi = negaEnd - (nega - posi); 35 | } 36 | } 37 | 38 | 39 | public static void main(String[] args) { 40 | int []a = {1, 7, -5, 9, -12, 15}; 41 | resort(a); 42 | NumberUtils.printInArray(a); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/com/chenlei/array/back/ShortestSubStringOfSumS.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array.back; 2 | 3 | /** 4 | * 2.4.5 满足条件的长度最短的连续子序列 5 | * @author chenlei 6 | * @since 2017 - 03 - 04 10:28 7 | */ 8 | public class ShortestSubStringOfSumS { 9 | 10 | private static void getShortestSubString(int a[], int s) { 11 | int begin = 0, end = 0, sum = 0; 12 | int minBegin = 0, minLength = Integer.MAX_VALUE; 13 | while(end < a.length) { 14 | if(sum < s) { 15 | sum += a[end]; 16 | end++; 17 | } else { 18 | if(end - begin < minLength) { 19 | minBegin = begin; 20 | minLength = end - begin; 21 | } 22 | sum -= a[begin]; 23 | begin++; 24 | } 25 | } 26 | System.out.println("满足条件的最短序列从"+minBegin+"开始,总长度为"+minLength); 27 | } 28 | 29 | 30 | public static void main(String[] args) { 31 | int a[] = {1, 2, 3, 10, 5, 7, 2, 5}; 32 | getShortestSubString(a, 15); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/com/chenlei/array/practice/DistanceOfStation.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array.practice; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * 37.站点之间的距离 8 | * @author chenlei 9 | * @since 2017 - 05 - 21 10:34 10 | */ 11 | public class DistanceOfStation { 12 | 13 | private static List initCycles(int distance[]) { 14 | List forNow = new ArrayList<>(); 15 | int sum = 0; 16 | forNow.add(sum); 17 | for(int i : distance) { 18 | sum += i; 19 | forNow.add(sum); 20 | } 21 | return forNow; 22 | } 23 | 24 | //求两站之间的距离,由加法转化为减法 25 | public static void main(String[] args) { 26 | int distance[] = {3, 1, 7, 5, 4, 2}; 27 | List info = initCycles(distance); 28 | int i = 0, j = distance.length - 1; // 求第一个到最后一个站点的距离 29 | int length = info.get(j) - info.get(i); 30 | int total = info.get(info.size() - 1); 31 | System.out.println(length < total - length ? length : total - length); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/com/chenlei/array/practice/DoubleLS.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array.practice; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * 20. 双端LIS 7 | * @author chenlei 8 | * @since 2017 - 03 - 22 17:12 9 | */ 10 | public class DoubleLS { 11 | 12 | private static int getMinDelete(int a[]) { 13 | List nega = LS.lisBinary(a); 14 | List posi = LS.ldsBasicDp(a); 15 | int max = Integer.MIN_VALUE; 16 | for(int i = 0; i < a.length; i++) { 17 | int iLength = nega.get(i) + posi.get(i) - 1; 18 | max = max > iLength ? max : iLength; 19 | } 20 | return max; 21 | } 22 | 23 | public static void main(String[] args) { 24 | int a[] = {2, 1, 5, 3, 6, 4, 8, 9, 7}; 25 | System.out.println(getMinDelete(a)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/com/chenlei/array/practice/EggAndBasket.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array.practice; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * 28. 鸡蛋放篮子 8 | * @author chenlei 9 | * @since 2017 - 05 - 18 14:20 10 | */ 11 | public class EggAndBasket { 12 | 13 | 14 | //回溯剪枝 15 | private static void printAllWays(int eggs, int baskets, List oneMethod) { 16 | if(eggs == 0 || baskets == 0) { 17 | if(eggs == 0 && baskets == 0) { 18 | //刚好分完 19 | System.out.println(oneMethod); 20 | } 21 | return; 22 | } 23 | for(int i = 1; i <= eggs; i++) { 24 | if(oneMethod.size() != 0) { 25 | if(i > oneMethod.get(oneMethod.size() - 1)) { 26 | //鸡蛋分配必须按照降序 27 | break; 28 | } 29 | } 30 | if(i * baskets < eggs) { 31 | continue; 32 | } 33 | oneMethod.add(i); 34 | printAllWays(eggs - i, baskets - 1, oneMethod); 35 | oneMethod.remove(oneMethod.size() - 1); 36 | } 37 | } 38 | 39 | 40 | public static void main(String[] args) { 41 | printAllWays(9, 5, new ArrayList<>()); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/com/chenlei/array/practice/FindContinueSeqSumOfTarget.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array.practice; 2 | 3 | /** 4 | * 12 寻找和为定值的连续序列 5 | * @author chenlei 6 | * @since 2017 - 03 - 12 11:15 7 | */ 8 | public class FindContinueSeqSumOfTarget { 9 | 10 | private static void findContinueSeqSumOfTarget(int n) { 11 | int before = 1, after = 2; 12 | int nowValue = 1 + 2; 13 | while (before < after && after <= (n / 2 + 1)) { 14 | if(nowValue == n) { 15 | print(before, after); 16 | nowValue -= before++; 17 | nowValue += ++after; 18 | } else if(nowValue < n) { 19 | nowValue += ++after; 20 | } else { 21 | nowValue -= before++; 22 | } 23 | } 24 | } 25 | 26 | private static void print(int begin, int end) { 27 | for(int i = begin; i <= end; i++) { 28 | System.out.print(i + " "); 29 | } 30 | System.out.println(); 31 | } 32 | 33 | public static void main(String[] args) { 34 | findContinueSeqSumOfTarget(15); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/com/chenlei/array/practice/FindNumsCloseOne.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array.practice; 2 | 3 | import util.NumberUtils; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | /** 9 | * 11. 寻找接近给定和的若干个数 10 | * @author chenlei 11 | * @since 2017 - 03 - 12 10:41 12 | */ 13 | public class FindNumsCloseOne { 14 | 15 | private static Integer closeValue = Integer.MAX_VALUE; 16 | 17 | private static void findNumsCloseOne(int a[], int index, int target, List tempList, int nowValue, List closeList) { 18 | if(NumberUtils.distance(target, nowValue) < NumberUtils.distance(target, closeValue)) { 19 | closeValue = nowValue; 20 | closeList.clear(); 21 | closeList.addAll(tempList); 22 | } 23 | if(index >= a.length || nowValue > target) { 24 | return; 25 | } 26 | //不包含a[index] 27 | findNumsCloseOne(a, index + 1, target, tempList, nowValue, closeList); 28 | //包含a[index] 29 | tempList.add(a[index]); 30 | findNumsCloseOne(a, index + 1, target, tempList, nowValue + a[index], closeList); 31 | tempList.remove(tempList.size() - 1); 32 | } 33 | 34 | public static void main(String[] args) { 35 | int a[] = {1, 2, 4, 7, 8, 11, 14, 17, 23}; 36 | List closeList = new ArrayList<>(); 37 | findNumsCloseOne(a, 0, 42, new ArrayList<>(), 0, closeList); 38 | System.out.println(closeList); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/com/chenlei/array/practice/FindTheMaxRectangle.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array.practice; 2 | 3 | import java.util.Stack; 4 | 5 | /** 6 | * 17. 寻找直方图中面积最大的矩形 7 | * @author chenlei 8 | * @since 2017 - 03 - 21 18:19 9 | */ 10 | public class FindTheMaxRectangle { 11 | 12 | private static void findTheMaxRectangle(int a[]) { 13 | Stack stack = new Stack<>(); 14 | stack.push(0); 15 | int maxRectangle = a[0]; 16 | for(int i = 1; i < a.length; i++) { 17 | if(stack.empty() || a[i] >= a[stack.peek()]) { 18 | stack.push(i); 19 | } else { 20 | int topIndex = stack.pop(); 21 | maxRectangle = maxRectangle > (i - topIndex) * a[topIndex] ? maxRectangle : (i - topIndex) * a[topIndex]; 22 | i--; 23 | } 24 | } 25 | System.out.println("maxRectangle is " + maxRectangle); 26 | } 27 | 28 | public static void main(String[] args) { 29 | int a[] = {2, 1, 5, 6, 2, 3}; 30 | findTheMaxRectangle(a); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/com/chenlei/array/practice/FindTheMiddleOfTwoNoSortArray.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array.practice; 2 | 3 | import com.chenlei.sort.QuickSort; 4 | 5 | /** 6 | * 8. 求两个无序数组的中位数 7 | * @author chenlei 8 | * @since 2017 - 03 - 11 9:37 9 | */ 10 | public class FindTheMiddleOfTwoNoSortArray { 11 | 12 | private static Integer findTheK(int a[], int b[], int low, int high, int k) { 13 | int index = QuickSort.partitionByTwoArray(a, b, low, high); 14 | if(k == (index - low + 1)) { 15 | return index < a.length ? a[index] : b[index - a.length]; 16 | } 17 | if(k < (index - low + 1)) { 18 | return findTheK(a, b, low, index - 1, k); 19 | } else { 20 | return findTheK(a, b, index + 1, high, k - (index - low + 1)); 21 | } 22 | } 23 | 24 | private static Integer findTheMiddle(int a[], int b[]) { 25 | int middle = findTheK(a, b, 0, a.length + b.length - 1, (a.length + b.length)/2 + 1); 26 | if((a.length + b.length) % 2 == 0) { 27 | //偶数长度 28 | int before = findTheK(a, b, 0, a.length + b.length - 1, (a.length + b.length)/2); 29 | middle = (before + middle) / 2; 30 | } 31 | return middle; 32 | } 33 | 34 | public static void main(String[] args) { 35 | int a[] = {9, 1, 2, 7}; 36 | int b[] = {4, 3, 9, 5, 8}; 37 | System.out.println(findTheMiddle(a, b)); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/com/chenlei/array/practice/FindThePair.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array.practice; 2 | 3 | import util.NumberUtils; 4 | 5 | import static com.chenlei.sort.QuickSort.quickSort; 6 | 7 | /** 8 | * 9. 寻找满足条件的数对 9 | * @author chenlei 10 | * @since 2017 - 03 - 11 10:24 11 | */ 12 | public class FindThePair { 13 | 14 | private static void printThePair(int a[]) { 15 | int first = 0, second = 1; 16 | while(second < a.length) { 17 | if(a[first] * 2 == a[second]) { 18 | System.out.println("first is " + a[first] + ", second is " + a[second]); 19 | first++; 20 | second++; 21 | } else { 22 | if(a[first] * 2 < a[second]) { 23 | first++; 24 | } else { 25 | second++; 26 | } 27 | } 28 | } 29 | } 30 | 31 | public static void main(String[] args) { 32 | int array[] = {10, 3, 2, 5, 4, 7, 1}; 33 | quickSort(array, 0, array.length - 1); 34 | NumberUtils.printInArray(array); 35 | printThePair(array); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/com/chenlei/array/practice/FindTheTwoOfMaxIndexReduce.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array.practice; 2 | 3 | import com.chenlei.sort.QuickSort; 4 | import util.NumberUtils; 5 | 6 | /** 7 | * 16.寻找下标差值最大的两个数 8 | * @author chenlei 9 | * @since 2017 - 03 - 20 20:06 10 | */ 11 | public class FindTheTwoOfMaxIndexReduce { 12 | 13 | //问题转换为求数组中两个数的最大差值(后面的数-前面的数),时间O(n),空间O(n) 14 | private static void findTheTwoOfMaxIndexReduce(int a[]) { 15 | int maxReduce = Integer.MIN_VALUE; 16 | int before = 0, after = 0; 17 | for(int i = 1; i < a.length; i++) { 18 | if(a[i] < a[before]) { 19 | before = i; 20 | } else { 21 | if(a[i] - a[before] > maxReduce) { 22 | maxReduce = a[i] - a[before]; 23 | after = i; 24 | } 25 | } 26 | } 27 | System.out.println("before = " + before + " after = " + after); 28 | } 29 | 30 | public static void main(String[] args) { 31 | //先对数组排序,并替换下标 32 | int a[] = {3, 1, 2, 5, 4}; 33 | QuickSort.quickSort(a, 0, a.length - 1); 34 | NumberUtils.printInArray(a); 35 | a[0] = 1; 36 | a[1] = 2; 37 | a[2] = 0; 38 | a[3] = 4; 39 | a[4] = 3; 40 | NumberUtils.printInArray(a); 41 | findTheTwoOfMaxIndexReduce(a); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/com/chenlei/array/practice/FindTheTwoProperNum.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array.practice; 2 | 3 | import util.NumberUtils; 4 | 5 | import static com.chenlei.sort.QuickSort.quickSort; 6 | 7 | /** 8 | * 10. 寻找满足条件的两个数(寻找其和最接近0的两个数) 9 | * @author chenlei 10 | * @since 2017 - 03 - 11 10:31 11 | */ 12 | public class FindTheTwoProperNum { 13 | 14 | private static void findTheTwoNum(int a[]) { 15 | int before = 0, after = a.length - 1; 16 | int min = Integer.MAX_VALUE, minBefore = -1, minAfter = -1; 17 | while(before < after) { 18 | int now = a[before] + a[after]; 19 | if(NumberUtils.abs(now) < min) { 20 | min = NumberUtils.abs(now); 21 | minBefore = before; 22 | minAfter = after; 23 | if(min == 0) { 24 | break; 25 | } 26 | } 27 | if(now > 0) { 28 | after--; 29 | } else { 30 | before++; 31 | } 32 | } 33 | System.out.println("min is " + min + ", before=" + a[minBefore] + ", after=" + a[minAfter]); 34 | } 35 | 36 | 37 | public static void main(String[] args) { 38 | int array[] = {7, -3, 2, -1, -5, -4, 6, 1}; 39 | quickSort(array, 0, array.length - 1); 40 | NumberUtils.printInArray(array); 41 | findTheTwoNum(array); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/com/chenlei/array/practice/JosephProblem.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array.practice; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * 49. 约瑟夫环问题 8 | * @author chenlei 9 | * @since 2017 - 05 - 24 11:09 10 | */ 11 | public class JosephProblem { 12 | 13 | //O(n)算法 14 | private static void basic(List circle, int m) { 15 | int nowIndex = 0; 16 | while(circle.size() > 1) { 17 | int steps = (m - 1) % circle.size(); //往前走的步数 18 | nowIndex = (nowIndex + steps) % circle.size(); 19 | circle.remove(nowIndex); 20 | } 21 | } 22 | 23 | public static void main(String[] args) { 24 | List circle = new ArrayList<>(); 25 | for(int i = 0; i < 10; i++) { 26 | circle.add(i); 27 | } 28 | basic(circle, 8); 29 | System.out.println(circle); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/com/chenlei/array/practice/MinAbs.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array.practice; 2 | 3 | import util.NumberUtils; 4 | 5 | /** 6 | * 18. 数组中的最小绝对值 7 | * @author chenlei 8 | * @since 2017 - 03 - 21 19:34 9 | */ 10 | public class MinAbs { 11 | 12 | private static int minAbs(int a[], int before, int after) { 13 | int begin = before, end = after; 14 | while(begin <= end) { 15 | int middle = (begin + end) / 2; 16 | if(a[middle] == 0) { 17 | return 0; 18 | } else if(a[middle] < 0) { 19 | begin = middle + 1; 20 | } else { 21 | end = middle - 1; 22 | } 23 | } 24 | if(end < before) { 25 | return a[begin]; 26 | } else if(begin > after) { 27 | return a[after]; 28 | } else { 29 | return NumberUtils.abs(a[begin]) < NumberUtils.abs(a[end]) ? a[begin] : a[end]; 30 | } 31 | } 32 | 33 | public static void main(String[] args) { 34 | int a[] = {-3, -2, -1, 2, 3, 4}; 35 | System.out.println(minAbs(a, 0, a.length - 1)); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/com/chenlei/array/practice/MinOfRotateNum.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array.practice; 2 | 3 | import util.NumberUtils; 4 | 5 | /** 6 | * 27. 旋转数组的最小元素 7 | * @author chenlei 8 | * @since 2017 - 05 - 18 11:17 9 | */ 10 | public class MinOfRotateNum { 11 | 12 | private static int minOfRotateNum(int []a, int begin, int end) { 13 | int before = begin, after = end; 14 | while(before < after) { 15 | int middle = (before + after) / 2; 16 | if(a[before] < a[middle]) { 17 | if(a[middle] <= a[after]) { 18 | //整个数组升序 19 | return a[before]; 20 | } 21 | //最小数在后半段 22 | before = middle + 1; 23 | } else if(a[before] > a[middle]) { 24 | //最小数在前半段 25 | after = middle; 26 | } else { 27 | //a[before == a[middle] 28 | if(a[middle] == a[after]) { 29 | return NumberUtils.min(minOfRotateNum(a, before, middle - 1), minOfRotateNum(a, middle + 1, after)); 30 | } else if(a[middle] > a[after]) { 31 | before = middle + 1; 32 | } else { 33 | return a[before]; 34 | } 35 | } 36 | } 37 | return a[before]; 38 | } 39 | 40 | public static void main(String[] args) { 41 | int[] a = {1, 1, 1, 0, 0, 1}; 42 | System.out.println(minOfRotateNum(a, 0, a.length - 1)); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/com/chenlei/array/practice/NotDivisionConquer.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array.practice; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * 54.不用除法运算 8 | * @author chenlei 9 | * @since 2017 - 05 - 26 16:16 10 | */ 11 | public class NotDivisionConquer { 12 | 13 | //一个数的值等于左边乘积x右边乘积 14 | private static void conquer(int a[], List result) { 15 | int lastMatrix = 1; 16 | for(int i : a) { 17 | result.add(lastMatrix); 18 | lastMatrix = lastMatrix * i; 19 | } 20 | lastMatrix = 1; 21 | for(int i = result.size() - 1; i >= 0; i--) { 22 | result.set(i, result.get(i) * lastMatrix); 23 | lastMatrix = lastMatrix * a[i]; 24 | } 25 | } 26 | 27 | public static void main(String[] args) { 28 | int a[] = {2, 3, 4, 5, 6, 7}; 29 | List b = new ArrayList<>(); 30 | conquer(a, b); 31 | System.out.println(b); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/com/chenlei/array/practice/OneOccurrence.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array.practice; 2 | 3 | /** 4 | * 4. n个整数中1出现的次数 5 | * @author chenlei 6 | * @since 2016 - 12 - 11 19:45 7 | */ 8 | public class OneOccurrence { 9 | 10 | private static int one(String sb) { 11 | if(sb.length() == 1) { 12 | if(Integer.valueOf(sb) == 0) { 13 | return 0; 14 | } else { 15 | return 1; 16 | } 17 | } 18 | Integer firstNum = sb.charAt(0) - '0'; 19 | Integer otherNum = Integer.valueOf(sb.substring(1, sb.length())); 20 | int firstOneCount = 1; 21 | if(firstNum == 1) { 22 | firstOneCount = otherNum + 1; 23 | } else { 24 | for(int i = 0; i < sb.length() - 1; i++) { 25 | firstOneCount *= 10; 26 | } 27 | } 28 | StringBuilder temp = new StringBuilder(); 29 | for(int i = 0; i < sb.length() - 1; i++) { 30 | temp.append(9); 31 | } 32 | return firstNum * one(temp.toString()) + one(otherNum.toString()) + firstOneCount; 33 | } 34 | 35 | public static void main(String[] args) { 36 | int times = one("102"); 37 | System.out.println(times); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/com/chenlei/array/practice/SortArrayMinNum.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array.practice; 2 | 3 | import util.NumberUtils; 4 | 5 | /** 6 | * 26. 把数组排成最小的数 7 | * @author chenlei 8 | * @since 2017 - 05 - 17 14:18 9 | */ 10 | public class SortArrayMinNum { 11 | 12 | private static void specialSort(Integer a[]) { 13 | for(int i = 0; i < a.length - 1; i++) { 14 | int minIndex = i; 15 | for(int j = i + 1; j < a.length; j++) { 16 | if(specialMin(a[j], a[minIndex]) == a[j]) { 17 | minIndex = j; 18 | } 19 | } 20 | NumberUtils.swapInteger(a, i, minIndex); 21 | } 22 | } 23 | 24 | private static int specialMin(int a, int b) { 25 | StringBuilder strA = new StringBuilder(String.valueOf(a)); 26 | StringBuilder strB = new StringBuilder(String.valueOf(b)); 27 | int compareLength = strA.length() > strB.length() ? strA.length() : strB.length(); 28 | for(int i = 0; i < compareLength; i++) { 29 | char charA = strA.charAt(i % strA.length()); 30 | char charB = strB.charAt(i % strB.length()); 31 | if(charA < charB) { 32 | return a; 33 | } 34 | if(charA > charB) { 35 | return b; 36 | } 37 | } 38 | //相等 39 | return a; 40 | } 41 | 42 | public static void main(String[] args) { 43 | Integer a[] = {3, 32, 321}; 44 | specialSort(a); 45 | NumberUtils.printArray(a); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/com/chenlei/array/practice/SortByZero.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array.practice; 2 | 3 | import util.NumberUtils; 4 | 5 | /** 6 | * 45. 只能进行0与其他数的交换操作的排序 7 | * @author chenlei 8 | * @since 2017 - 05 - 22 18:21 9 | */ 10 | public class SortByZero { 11 | 12 | //利用0来作为中间变量,指针不回溯来保证O(n)复杂度 13 | private static void sortByZero(int a[]) { 14 | if(a.length <=1) { 15 | return; 16 | } 17 | int zeroIndex = 0; 18 | for(int i = 0; i < a.length; i++) { 19 | if(a[i] == 0) { 20 | zeroIndex = i; 21 | break; 22 | } 23 | } 24 | //把0换到0的位置 25 | NumberUtils.swapInt(a, zeroIndex, 0); 26 | int currentIndex = 1; 27 | while (currentIndex < a.length) { 28 | if(a[currentIndex] == currentIndex) { 29 | currentIndex++; 30 | } else { 31 | int targetIndex = a[currentIndex]; 32 | NumberUtils.swapInt(a, 0, targetIndex); 33 | NumberUtils.swapInt(a, currentIndex, targetIndex); 34 | NumberUtils.swapInt(a, 0, currentIndex); 35 | } 36 | } 37 | } 38 | 39 | public static void main(String[] args) { 40 | int a[] = {4, 2, 6, 0, 7, 3, 1, 5}; 41 | sortByZero(a); 42 | NumberUtils.printInArray(a); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/com/chenlei/array/practice/TwoOnceAppeared.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.array.practice; 2 | 3 | import util.NumberUtils; 4 | import util.tuple.Tuple; 5 | import util.tuple.Tuple2; 6 | 7 | /** 8 | * 3. 两个只出现一次的数字 9 | * @author chenlei 10 | * @since 2017 - 03 - 08 20:31 11 | */ 12 | public class TwoOnceAppeared { 13 | 14 | private static Tuple2 twoOnce(int a[]) { 15 | int xor = 0; 16 | for (int anA : a) { 17 | xor = xor ^ anA; 18 | } 19 | int bitOfOne = NumberUtils.getBitOne(xor); 20 | int firstNum = 0, secondNum = 0; 21 | for (int anA : a) { 22 | if ((anA & (1 << (bitOfOne - 1))) != 0) { 23 | firstNum = firstNum ^ anA; 24 | } else { 25 | secondNum = secondNum ^ anA; 26 | } 27 | } 28 | return Tuple.of(firstNum, secondNum); 29 | } 30 | 31 | public static void main(String[] args) { 32 | int a[] = {1, 4, 8, 2, 3, 8, 4, 1}; 33 | Tuple2 result = twoOnce(a); 34 | System.out.println("firstNum is " + result._1().orElse(null) + ", secondNum is " + result._2().orElse(null)); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/com/chenlei/dp/practice/SubSeqCount.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.dp.practice; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | /** 9 | * 1. 子序列的个数 10 | * @author chenlei 11 | * @since 2017 - 06 - 09 11:24 12 | */ 13 | public class SubSeqCount { 14 | 15 | /** 16 | * dp[k]=2*dp[k-1]+1;如果a[k]与前k-1个字符都不相同 17 | * dp[k]=2*dp[k-1]-dp[t-1],如果a[k]与前k-1个字符有相同的,t是与之相同的最近的一个下标 18 | */ 19 | private static int getSubSeqCount(int a[]) { 20 | Map index = new HashMap<>(); 21 | index.put(a[0], 0); 22 | List dp = new ArrayList<>(); 23 | for(int i = 1; i < a.length; i++) { 24 | if(!index.containsKey(a[i])) { 25 | dp.add(2*dp.get(dp.size() - 1) + 1); 26 | } else { 27 | dp.add(2*dp.get(dp.size() - 1) - dp.get(index.get(a[i]))); 28 | } 29 | index.put(a[i], i); 30 | } 31 | return dp.get(dp.size() - 1); 32 | } 33 | 34 | public static void main(String[] args) { 35 | int a[] = {4, 13, 14, 1, 2, 3}; 36 | System.out.println(getSubSeqCount(a)); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/com/chenlei/find/BinarySearch.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.find; 2 | 3 | /** 4 | * 1. 二分查找 5 | * @author chenlei 6 | * @since 2017 - 06 - 04 15:17 7 | */ 8 | public class BinarySearch { 9 | 10 | //找到返回下标,没找到返回-1 11 | private static int binarySearch(int a[], int target) { 12 | int begin = 0, end = a.length - 1; 13 | while(begin <= end) { 14 | int middle = (begin + end) / 2; 15 | if(a[middle] == target) { 16 | return middle; 17 | } else if(a[middle] < target) { 18 | begin = middle + 1; 19 | } else { 20 | end = middle - 1; 21 | } 22 | } 23 | return -1; 24 | } 25 | 26 | public static void main(String[] args) { 27 | int a[] = {-5, 2, 3, 4, 5, 7, 8, 9}; 28 | System.out.println(binarySearch(a, 6)); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/com/chenlei/find/NumTimesOverHalf.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.find; 2 | 3 | /** 4 | * 3. 出现次数超过一半的数 5 | * @author chenlei 6 | * @since 2017 - 06 - 06 8:12 7 | */ 8 | public class NumTimesOverHalf { 9 | 10 | private static int findOverHalfNum(int a[]) { 11 | int candidate = a[0]; 12 | int times = 1; 13 | for(int i = 1; i < a.length; i++) { 14 | if(times == 0) { 15 | candidate = a[i]; 16 | times = 1; 17 | } else { 18 | if(candidate == a[i]) { 19 | times++; 20 | } else { 21 | times--; 22 | } 23 | } 24 | } 25 | return candidate; 26 | } 27 | 28 | public static void main(String[] args) { 29 | int a[] = {0, 1, 2, 1, 1}; 30 | System.out.println(findOverHalfNum(a)); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/com/chenlei/find/YoungTableau.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.find; 2 | 3 | import util.CollectionUtils; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | /** 9 | * 2. 杨氏矩阵的查找 10 | * @author chenlei 11 | * @since 2017 - 06 - 05 10:39 12 | */ 13 | public class YoungTableau { 14 | 15 | //从左下角开始查找, 时间O(n + m) 16 | private static boolean find(List> tableau, int n, int m, int target) { 17 | int rowIndex = n - 1, columnIndex = 0; 18 | while(rowIndex >= 0 && columnIndex < m) { 19 | int value = tableau.get(rowIndex).get(columnIndex); 20 | if(value < target) { 21 | rowIndex--; 22 | } else if(value > target) { 23 | columnIndex++; 24 | } else { 25 | return true; 26 | } 27 | } 28 | return false; 29 | } 30 | 31 | 32 | public static void main(String[] args) { 33 | List> tableau = new ArrayList<>(); 34 | tableau.add(CollectionUtils.asList(1, 2, 8, 9)); 35 | tableau.add(CollectionUtils.asList(2, 4, 9, 12)); 36 | tableau.add(CollectionUtils.asList(4, 7, 10, 13)); 37 | tableau.add(CollectionUtils.asList(6, 8, 11, 15)); 38 | System.out.println(find(tableau, 4, 4, 5)); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/com/chenlei/other/list/EntryOfCircleInList.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.other.list; 2 | 3 | /** 4 | * 寻找有环链表中环的起点 5 | * @author chenlei 6 | * @since 2017 - 06 - 17 11:34 7 | */ 8 | public class EntryOfCircleInList { 9 | 10 | private static int getTheEntry(Node list) { 11 | Node fastPointer = list, slowPointer = list; 12 | while (true) { 13 | fastPointer = fastPointer.pNext.pNext; 14 | slowPointer = slowPointer.pNext; 15 | if(fastPointer == slowPointer) { 16 | break; 17 | } 18 | } 19 | slowPointer = list; 20 | //之后每次只走一步 21 | while (fastPointer != slowPointer) { 22 | fastPointer = fastPointer.pNext; 23 | slowPointer = slowPointer.pNext; 24 | } 25 | return fastPointer.value; 26 | } 27 | 28 | public static void main(String[] args) { 29 | Node node4 = new Node(4, null); 30 | Node node3 = new Node(3, node4); 31 | Node node2 = new Node(2, node3); 32 | Node node1 = new Node(1, node2); 33 | node4.pNext = node2; 34 | System.out.println(getTheEntry(node1)); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/com/chenlei/other/list/LinkListWithCircle.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.other.list; 2 | 3 | /** 4 | * 判断一个单链表是否有环 5 | * @author chenlei 6 | * @since 2017 - 06 - 17 11:24 7 | */ 8 | public class LinkListWithCircle { 9 | 10 | //快慢指针,一个走一步,一个走两步 11 | private static boolean withCircle(Node list) { 12 | Node fastPointer = list, slowPointer = list; 13 | while (fastPointer.pNext != null && fastPointer.pNext.pNext != null) { 14 | fastPointer = fastPointer.pNext.pNext; 15 | slowPointer = slowPointer.pNext; 16 | if(fastPointer == slowPointer) { 17 | return true; 18 | } 19 | } 20 | return false; 21 | } 22 | 23 | public static void main(String[] args) { 24 | Node node4 = new Node(4, null); 25 | Node node3 = new Node(3, node4); 26 | Node node2 = new Node(2, node3); 27 | Node node1 = new Node(1, node2); 28 | node4.pNext = node2; 29 | System.out.println(withCircle(node1)); 30 | } 31 | 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/com/chenlei/other/list/Node.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.other.list; 2 | 3 | /** 4 | * @author chenlei 5 | * @since 2017 - 06 - 17 11:36 6 | */ 7 | class Node { 8 | Node(int value, Node pNext) { 9 | this.value = value; 10 | this.pNext = pNext; 11 | } 12 | int value; 13 | Node pNext; 14 | } 15 | -------------------------------------------------------------------------------- /src/com/chenlei/sort/BubbleSort.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.sort; 2 | 3 | import util.NumberUtils; 4 | 5 | /** 6 | * 冒泡排序 7 | * @author chenlei 8 | * @since 2016 - 11 - 16 21:04 9 | */ 10 | public class BubbleSort { 11 | 12 | private static void bubbleSort(Integer[] array) { 13 | for (int i = 0; i < array.length - 1; i++) { 14 | boolean changed = false; 15 | for (int j = array.length - 1; j > i; j--) { 16 | if (array[j] < array[j - 1]) { 17 | changed = true; 18 | NumberUtils.swapInteger(array, j - 1, j); 19 | } 20 | } 21 | if(!changed) { 22 | break; 23 | } 24 | } 25 | } 26 | 27 | public static void main(String[] args) { 28 | Integer[] array = {3, 2, 5, 4, 7}; 29 | bubbleSort(array); 30 | NumberUtils.printArray(array); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/com/chenlei/sort/HeapSort.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.sort; 2 | 3 | import util.NumberUtils; 4 | 5 | /** 6 | * @author chenlei 7 | * @since 2016 - 11 - 17 20:22 8 | */ 9 | public class HeapSort { 10 | 11 | private static void initHeap(Integer[] array) { 12 | //初始化从非叶子节点开始 13 | for(int i = (array.length - 2) / 2; i >= 0; i--) { 14 | sickDown(array, i, array.length - 1); 15 | } 16 | } 17 | 18 | private static void heapSort(Integer[] array) { 19 | for(int i = array.length - 1; i >= 0; i--) { 20 | NumberUtils.swapInteger(array, 0, i); 21 | sickDown(array, 0, i); 22 | } 23 | } 24 | 25 | /** 26 | * 第q个结点向下沉 27 | */ 28 | private static void sickDown(Integer[] array, int q, int p) { 29 | int leftChild = 2 * q + 1; 30 | while(leftChild < p) { 31 | //q有左子结点 32 | int min = q; 33 | if(array[leftChild] < array[min]) { 34 | min = leftChild; 35 | } 36 | if(leftChild + 1 < p && array[leftChild + 1] < array[min]) { 37 | min = leftChild + 1; 38 | } 39 | if(min == q) { 40 | break; 41 | } 42 | NumberUtils.swapInteger(array, q, min); 43 | q = min; 44 | leftChild = 2 * q + 1; 45 | } 46 | } 47 | 48 | 49 | public static void main(String[] args) { 50 | Integer[] array = {3, 2, 5, 4, 7}; 51 | initHeap(array); 52 | heapSort(array); 53 | NumberUtils.printArray(array); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/com/chenlei/sort/InsertSort.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.sort; 2 | 3 | import util.NumberUtils; 4 | 5 | /** 6 | * @author chenlei 7 | * @since 2016 - 11 - 16 20:05 8 | */ 9 | public class InsertSort { 10 | 11 | private static void insertSort(Integer[] array) { 12 | for(int i = 1; i < array.length; i++) { 13 | int target = array[i]; 14 | int j = i - 1; 15 | for( ; j >= 0 ; j --) { 16 | if(array[j] > target) { 17 | array[j + 1] = array[j]; 18 | } else { 19 | break; 20 | } 21 | } 22 | array[j + 1] = target; 23 | } 24 | } 25 | 26 | public static void main(String[] args) { 27 | Integer[] array = {3, 2, 5, 4, 7}; 28 | insertSort(array); 29 | NumberUtils.printArray(array); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/com/chenlei/sort/SelectSort.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.sort; 2 | 3 | import util.NumberUtils; 4 | 5 | /** 6 | * @author chenlei 7 | * @since 2016 - 11 - 16 21:33 8 | */ 9 | public class SelectSort { 10 | 11 | private static void selectSort(Integer []array) { 12 | for(int i = 0; i < array.length - 1; i++) { 13 | int minIndex = i; 14 | for(int j = i + 1; j < array.length; j++) { 15 | if(array[j] < array[minIndex]) { 16 | minIndex = j; 17 | } 18 | } 19 | NumberUtils.swapInteger(array, i, minIndex); 20 | } 21 | } 22 | 23 | public static void main(String[] args) { 24 | Integer[] array = {3, 2, 5, 4, 7}; 25 | selectSort(array); 26 | NumberUtils.printArray(array); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/com/chenlei/string/Palindrome.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.string; 2 | 3 | import util.StringUtils; 4 | 5 | /** 6 | * 1.5 回文判断 7 | * @author chenlei 8 | * @since 2016 - 09 - 06 21:30 9 | */ 10 | public class Palindrome { 11 | 12 | private static boolean isPalindrome(String str) { 13 | if(StringUtils.isBlank(str)) { 14 | return false; 15 | } 16 | int before = 0, after = str.length() - 1; 17 | while(before < after) { 18 | if(str.charAt(before) != str.charAt(after)) { 19 | return false; 20 | } 21 | before++; 22 | after--; 23 | } 24 | return true; 25 | } 26 | 27 | private static boolean isPalindromeByMiddle(String str) { 28 | int before = str.length() / 2 - 1, after; 29 | if(str.length() % 2 == 0) { 30 | after = str.length() / 2; 31 | } else { 32 | after = str.length() / 2 + 1; 33 | } 34 | while(before >= 0) { 35 | if(str.charAt(before) != str.charAt(after)) { 36 | return false; 37 | } 38 | before--; 39 | after++; 40 | } 41 | return true; 42 | } 43 | 44 | public static void main(String[] args) { 45 | System.out.println(isPalindrome("issi")); 46 | System.out.println(isPalindrome("abcba")); 47 | System.out.println(isPalindrome("abcea")); 48 | System.out.println(isPalindromeByMiddle("issi")); 49 | System.out.println(isPalindromeByMiddle("abcba")); 50 | System.out.println(isPalindromeByMiddle("abcea")); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/com/chenlei/string/StringContain.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.string; 2 | 3 | /** 1.2 字符串包含 4 | * @author chenlei 5 | * @since 2016 - 09 - 04 15:22 6 | */ 7 | public class StringContain { 8 | 9 | private static boolean stringContainByHash(String a, String b) { 10 | boolean[] array = new boolean[26]; 11 | for(char c : a.toCharArray()) { 12 | array[c - 'A'] = true; 13 | } 14 | for(char c : b.toCharArray()) { 15 | if(!array[c - 'A']) { 16 | return false; 17 | } 18 | } 19 | return true; 20 | } 21 | 22 | private static boolean stringContainByBit(String a, String b) { 23 | int aBit = 0; 24 | for(char c : a.toCharArray()) { 25 | aBit |= 1 << (c - 'A'); 26 | } 27 | for(char c : b.toCharArray()) { 28 | if((aBit & (1 << (c - 'A'))) == 0) { 29 | return false; 30 | } 31 | } 32 | return true; 33 | } 34 | 35 | public static void main(String[] args) { 36 | System.out.println(stringContainByHash("ABCD","BD")); 37 | System.out.println(stringContainByBit("ABCD","BCDE")); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/com/chenlei/string/back/AnyPerm.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.string.back; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * 1.3.1 字典序的所有排列 7 | * @author chenlei 8 | * @since 2016 - 09 - 04 20:27 9 | */ 10 | public class AnyPerm { 11 | 12 | private static void anyPerm(char a[], char temp[]) { 13 | Arrays.sort(a); 14 | perm(temp, a, 0); 15 | } 16 | 17 | private static void perm(char current[], char inOrder[], int index) { 18 | if(index > inOrder.length - 1) { 19 | System.out.println(current); 20 | return; 21 | } 22 | for (char anInOrder : inOrder) { 23 | current[index] = anInOrder; 24 | perm(current, inOrder, index + 1); 25 | } 26 | } 27 | 28 | public static void main(String[] args) { 29 | char c[] = {'a','b','c'}; 30 | char temp[] = new char[3]; 31 | anyPerm(c, temp); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/com/chenlei/string/back/BrotherWord.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.string.back; 2 | 3 | /** 1.2 变位词 4 | * @author chenlei 5 | * @since 2016 - 09 - 04 16:01 6 | */ 7 | public class BrotherWord { 8 | 9 | private static boolean isBrotherWord(String a, String b) { 10 | int arr[] = new int[26]; 11 | for(char c : a.toCharArray()) { 12 | arr[c - 'a'] = arr[c - 'a'] + 1; 13 | } 14 | for(char c : b.toCharArray()) { 15 | arr[c - 'a'] = arr[c - 'a'] - 1; 16 | } 17 | for(int value : arr) { 18 | if(value != 0) { 19 | return false; 20 | } 21 | } 22 | return true; 23 | } 24 | 25 | public static void main(String[] args) { 26 | System.out.println(isBrotherWord("bad","adbb")); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/com/chenlei/string/back/ListPalindrome.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.string.back; 2 | 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | import java.util.Objects; 6 | import java.util.Stack; 7 | 8 | /** 9 | * 1.5.1 链表回文 10 | * @author chenlei 11 | * @since 2017 - 02 - 15 20:18 12 | */ 13 | public class ListPalindrome { 14 | 15 | static boolean isListPalindrome(List list) { 16 | Stack stack = new Stack<>(); 17 | stack.addAll(list); 18 | for(Integer i : list) { 19 | Integer reverse = stack.pop(); 20 | if(!Objects.equals(i, reverse)) { 21 | return false; 22 | } 23 | } 24 | return true; 25 | } 26 | 27 | public static void main(String[] args) { 28 | List list = new LinkedList<>(); 29 | list.add(1); 30 | list.add(2); 31 | list.add(2); 32 | list.add(1); 33 | System.out.println(isListPalindrome(list)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/com/chenlei/string/back/ReverseWord.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.string.back; 2 | 3 | import util.StringUtils; 4 | 5 | /** 6 | * 1.1 单词反转 7 | * @author chenlei 8 | * @since 2016 - 09 - 04 11:42 9 | */ 10 | public class ReverseWord { 11 | private static String reverseWord(String string) { 12 | char[] chars = string.toCharArray(); 13 | StringUtils.reverseCharArray(chars, 0, chars.length - 1); 14 | int first = 0, second; 15 | do{ 16 | //firstIndex指向第一个不等于空的字符 17 | while(first < chars.length && chars[first] == ' ') first++; 18 | if(first >= chars.length) break; 19 | second = first; // second指向该word的最后一个字符 20 | while(second < chars.length - 1 && chars[second + 1] != ' ') second++; 21 | StringUtils.reverseCharArray(chars, first, second); 22 | first = second + 1; 23 | } while(true); 24 | return String.valueOf(chars); 25 | } 26 | 27 | public static void main(String[] args) { 28 | System.out.println(reverseWord(" I am a student.")); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/com/chenlei/string/back/StackPalindrome.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.string.back; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Stack; 6 | 7 | /** 8 | * 1.5.2 栈回文 9 | * @author chenlei 10 | * @since 2017 - 02 - 15 20:27 11 | */ 12 | public class StackPalindrome { 13 | 14 | private static boolean isStackPalindrome(Stack obj) { 15 | List list = new ArrayList<>(); 16 | while(!obj.empty()) { 17 | Integer i = obj.pop(); 18 | list.add(i); 19 | } 20 | for(int index = list.size() - 1; index >= 0; index--) { 21 | obj.push(list.get(index)); 22 | } 23 | return ListPalindrome.isListPalindrome(list); 24 | 25 | } 26 | 27 | public static void main(String[] args) { 28 | Stack obj = new Stack<>(); 29 | obj.push(1); 30 | obj.push(2); 31 | obj.push(3); 32 | obj.push(4); 33 | obj.push(5); 34 | System.out.println(isStackPalindrome(obj)); 35 | System.out.println(obj); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/com/chenlei/string/back/StrCombination.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.string.back; 2 | 3 | import java.util.ArrayList; 4 | 5 | /** 6 | * 1.3.2 字符的所有组合 7 | * @author chenlei 8 | * @since 2016 - 09 - 04 21:00 9 | */ 10 | public class StrCombination { 11 | 12 | private static void combination(char a[], ArrayList list, int index) { 13 | if(index == a.length) { 14 | if(list.size() > 0) { 15 | System.out.println(list); 16 | } 17 | return; 18 | } 19 | combination(a, list, index + 1); 20 | list.add(a[index]); 21 | combination(a, list, index + 1); 22 | list.remove(list.size() -1); 23 | } 24 | 25 | private static void combinationByBit(char a[]) { 26 | int times = 1; 27 | for (char ignored : a) { 28 | times *= 2; 29 | } 30 | for(int printTemplate = 1; printTemplate < times; printTemplate++) { 31 | printCombination(a, printTemplate); 32 | } 33 | } 34 | 35 | private static void printCombination(char a[], int printTemplate) { 36 | for(int i = 0; i < a.length; i++) { 37 | if((printTemplate & (1 << i)) != 0) { 38 | System.out.print(a[a.length - i - 1]); 39 | } 40 | } 41 | System.out.println(); 42 | } 43 | 44 | public static void main(String[] args) { 45 | char c[] = {'a', 'b', 'c'}; 46 | ArrayList list = new ArrayList<>(); 47 | combination(c, list, 0); 48 | combinationByBit(c); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/com/chenlei/string/practice/MaxContinueCharLength.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.string.practice; 2 | 3 | /** 4 | * 12 最长连续字符递归写法 5 | * @author chenlei 6 | * @since 2016 - 10 - 23 10:25 7 | */ 8 | public class MaxContinueCharLength { 9 | 10 | private static int maxContinueCharLength(String str, int index) { 11 | if(index < 0 || index >= str.length()) { 12 | return 0; 13 | } 14 | int after = index+1; 15 | while(after < str.length()) { 16 | if(str.charAt(after - 1) == str.charAt(after)) { 17 | after++; 18 | } else { 19 | break; 20 | } 21 | } 22 | if(after >= str.length()) { 23 | return after - index; 24 | } else { 25 | int otherMaxLength = maxContinueCharLength(str, after); 26 | return (after - index) > otherMaxLength ? (after - index) : otherMaxLength; 27 | } 28 | } 29 | 30 | public static void main(String[] args) { 31 | System.out.println(maxContinueCharLength("aaaabbcc",0)); 32 | System.out.println(maxContinueCharLength("aabb",0)); 33 | System.out.println(maxContinueCharLength("ab",0)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/com/chenlei/string/practice/Per01.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.string.practice; 2 | 3 | /** 4 | * 15 均分01 5 | * @author chenlei 6 | * @since 2016 - 11 - 09 22:26 7 | */ 8 | public class Per01 { 9 | 10 | private static void per01(String str) { 11 | int total0 = 0; 12 | int total0Now = 0; 13 | for(int i = 0; i < str.length(); i++) { 14 | if(str.charAt(i) == '0') { 15 | total0++; 16 | if(i < str.length() / 2) { 17 | total0Now++; 18 | } 19 | } 20 | } 21 | int total0Half = total0 / 2; 22 | 23 | int beforeIndex = 0; 24 | while(total0Now != total0Half) { 25 | if(str.charAt(beforeIndex) == '0') { 26 | total0Now--; 27 | } 28 | if(str.charAt(beforeIndex+ (str.length() / 2)) == '0') { 29 | total0Now++; 30 | } 31 | beforeIndex++; 32 | } 33 | System.out.println("beforeIndex is " + beforeIndex); 34 | } 35 | 36 | public static void main(String[] args) { 37 | per01("010111"); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/com/chenlei/tree/BSTNode.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.tree; 2 | 3 | /** 4 | * tool 5 | * @author chenlei 6 | * @since 2017 - 06 - 01 10:03 7 | */ 8 | class BSTNode { 9 | 10 | private BSTNode(int value, int stone) { 11 | this.value = value; 12 | this.stone = stone; 13 | } 14 | 15 | private void initLink(BSTNode leftChild, BSTNode rightChild) { 16 | this.leftChild = leftChild; 17 | this.rightChild = rightChild; 18 | } 19 | 20 | static BSTNode initTree() { 21 | BSTNode node1 = new BSTNode(10, 0); 22 | BSTNode node2 = new BSTNode(6, 1); 23 | BSTNode node3 = new BSTNode(14, 1); 24 | BSTNode node4 = new BSTNode(4, 4); 25 | BSTNode node5 = new BSTNode(8, 0); 26 | BSTNode node6 = new BSTNode(12, 1); 27 | BSTNode node7 = new BSTNode(16, 0); 28 | node1.initLink(node2, node3); 29 | node2.initLink(node4, node5); 30 | node3.initLink(node6, node7); 31 | node4.initLink(null, null); 32 | node5.initLink(null, null); 33 | node6.initLink(null, null); 34 | node7.initLink(null, null); 35 | return node1; 36 | } 37 | 38 | int value; 39 | int stone; 40 | BSTNode leftChild; 41 | BSTNode rightChild; 42 | BSTNode pNext; 43 | } 44 | -------------------------------------------------------------------------------- /src/com/chenlei/tree/DepthOfTree.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.tree; 2 | 3 | import util.NumberUtils; 4 | 5 | /** 6 | * 5. 求树的深度 7 | * @author chenlei 8 | * @since 2017 - 06 - 01 10:01 9 | */ 10 | public class DepthOfTree { 11 | 12 | private static int getDepthOfTree(BSTNode tree) { 13 | if(tree == null) { 14 | return 0; 15 | } 16 | return NumberUtils.max(getDepthOfTree(tree.leftChild), getDepthOfTree(tree.rightChild)) + 1; 17 | } 18 | 19 | public static void main(String[] args) { 20 | BSTNode bst = BSTNode.initTree(); 21 | System.out.println(getDepthOfTree(bst)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/com/chenlei/tree/MaxDistanceInBinaryTree.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.tree; 2 | 3 | import util.NumberUtils; 4 | import util.tuple.Tuple; 5 | import util.tuple.Tuple2; 6 | 7 | /** 8 | * 4. 求二叉树中结点的最大距离 9 | * @author chenlei 10 | * @since 2017 - 06 - 01 15:09 11 | */ 12 | public class MaxDistanceInBinaryTree { 13 | 14 | // 避免重复计算 15 | private static Tuple2 getMaxDistanceOfBinaryTree(BSTNode tree) { 16 | if(tree == null) { 17 | return Tuple.of(0, 0); 18 | } 19 | Tuple2 leftInfo = getMaxDistanceOfBinaryTree(tree.leftChild); 20 | Tuple2 rightInfo = getMaxDistanceOfBinaryTree(tree.rightChild); 21 | int maxDistance = NumberUtils.maxOfThree(leftInfo._1().orElse(0), rightInfo._1().orElse(0), leftInfo._2().orElse(0) + rightInfo._2().orElse(0)); 22 | return Tuple.of(maxDistance, NumberUtils.max(leftInfo._2().orElse(0), rightInfo._2().orElse(0)) + 1); 23 | } 24 | 25 | 26 | public static void main(String[] args) { 27 | BSTNode bst = BSTNode.initTree(); 28 | System.out.println(getMaxDistanceOfBinaryTree(bst)); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/com/chenlei/tree/MoveNode.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.tree; 2 | 3 | import util.NumberUtils; 4 | 5 | /** 6 | * 6. 树结点的移动 7 | * @author chenlei 8 | * @since 2017 - 06 - 02 15:36 9 | */ 10 | public class MoveNode { 11 | 12 | private static int steps = 0; 13 | 14 | /** 15 | * 将所有子树的多余石头或者亏欠都移动到tree的根节点。return值为根节点多余或亏欠的值 16 | */ 17 | private static int moveNode(BSTNode tree) { 18 | if(tree == null) { 19 | return 0; 20 | } 21 | int leftNodes = moveNode(tree.leftChild); 22 | int rightNodes = moveNode(tree.rightChild); 23 | steps = steps + NumberUtils.abs(leftNodes) + NumberUtils.abs(rightNodes); 24 | return tree.stone + leftNodes + rightNodes - 1; 25 | } 26 | 27 | public static void main(String[] args) { 28 | BSTNode tree = BSTNode.initTree(); 29 | moveNode(tree); 30 | System.out.println(steps); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/com/chenlei/tree/PNext.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.tree; 2 | 3 | import java.util.ArrayDeque; 4 | import java.util.Queue; 5 | 6 | /** 7 | * 7. 给树节点加上pNext指针 8 | * @author chenlei 9 | * @since 2017 - 06 - 02 13:46 10 | */ 11 | public class PNext { 12 | 13 | //层序遍历添加兄弟指针 14 | private static void addPNext(BSTNode tree, Queue queue) { 15 | queue.add(tree); 16 | int nextNullNum = 1; 17 | int currentNum = 0; 18 | BSTNode node = null; 19 | while(!queue.isEmpty()) { 20 | currentNum++; 21 | node = queue.poll(); 22 | if(node.leftChild != null) { 23 | queue.add(node.leftChild); 24 | } 25 | if(node.rightChild != null) { 26 | queue.add(node.rightChild); 27 | } 28 | if(currentNum == nextNullNum) { 29 | node.pNext = null; 30 | nextNullNum = nextNullNum * 2; 31 | currentNum = 0; 32 | } else { 33 | node.pNext = queue.element(); 34 | } 35 | } 36 | if(node != null) { 37 | node.pNext = null; 38 | } 39 | } 40 | 41 | public static void main(String[] args) { 42 | BSTNode tree = BSTNode.initTree(); 43 | addPNext(tree, new ArrayDeque<>()); 44 | System.exit(0); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/com/chenlei/tree/RevertBSTtoDouLink.java: -------------------------------------------------------------------------------- 1 | package com.chenlei.tree; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * 2. 把二叉查找树转变成有序的双向链表 8 | * @author chenlei 9 | * @since 2017 - 05 - 31 11:38 10 | */ 11 | public class RevertBSTtoDouLink { 12 | 13 | //中序遍历添加到list 14 | private static void inOrder(BSTNode tree, List list) { 15 | if(tree != null) { 16 | inOrder(tree.leftChild, list); 17 | list.add(tree); 18 | inOrder(tree.rightChild, list); 19 | } 20 | } 21 | 22 | public static void main(String[] args) { 23 | BSTNode bst = BSTNode.initTree(); 24 | List list = new ArrayList<>(); 25 | inOrder(bst, list); 26 | for(int i = 0; i < list.size(); i++) { 27 | list.get(i).leftChild = (i == 0 ? null : list.get(i -1)); 28 | list.get(i).rightChild = (i == list.size() - 1 ? null : list.get(i+1)); 29 | } 30 | for(BSTNode node : list) { 31 | System.out.println(node.value); 32 | } 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/util/CollectionUtils.java: -------------------------------------------------------------------------------- 1 | package util; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.List; 6 | 7 | /** 8 | * @author chenlei 9 | * @since 2017 - 06 - 05 10:50 10 | */ 11 | public class CollectionUtils { 12 | 13 | @SafeVarargs 14 | public static List asList(T ...args) { 15 | List list = new ArrayList(); 16 | Collections.addAll(list, args); 17 | return list; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/util/LocalCache/CacheObject.java: -------------------------------------------------------------------------------- 1 | package util.LocalCache; 2 | 3 | /** 4 | * @author chenlei 5 | * @since 2017 - 07 - 01 13:10 6 | */ 7 | public class CacheObject { 8 | 9 | private Object object; 10 | private long timestamp; 11 | 12 | public CacheObject(Object object, long timestamp) { 13 | this.object = object; 14 | this.timestamp = timestamp; 15 | } 16 | 17 | public long getTimestamp() { 18 | return timestamp; 19 | } 20 | 21 | public Object getObject() { 22 | return object; 23 | } 24 | 25 | public void setObject(Object object) { 26 | this.object = object; 27 | } 28 | 29 | public void setTimestamp(long timestamp) { 30 | this.timestamp = timestamp; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/util/StringUtils.java: -------------------------------------------------------------------------------- 1 | package util; 2 | 3 | /** 4 | * @author chenlei 5 | * @since 2016 - 09 - 04 10:55 6 | */ 7 | public class StringUtils { 8 | 9 | public static boolean isBlank(String string) { 10 | if(string == null) { 11 | return true; 12 | } 13 | for(int i = 0; i < string.length(); i++) { 14 | if(string.charAt(i) != ' ') { 15 | return false; 16 | } 17 | } 18 | return true; 19 | } 20 | 21 | public static boolean isNotBlank(String string) { 22 | return !isBlank(string); 23 | } 24 | 25 | public static void swapChar(char []chars, int first, int second) { 26 | char temp = chars[first]; 27 | chars[first] = chars[second]; 28 | chars[second] = temp; 29 | } 30 | 31 | 32 | public static void reverseCharArray(char []chars, int first, int second) { 33 | while (first < second) { 34 | swapChar(chars, first++, second--); 35 | } 36 | } 37 | 38 | public static void printStrToHex(String s) { 39 | for (char c : s.toCharArray()) { 40 | System.out.print(Integer.toHexString(c)); 41 | } 42 | System.out.println(); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/util/tuple/Tuple2.java: -------------------------------------------------------------------------------- 1 | package util.tuple; 2 | 3 | import java.util.Optional; 4 | 5 | @SuppressWarnings("all") 6 | public class Tuple2 extends Tuple { 7 | private A a; 8 | private B b; 9 | 10 | Tuple2(A a, B b) { 11 | this.a = a; 12 | this.b = b; 13 | } 14 | 15 | @SuppressWarnings("unchecked") 16 | public Optional _1() { 17 | if (a == null) { 18 | return Optional.empty(); 19 | } 20 | return Optional.of(a); 21 | } 22 | 23 | @SuppressWarnings("unchecked") 24 | public Optional _2() { 25 | if (b == null) { 26 | return Optional.empty(); 27 | } 28 | return Optional.of(b); 29 | } 30 | 31 | @SuppressWarnings("unchecked") 32 | public Optional _3() { 33 | return Optional.empty(); 34 | } 35 | 36 | @SuppressWarnings("unchecked") 37 | public Optional _4() { 38 | return Optional.empty(); 39 | } 40 | 41 | @SuppressWarnings("unchecked") 42 | public Optional _5() { 43 | return Optional.empty(); 44 | } 45 | 46 | 47 | public String toString() { 48 | return "Tuple2{" + 49 | "a=" + a + 50 | ", b=" + b + 51 | '}'; 52 | } 53 | } -------------------------------------------------------------------------------- /src/util/tuple/Tuple3.java: -------------------------------------------------------------------------------- 1 | package util.tuple; 2 | 3 | import java.util.Optional; 4 | 5 | @SuppressWarnings("all") 6 | public class Tuple3 extends Tuple { 7 | private A a; 8 | private B b; 9 | private C c; 10 | 11 | Tuple3(A e, B t, C k) { 12 | this.a = e; 13 | this.b = t; 14 | this.c = k; 15 | } 16 | 17 | public Optional _1() { 18 | if (a == null) { 19 | return Optional.empty(); 20 | } 21 | return Optional.of(a); 22 | } 23 | 24 | public Optional _2() { 25 | if (b == null) { 26 | return Optional.empty(); 27 | } 28 | return Optional.of(b); 29 | } 30 | 31 | public Optional _3() { 32 | if (c == null) { 33 | return Optional.empty(); 34 | } 35 | return Optional.of(c); 36 | } 37 | 38 | @Override 39 | public Optional _4() { 40 | return Optional.empty(); 41 | } 42 | 43 | @Override 44 | public Optional _5() { 45 | return Optional.empty(); 46 | } 47 | 48 | @Override 49 | public String toString() { 50 | return "Tuple3{" + 51 | "a=" + a + 52 | ", b=" + b + 53 | ", c=" + c + 54 | '}'; 55 | } 56 | } -------------------------------------------------------------------------------- /src/util/tuple/Tuple4.java: -------------------------------------------------------------------------------- 1 | package util.tuple; 2 | 3 | import java.util.Optional; 4 | 5 | @SuppressWarnings("all") 6 | public class Tuple4 extends Tuple { 7 | private A a; 8 | private B b; 9 | private C c; 10 | private D d; 11 | 12 | Tuple4(A a, B b, C c, D d) { 13 | this.a = a; 14 | this.b = b; 15 | this.c = c; 16 | this.d = d; 17 | } 18 | 19 | public Optional _1() { 20 | if (a == null) { 21 | return Optional.empty(); 22 | } 23 | return Optional.of(a); 24 | } 25 | 26 | public Optional _2() { 27 | if (b == null) { 28 | return Optional.empty(); 29 | } 30 | return Optional.of(b); 31 | } 32 | 33 | public Optional _3() { 34 | if (c == null) { 35 | return Optional.empty(); 36 | } 37 | return Optional.of(c); 38 | } 39 | 40 | public Optional _4() { 41 | if (d == null) { 42 | return Optional.empty(); 43 | } 44 | return Optional.of(d); 45 | } 46 | 47 | @Override 48 | public Optional _5() { 49 | return Optional.empty(); 50 | } 51 | 52 | @Override 53 | public String toString() { 54 | return "Tuple4{" + 55 | "a=" + a + 56 | ", b=" + b + 57 | ", c=" + c + 58 | ", d=" + d + 59 | '}'; 60 | } 61 | } -------------------------------------------------------------------------------- /src/util/tuple/Tuple5.java: -------------------------------------------------------------------------------- 1 | package util.tuple; 2 | 3 | import java.util.Optional; 4 | 5 | @SuppressWarnings("all") 6 | public class Tuple5 extends Tuple { 7 | private A a; 8 | private B b; 9 | private C c; 10 | private D d; 11 | private E e; 12 | 13 | Tuple5(A a, B b, C c, D d, E e) { 14 | this.a = a; 15 | this.b = b; 16 | this.c = c; 17 | this.d = d; 18 | this.e = e; 19 | } 20 | 21 | public Optional _1() { 22 | if (a == null) { 23 | return Optional.empty(); 24 | } 25 | return Optional.of(a); 26 | } 27 | 28 | public Optional _2() { 29 | if (b == null) { 30 | return Optional.empty(); 31 | } 32 | return Optional.of(b); 33 | } 34 | 35 | public Optional _3() { 36 | if (c == null) { 37 | return Optional.empty(); 38 | } 39 | return Optional.of(c); 40 | } 41 | 42 | public Optional _4() { 43 | if (d == null) { 44 | return Optional.empty(); 45 | } 46 | return Optional.of(d); 47 | } 48 | 49 | public Optional _5() { 50 | if (e == null) { 51 | return Optional.empty(); 52 | } 53 | return Optional.of(e); 54 | } 55 | 56 | @Override 57 | public String toString() { 58 | return "Tuple5{" + 59 | "a=" + a + 60 | ", b=" + b + 61 | ", c=" + c + 62 | ", d=" + d + 63 | ", e=" + e + 64 | '}'; 65 | } 66 | } --------------------------------------------------------------------------------