├── .idea
└── libraries
│ ├── Maven__com_googlecode_concurrent_trees_concurrent_trees_1_0_0.xml
│ ├── Maven__commons_lang_commons_lang_2_3.xml
│ ├── Maven__junit_junit_4_11.xml
│ └── Maven__org_hamcrest_hamcrest_core_1_3.xml
├── README.md
├── pom.xml
└── src
├── main
├── java
│ └── com
│ │ └── pli
│ │ └── project
│ │ ├── PhoneNumberGenerator.java
│ │ ├── Splitter.java
│ │ ├── algorithm
│ │ ├── TestQuickSelect.java
│ │ ├── ai
│ │ │ └── WaterJug.java
│ │ ├── amz
│ │ │ ├── AddBinary.java
│ │ │ ├── BestBuySellStock.java
│ │ │ ├── BinaryTreeLevelOrder.java
│ │ │ ├── BstTopView.java
│ │ │ ├── ClimbingLadder.java
│ │ │ ├── CloneGraph.java
│ │ │ ├── CombinationSum.java
│ │ │ ├── CombinationSumII.java
│ │ │ ├── ConvertToTitle.java
│ │ │ ├── CopyListWithRandomPointer.java
│ │ │ ├── CountDigitOne.java
│ │ │ ├── CountNumberWithUniqueDigit.java
│ │ │ ├── CountPrimes.java
│ │ │ ├── Excel1.java
│ │ │ ├── FindDuplicate.java
│ │ │ ├── FindKthLargest.java
│ │ │ ├── FindKthLargest2.java
│ │ │ ├── FlipGameII.java
│ │ │ ├── GrayCode.java
│ │ │ ├── HasCycle.java
│ │ │ ├── HouseRobber.java
│ │ │ ├── HouseRobberII.java
│ │ │ ├── HouseRobberIII.java
│ │ │ ├── IntToRoman.java
│ │ │ ├── IntegerBinaryPalindrome.java
│ │ │ ├── IntersectionOfTwoLL.java
│ │ │ ├── LRUCache.java
│ │ │ ├── Lca.java
│ │ │ ├── LetterCombinationOfPhoneNumber.java
│ │ │ ├── LinkedListCycle.java
│ │ │ ├── LinkedListCycleII.java
│ │ │ ├── LongestPalindromeSubString.java
│ │ │ ├── LongestSubsqeuence.java
│ │ │ ├── LongestSubstringAtMostKDiff.java
│ │ │ ├── LongestSubstringWithoutRepeatingCharacters.java
│ │ │ ├── LowestCommonAncestorofBst.java
│ │ │ ├── MergeKSortedList.java
│ │ │ ├── MergeKSortedList2.java
│ │ │ ├── MinStack.java
│ │ │ ├── MinStack2.java
│ │ │ ├── MinStack3.java
│ │ │ ├── MoveZeros.java
│ │ │ ├── MyAtoi.java
│ │ │ ├── Nim.java
│ │ │ ├── NumberOfIslands.java
│ │ │ ├── NutsAndBoltsMatch.java
│ │ │ ├── PalindromeLinkedList.java
│ │ │ ├── PalindromeNumber.java
│ │ │ ├── PatchingArray.java
│ │ │ ├── Permutation.java
│ │ │ ├── ProductArrayExceptSelf.java
│ │ │ ├── QuickSort.java
│ │ │ ├── ReconstructItenerary.java
│ │ │ ├── RemoveDupFromSlII.java
│ │ │ ├── RemoveDupLettters.java
│ │ │ ├── RemoveDuplicate.java
│ │ │ ├── RemoveDuplicateFromSlist.java
│ │ │ ├── ReverseInteger.java
│ │ │ ├── ReverseLinkListII.java
│ │ │ ├── ReverseLinkedList.java
│ │ │ ├── ReverseWordInString.java
│ │ │ ├── RomanToInt.java
│ │ │ ├── RotateImage.java
│ │ │ ├── SearchTwoDMatrix.java
│ │ │ ├── SelfCrossing.java
│ │ │ ├── SerializeandDeserializeBinaryTree.java
│ │ │ ├── SlidingWindowMaximumSlidingWindowMaximum.java
│ │ │ ├── SortColors.java
│ │ │ ├── Sqrt.java
│ │ │ ├── SymmetryTree.java
│ │ │ ├── ThreeSum.java
│ │ │ ├── TrappingRainWater.java
│ │ │ ├── Twitter.java
│ │ │ ├── Twitter2.java
│ │ │ ├── ValidAnagram.java
│ │ │ ├── ValidParentheses.java
│ │ │ ├── ValidateBst.java
│ │ │ ├── VerifyPreorderSerialization.java
│ │ │ ├── WordBreak.java
│ │ │ ├── WordSearchII.java
│ │ │ └── l21MergeTwoSortedList.java
│ │ ├── array
│ │ │ ├── AdditiveNumber.java
│ │ │ ├── BasicCalculatorI.java
│ │ │ ├── BasicCalculatorII.java
│ │ │ ├── BasicCalculator_OPG.java
│ │ │ ├── BigNumberAdd.java
│ │ │ ├── BinarySearch.java
│ │ │ ├── BullAndCow.java
│ │ │ ├── BuyStockII.java
│ │ │ ├── ContainerWithMostWater.java
│ │ │ ├── CreateMaximumNumber.java
│ │ │ ├── CreateMaximumNumber2.java
│ │ │ ├── DuplicateInKLength.java
│ │ │ ├── Find01Pos.java
│ │ │ ├── FindDuplicateNumber.java
│ │ │ ├── FindSquare1.java
│ │ │ ├── FirstBadVersion.java
│ │ │ ├── HIndex.java
│ │ │ ├── IncreasingTriplet.java
│ │ │ ├── IntegerToEnglishWord.java
│ │ │ ├── Isomorphic.java
│ │ │ ├── KMP.java
│ │ │ ├── KthLargestElement.java
│ │ │ ├── LengthOfLIS.java
│ │ │ ├── LongestContinuousOne.java
│ │ │ ├── LongestContinuousOne2.java
│ │ │ ├── LongestIncreasingPath.java
│ │ │ ├── LongestIncreasingSubsequence.java
│ │ │ ├── LongestPalindromeStartingLeft.java
│ │ │ ├── MajorityElement.java
│ │ │ ├── MajorityElementII.java
│ │ │ ├── MatrixRotate.java
│ │ │ ├── MaxGap.java
│ │ │ ├── MaxSubarray.java
│ │ │ ├── MaxSubarrayLessThanK.java
│ │ │ ├── MaxSubarrayRectangle.java
│ │ │ ├── MaxSubarrayRectangleLessThanK.java
│ │ │ ├── MaxSubarrayWithSumK.java
│ │ │ ├── MaximalSquare.java
│ │ │ ├── MergeInterval.java
│ │ │ ├── MergeKSortedArray.java
│ │ │ ├── MinConsecutiveSubStr.java
│ │ │ ├── MinDistanceIn2List.java
│ │ │ ├── MinStack.java
│ │ │ ├── MoveZeroes.java
│ │ │ ├── NumArray.java
│ │ │ ├── NumberOfAirplane.java
│ │ │ ├── NumberOfTriangle.java
│ │ │ ├── PalindromePair.java
│ │ │ ├── PalindromePair2.java
│ │ │ ├── PartitionRandomPivot.java
│ │ │ ├── Permutation.java
│ │ │ ├── Permutation2.java
│ │ │ ├── Permutation3.java
│ │ │ ├── Permutation4.java
│ │ │ ├── RangeScan.java
│ │ │ ├── RangeSumQuery2D.java
│ │ │ ├── RectangleArea.java
│ │ │ ├── RestoreSortedArray.java
│ │ │ ├── ShortestSubstringCovering.java
│ │ │ ├── SingleNumberIII.java
│ │ │ ├── SortMinimum.java
│ │ │ ├── SparseMatrix.java
│ │ │ ├── Sum3.java
│ │ │ ├── Sum3_2nd.java
│ │ │ ├── SummaryRange.java
│ │ │ ├── SuperSet.java
│ │ │ ├── ThreeSumSmaller.java
│ │ │ ├── TwoWayPartition.java
│ │ │ ├── ValidPerfectSquare.java
│ │ │ ├── WaterJug.java
│ │ │ ├── WordDistanceI.java
│ │ │ ├── WordDistanceII.java
│ │ │ ├── WordDistanceIII.java
│ │ │ ├── ZigzagIterator.java
│ │ │ ├── ZigzagIterator2.java
│ │ │ └── suffixarray
│ │ │ │ ├── Suffix.java
│ │ │ │ └── SuffixArray.java
│ │ ├── divideandconquer
│ │ │ ├── CountSmallerNumberAfterSelf.java
│ │ │ ├── PointList.java
│ │ │ └── SkyLine.java
│ │ ├── dp
│ │ │ ├── AllPalindromePartition.java
│ │ │ ├── BollanBurst.java
│ │ │ ├── BurstBalloon.java
│ │ │ ├── BuyStockIII.java
│ │ │ ├── BuyStockIV.java
│ │ │ ├── BuyStockV.java
│ │ │ ├── DistinctSubsequence.java
│ │ │ ├── FindPalindromeInString.java
│ │ │ ├── LargestDivisibleSubset.java
│ │ │ ├── LeastPerfectSquare.java
│ │ │ ├── LongestSubsequenceInString.java
│ │ │ ├── MinimumCoins.java
│ │ │ ├── NumOfPath.java
│ │ │ ├── PalindromePartition.java
│ │ │ ├── PowerInNonRecursive.java
│ │ │ ├── SumOfSet.java
│ │ │ └── WordBreak.java
│ │ ├── encode
│ │ │ └── Base62.java
│ │ ├── exercise2014
│ │ │ ├── AddLinkedList.java
│ │ │ ├── AlternateNumber.java
│ │ │ ├── BestTimeToBuySellStockAtMostKTimes.java
│ │ │ ├── BuildSumTree.java
│ │ │ ├── CNode.java
│ │ │ ├── ConstructBSTPreOrder.java
│ │ │ ├── ConstructTreeByPreOrder.java
│ │ │ ├── ConstructTreeByPreOrder2.java
│ │ │ ├── CountBoundedSlices.java
│ │ │ ├── CountBoundedSlices2.java
│ │ │ ├── DiagonalPrintMatrix.java
│ │ │ ├── DivisionWithCycleRemainder.java
│ │ │ ├── DynamicPlan.java
│ │ │ ├── FindDiameterTrail.java
│ │ │ ├── FindKthInSortedArray.java
│ │ │ ├── FindLargestBST.java
│ │ │ ├── FindMedianOfMedian.java
│ │ │ ├── FindNearestLeaf.java
│ │ │ ├── FindNextLargest.java
│ │ │ ├── FindWeightedMedianInMatrix.java
│ │ │ ├── FindZero.java
│ │ │ ├── GetMaxGold.java
│ │ │ ├── IfSubTree.java
│ │ │ ├── IntegerSet.java
│ │ │ ├── Jaccard.java
│ │ │ ├── KnapSack01.java
│ │ │ ├── LCA.java
│ │ │ ├── LengthOfLongestSubstringWithoutRepeating.java
│ │ │ ├── LowestCostToSort.java
│ │ │ ├── MarriageProblem.java
│ │ │ ├── MaxDifferenceTwoElement.java
│ │ │ ├── MedianIn2SortedArray.java
│ │ │ ├── MinSublist.java
│ │ │ ├── PageVisit.java
│ │ │ ├── PartitionArrayByRandom.java
│ │ │ ├── PatriciaTree.java
│ │ │ ├── PostOrderNonTraverse.java
│ │ │ ├── PostOrderNonTraverse2.java
│ │ │ ├── PrimeNumerAfter1000000000.java
│ │ │ ├── PrintLineInArray.java
│ │ │ ├── QuickSortMedian.java
│ │ │ ├── ReplaceWithNextGreatOne.java
│ │ │ ├── SearchSortedRotatedArray.java
│ │ │ ├── SegregateZeroAndOne.java
│ │ │ ├── ServerCapacityBalancer.java
│ │ │ ├── SortAccordingToAnArray.java
│ │ │ ├── SortInWave.java
│ │ │ ├── StringComparisonOrder.java
│ │ │ ├── TopK.java
│ │ │ ├── TopogicalSorintDFS.java
│ │ │ ├── VerticallyPrintBiTree.java
│ │ │ ├── WiselyPrintArray.java
│ │ │ ├── test.java
│ │ │ └── weeklychallenge1
│ │ │ │ ├── DescendPrint.java
│ │ │ │ ├── DescendPrint2.java
│ │ │ │ ├── Junmin.java
│ │ │ │ └── MostRepeatedChar.java
│ │ ├── exercise2018
│ │ │ ├── MatrixTransponse.java
│ │ │ ├── QueryManager.java
│ │ │ └── querymanager
│ │ │ │ ├── QueryManger.java
│ │ │ │ ├── QueryMangerImpl.java
│ │ │ │ └── exception
│ │ │ │ ├── CyclicRelationFoundException.java
│ │ │ │ └── EmployeeNotFoundException.java
│ │ ├── gcd
│ │ │ ├── BulkSwitch.java
│ │ │ ├── FarmerAndPlot.java
│ │ │ └── Gcd.java
│ │ ├── graph
│ │ │ ├── CycleDetect.java
│ │ │ ├── Dijkstra.java
│ │ │ ├── MinimumTreeHeights.java
│ │ │ ├── MinimumTreeHeights2.java
│ │ │ ├── ReconstructItinerary.java
│ │ │ ├── TallestBox.java
│ │ │ ├── ValidGraph.java
│ │ │ └── WordLadder.java
│ │ ├── greedy
│ │ │ └── Search2DMatrix.java
│ │ ├── hash
│ │ │ ├── LinkedHashSet.java
│ │ │ └── rollinghash
│ │ │ │ ├── ExtendedEuclid.java
│ │ │ │ └── RollingHashQueue.java
│ │ ├── leetcode
│ │ │ ├── Atoi.java
│ │ │ ├── BinaryTreeInOrder.java
│ │ │ ├── BinaryTreePostOrder.java
│ │ │ ├── BinaryTreePreOrder.java
│ │ │ ├── BinaryTreeRightSideView.java
│ │ │ ├── BstIterator.java
│ │ │ ├── CoinChange.java
│ │ │ ├── CombinationSumIII.java
│ │ │ ├── CompareVersion.java
│ │ │ ├── ContainDuplicate.java
│ │ │ ├── ContainDuplicateII.java
│ │ │ ├── ContainDuplicateIII.java
│ │ │ ├── CopyListwithRandomPointer.java
│ │ │ ├── CountNumberWithUniqueDigit.java
│ │ │ ├── CourseScheduleII.java
│ │ │ ├── DNASequence.java
│ │ │ ├── Dungeon.java
│ │ │ ├── ExcelSheet.java
│ │ │ ├── ExcelSheetStrToNum.java
│ │ │ ├── FindKParisWithSmallestSums.java
│ │ │ ├── FindPeakElement.java
│ │ │ ├── FractionToRecurringDecimal.java
│ │ │ ├── HappyNumber.java
│ │ │ ├── InsertionSortList.java
│ │ │ ├── InterBreak.java
│ │ │ ├── IntersectionOfTwoArraysII.java
│ │ │ ├── IntersectionofTwoArrays.java
│ │ │ ├── Isomophic.java
│ │ │ ├── LargestNumber.java
│ │ │ ├── LinkedListCycleII.java
│ │ │ ├── ListNode.java
│ │ │ ├── LongestStrAtMostKDistinctChar.java
│ │ │ ├── MaxGap.java
│ │ │ ├── MaxPointsOnLine.java
│ │ │ ├── MaxProductSubarray.java
│ │ │ ├── MaximumSizeSubarraySumEqualsK.java
│ │ │ ├── MedianFinder.java
│ │ │ ├── MinSizeSumArray.java
│ │ │ ├── MissingNumber.java
│ │ │ ├── MissingRanges.java
│ │ │ ├── NestedInteger.java
│ │ │ ├── NestedIterator.java
│ │ │ ├── NestedIteratorII.java
│ │ │ ├── NextPermutation.java
│ │ │ ├── NumOfIslands.java
│ │ │ ├── NumberOf1Bit.java
│ │ │ ├── NumberOfTrailingZeros.java
│ │ │ ├── OddEvenList2.java
│ │ │ ├── PalindromeNumber.java
│ │ │ ├── PalindromePartition.java
│ │ │ ├── PowXN.java
│ │ │ ├── PowerOf4.java
│ │ │ ├── RandomizedCollection.java
│ │ │ ├── RandomizedSet.java
│ │ │ ├── RangeBitWiseAnd.java
│ │ │ ├── RemoveLInkedListElement.java
│ │ │ ├── ReorderList.java
│ │ │ ├── ReverseLinkList.java
│ │ │ ├── ReversePolishNotation.java
│ │ │ ├── RussianDollEnvelopes.java
│ │ │ ├── ScheduleCourse.java
│ │ │ ├── ShortestPalindrome.java
│ │ │ ├── SingleNumberII.java
│ │ │ ├── SkyLine.java
│ │ │ ├── SortList.java
│ │ │ ├── SumOfTwoIntegers.java
│ │ │ ├── SummaryRanges.java
│ │ │ ├── SuperPow.java
│ │ │ ├── TreeNode.java
│ │ │ ├── Twitter.java
│ │ │ ├── TwoSumII.java
│ │ │ ├── VerifyPreorderSerialization.java
│ │ │ ├── WeightedSum.java
│ │ │ ├── WordBreak.java
│ │ │ ├── WordBreakII.java
│ │ │ ├── WordDictionary.java
│ │ │ ├── WordPattern.java
│ │ │ ├── WordSearchII.java
│ │ │ ├── WordSearchIINaive.java
│ │ │ ├── ZigzagConversion.java
│ │ │ ├── junmin.java
│ │ │ ├── l100SameTree.java
│ │ │ ├── l103BstZigzag.java
│ │ │ ├── l104MaxDeptBst.java
│ │ │ ├── l105ConstructBstInorderPreorder.java
│ │ │ ├── l106ConstructBstInorderPostorder.java
│ │ │ ├── l107LevelOrderTraverse.java
│ │ │ ├── l108ConvertSortedArraytoBst.java
│ │ │ ├── l109ConvertSortedListAvl.java
│ │ │ ├── l10RegularExpression.java
│ │ │ ├── l110BalancedBst.java
│ │ │ ├── l111MinimumDepthBst.java
│ │ │ ├── l112SumPath.java
│ │ │ ├── l113SumPathII.java
│ │ │ ├── l114FlattenBinaryTree.java
│ │ │ ├── l117NextRightPointer.java
│ │ │ ├── l118PascalTriangle.java
│ │ │ ├── l120Triangle.java
│ │ │ ├── l125ValidPalindrome.java
│ │ │ ├── l127WordLadder.java
│ │ │ ├── l128LongestConsecutiveSequence.java
│ │ │ ├── l129SumRootToLeafNumbers.java
│ │ │ ├── l130SurroundedRegion.java
│ │ │ ├── l132PalindromePartitioningII.java
│ │ │ ├── l133CloneGraph.java
│ │ │ ├── l134GasStation.java
│ │ │ ├── l135Candy.java
│ │ │ ├── l14LongestCommonPrefix.java
│ │ │ ├── l156BinaryTreeUpsideDown.java
│ │ │ ├── l163SumClosest.java
│ │ │ ├── l184Sum.java
│ │ │ ├── l19RemoveNthNodeFromList.java
│ │ │ ├── l1TwoSum.java
│ │ │ ├── l205IsomorphicString.java
│ │ │ ├── l22GenerateParenthesis.java
│ │ │ ├── l25ReverseKGroup.java
│ │ │ ├── l27RemoveElements.java
│ │ │ ├── l28StrStr.java
│ │ │ ├── l299BullCow.java
│ │ │ ├── l29DivideTwoInteger.java
│ │ │ ├── l2AddTwoNumbers.java
│ │ │ ├── l31NextPermutation.java
│ │ │ ├── l31SearchInRotatedArray.java
│ │ │ ├── l35SearchInsertionPosition.java
│ │ │ ├── l374GuessNumber.java
│ │ │ ├── l375GuessNumberII.java
│ │ │ ├── l376WiggleSubsequence.java
│ │ │ ├── l377CombinationSumIV.java
│ │ │ ├── l378KthSmallInSortedMatrix.java
│ │ │ ├── l37SudokuSolver.java
│ │ │ ├── l382LinkedListRandomNode.java
│ │ │ ├── l383RansonNote.java
│ │ │ ├── l384Shuffling.java
│ │ │ ├── l385MiniParser.java
│ │ │ ├── l387FirstUniqueCharInString.java
│ │ │ ├── l389LexicographicalNumber.java
│ │ │ ├── l41FirstMissingPositive.java
│ │ │ ├── l43Multiply.java
│ │ │ ├── l44WildCard.java
│ │ │ ├── l45JumpGameII.java
│ │ │ ├── l49GroupAnagram.java
│ │ │ ├── l81SearchInRotatedArrayII.java
│ │ │ ├── l82RemoveDuplicateFromSortedListII.java
│ │ │ ├── l83RemoveDuplicateFromSortedList.java
│ │ │ ├── l84MaximalRectangle.java
│ │ │ ├── l86PartitionListII.java
│ │ │ ├── l87ScrambleString.java
│ │ │ ├── l88MergeTwoSortedArray.java
│ │ │ ├── l90SubSetII.java
│ │ │ ├── l91DecodeWays.java
│ │ │ ├── l92ReverseLinkedListII.java
│ │ │ ├── l93RestoreIPAddr.java
│ │ │ ├── l95UniqueBstII.java
│ │ │ ├── l96UniqueBst.java
│ │ │ ├── l97InterleavingString.java
│ │ │ ├── l99RecoverBst.java
│ │ │ ├── lf34SearchRange.java
│ │ │ └── test.js
│ │ ├── lintcode
│ │ │ └── NumberOfPlaneInSky.java
│ │ ├── list
│ │ │ ├── ArrayTest.java
│ │ │ ├── CycleQueue.java
│ │ │ ├── EvenOddList.java
│ │ │ ├── IsLinkedListPalindrome.java
│ │ │ ├── IsLinkedListPalindrome2.java
│ │ │ ├── IsPalindrome.java
│ │ │ ├── MaxQueue.java
│ │ │ ├── SplitLinkedList.java
│ │ │ └── SwapNear.java
│ │ ├── ms
│ │ │ ├── BalanceIndex.java
│ │ │ ├── BinaryIndeTree.java
│ │ │ ├── BinaryTreeSerialization.java
│ │ │ ├── BstLargestSumPath.java
│ │ │ ├── BurstBalloon.java
│ │ │ ├── CircleQueue.java
│ │ │ ├── ClosestBst.java
│ │ │ ├── CopyListWithRandomPointer.java
│ │ │ ├── CountingBit.java
│ │ │ ├── ExcelRowNumberToLabel.java
│ │ │ ├── FindKthLargest.java
│ │ │ ├── FindMinInRotateArray.java
│ │ │ ├── FindProduct.java
│ │ │ ├── FlattenBst.java
│ │ │ ├── GetNumber.java
│ │ │ ├── GraphExistCircle.java
│ │ │ ├── H2O.java
│ │ │ ├── HouseRobberI.java
│ │ │ ├── HouseRobberII.java
│ │ │ ├── ImplementQueueByStack.java
│ │ │ ├── InOrderSuccessorInBst.java
│ │ │ ├── InOrderTraversal.java
│ │ │ ├── JumpGame.java
│ │ │ ├── KthLargest.java
│ │ │ ├── LRUCache.java
│ │ │ ├── Lcs.java
│ │ │ ├── MaxQueue.java
│ │ │ ├── MaxRectangle.java
│ │ │ ├── MergeIntervals.java
│ │ │ ├── MyQueue.java
│ │ │ ├── NextRightPointer.java
│ │ │ ├── NumberOfIsland.java
│ │ │ ├── PaintHouse.java
│ │ │ ├── PaintHouseII.java
│ │ │ ├── PermutatioDeduplicate.java
│ │ │ ├── QuickSort.java
│ │ │ ├── ReverseWordII.java
│ │ │ ├── RotateArray.java
│ │ │ ├── RotateImage.java
│ │ │ ├── RoundRobin.java
│ │ │ ├── ShuffleString.java
│ │ │ ├── SimplyPath.java
│ │ │ ├── SpiralMatrix.java
│ │ │ ├── StockCoolDown.java
│ │ │ ├── StringToInteger.java
│ │ │ ├── Strstr.java
│ │ │ ├── SwapNodeInPair.java
│ │ │ ├── TopologySorting.java
│ │ │ ├── Trie.java
│ │ │ ├── UniqueIP.java
│ │ │ └── WildCardMatch.java
│ │ ├── numbertheory
│ │ │ ├── CountDigitOne.java
│ │ │ ├── DigitalRoot.java
│ │ │ ├── HappyNumber.java
│ │ │ ├── JumpingNumber.java
│ │ │ ├── NextSparseNumber.java
│ │ │ ├── NumberExpressible.java
│ │ │ ├── PascalTriangle.java
│ │ │ ├── PatchingArray.java
│ │ │ ├── PerfectSquare.java
│ │ │ ├── PowerOfThree.java
│ │ │ ├── PowerOfTwo.java
│ │ │ ├── PrintPrimeNumbers.java
│ │ │ ├── SelfCrossing.java
│ │ │ ├── StrobogrammaticII.java
│ │ │ ├── StrobogrammaticII2.java
│ │ │ ├── StrobogrammaticIII.java
│ │ │ ├── SuperUglyNumber.java
│ │ │ └── UglyNumber.java
│ │ ├── os
│ │ │ ├── LRUCache.java
│ │ │ ├── Sync
│ │ │ │ ├── Mutex.java
│ │ │ │ ├── NoSync.java
│ │ │ │ ├── SyncOnMethod.java
│ │ │ │ ├── SyncOnVariable.java
│ │ │ │ └── readme
│ │ │ └── thread
│ │ │ │ ├── H2O.java
│ │ │ │ └── ProducerConsumer.java
│ │ ├── other
│ │ │ └── HashSetTest.java
│ │ ├── practice
│ │ │ ├── AddTwoNumbers.java
│ │ │ ├── BinarySearch.java
│ │ │ ├── Candy.java
│ │ │ ├── FlattenBinaryTree.java
│ │ │ ├── InOrder.java
│ │ │ ├── InterLeaving.java
│ │ │ ├── Kmp.java
│ │ │ ├── LinkedListCycleII.java
│ │ │ ├── LongestIncreasingSubseq.java
│ │ │ ├── MergeInterval.java
│ │ │ ├── MinSubSum.java
│ │ │ ├── PatchingArray.java
│ │ │ ├── PowXNTest.java
│ │ │ ├── QuickSelect.java
│ │ │ ├── QuickSelect2.java
│ │ │ ├── QuickSort.java
│ │ │ ├── ReverseKthGroupNodes.java
│ │ │ ├── ReverseLinkedList.java
│ │ │ ├── SerachInRotatedArray.java
│ │ │ └── WordLadder.java
│ │ ├── probability
│ │ │ ├── ReservoirSampling.java
│ │ │ ├── ReturnWithProbabilityProportionalToItsWeight.java
│ │ │ └── WeightedReservoirSampling.java
│ │ ├── recursion
│ │ │ ├── AllPalindrome.java
│ │ │ ├── BuildNDistanceArray.java
│ │ │ ├── Combination.java
│ │ │ ├── DeepIterator.java
│ │ │ ├── DiffWayCompute.java
│ │ │ ├── FactorCombination.java
│ │ │ ├── FlipGameII.java
│ │ │ ├── IsNumber.java
│ │ │ ├── NextElement
│ │ │ │ ├── Data.java
│ │ │ │ ├── DataIterator.java
│ │ │ │ ├── Node.java
│ │ │ │ ├── readme.txt
│ │ │ │ └── test.java
│ │ │ ├── NumOfPath.java
│ │ │ ├── PrintAllParenthesis.java
│ │ │ ├── RestoreIpAddress.java
│ │ │ ├── SimpleRegularExpression.java
│ │ │ ├── SimpleRegularExpressionDp.java
│ │ │ ├── WildCardMatch.java
│ │ │ └── WordPatternII.java
│ │ ├── sort
│ │ │ ├── GrayCode.java
│ │ │ ├── GroupSort.java
│ │ │ ├── LinkedListMergeSort.java
│ │ │ └── WiggleSortII.java
│ │ ├── stack
│ │ │ ├── LongestParentheses.java
│ │ │ ├── MaxHistogramArea.java
│ │ │ ├── MaxWaterVolume.java
│ │ │ ├── MyStackByQueue.java
│ │ │ ├── OPG.java
│ │ │ └── PeekingIterator.java
│ │ ├── string
│ │ │ ├── MaximumProductofWordLengths.java
│ │ │ ├── RemoveDuplicateLetter.java
│ │ │ ├── ReverseSentence.java
│ │ │ └── ReverseString.java
│ │ ├── test.java
│ │ ├── test2.java
│ │ ├── tree
│ │ │ ├── BinaryIndexedTree.java
│ │ │ ├── BinaryPath.java
│ │ │ ├── CountCompleteTreeNodes.java
│ │ │ ├── CountUnivalSubtrees.java
│ │ │ ├── FindClosestKNode.java
│ │ │ ├── FindPalindromeInBiTree.java
│ │ │ ├── HouseRobberIII.java
│ │ │ ├── InOrderSuccessorForBst.java
│ │ │ ├── IsPreorderSequenceBst.java
│ │ │ ├── LargestBst.java
│ │ │ ├── LargestSumIncludingNegative.java
│ │ │ ├── LowestCommonAncestry.java
│ │ │ ├── LowestCommonAncestryBst.java
│ │ │ ├── MorrisTraversal.java
│ │ │ ├── PathToRight.java
│ │ │ ├── PostOrderTraverse.java
│ │ │ ├── RobHouseIII.java
│ │ │ ├── SegmentTree.java
│ │ │ ├── SuffixTreeTest.java
│ │ │ ├── SumTree.java
│ │ │ ├── TreeSerializing.java
│ │ │ ├── TreeSerializing2.java
│ │ │ ├── VerifyPreorderSerilization.java
│ │ │ ├── VerticalPrint.java
│ │ │ └── suffixtree
│ │ │ │ ├── SuffixTree.java
│ │ │ │ └── util
│ │ │ │ ├── ActivePoint.java
│ │ │ │ ├── LcsRec.java
│ │ │ │ ├── SuffixEdge.java
│ │ │ │ └── SuffixNode.java
│ │ └── util
│ │ │ ├── MQueue.java
│ │ │ ├── MQueue2.java
│ │ │ ├── MaxHeap.java
│ │ │ ├── MyBoolean.java
│ │ │ ├── MyInteger.java
│ │ │ ├── NestedInteger.java
│ │ │ ├── SegIntervalNode.java
│ │ │ ├── SegmentTree1.java
│ │ │ ├── SegmentTree2.java
│ │ │ ├── Tree.java
│ │ │ ├── Tree.pptx
│ │ │ └── TreeNode.java
│ │ └── lambda
│ │ ├── Basic.java
│ │ └── Usage.java
└── js
│ └── IntersectionofTwoArrays.js
└── test
└── java
└── com
└── pli
└── project
└── algorithm
├── SystemOut.java
├── amz
├── AddBinaryTest.java
├── BstRightSideViewTest.java
├── BstTopViewTest.java
├── ClimbingLadderTest.java
├── CombinationSumIITest.java
├── CombinationSumTest.java
├── ConvertToTitleTest.java
├── CountDigitOneTest.java
├── CountNumberWithUniqueDigitTest.java
├── CountPrimesTest.java
├── FindDuplicateTest.java
├── FindKthLargest2Test.java
├── FindKthLargestTest.java
├── FlipGameIITest.java
├── GrayCodeTest.java
├── HouseRobberTest.java
├── IntToRomanTest.java
├── IntegerBinaryPalindromeTest.java
├── IntersectionOfTwoLLTest.java
├── LRUCacheTest.java
├── LetterCombinationOfPhoneNumberTest.java
├── LongestPalindromeSubStringTest.java
├── LongestSubsqeuenceTest.java
├── LongestSubstringAtMostKDiffTest.java
├── LongestSubstringWithoutRepeatingCharactersTest.java
├── LowestCommonAncestorofBstTest.java
├── MergeKSortedListTest.java
├── MinStackTest.java
├── MoveZerosTest.java
├── MyAtoiTest.java
├── NutsAndBoltsMatchTest.java
├── PalindromeLinkedListTest.java
├── PalindromeNumberTest.java
├── PatchingArrayTest.java
├── PermutationTest.java
├── ProductArrayExceptSelfTest.java
├── QuickSortTest.java
├── ReconstructIteneraryTest.java
├── RemoveDupFromSlIITest.java
├── RemoveDupLetttersTest.java
├── RemoveDuplicateTest.java
├── ReverseIntegerTest.java
├── ReverseLinkListIITest.java
├── ReverseWordInStringTest.java
├── RomanToIntTest.java
├── SelfCrossingTest.java
├── SerializeandDeserializeBinaryTreeTest.java
├── SlidingWindowMaximumSlidingWindowMaximumTest.java
├── SortColorTest.java
├── SqrtTest.java
├── TrappingRainWaterTest.java
├── Twitter2Test.java
├── TwitterTest.java
├── VerifyPreorderSerializationTest.java
├── WordBreakTest.java
└── WordSearchIITest.java
├── divideandconquer
└── SkyLineTest.java
├── hash
└── rollinghash
│ └── RollingHashQueueTest.java
├── leetcode
├── CombinationSumIIITest.java
├── ContainDuplicateIIITest.java
├── ContainDuplicateIITest.java
├── ContainDuplicateTest.java
├── LongestStrAtMostKDistinctCharTest.java
├── MinSizeSumArrayTest.java
├── RandomizedCollectionTest.java
├── RandomizedSetTest.java
├── ScheduleCourseTest.java
├── ShortestPalindromeTest.java
├── WordDictionaryTest.java
├── l376WiggleSubsequenceTest.java
├── l383RansonNoteTest.java
├── l43MultiplyTest.java
├── l49GroupAnagramTest.java
└── lc727.java
├── practice
├── AddTwoNumbersTest.java
├── BinarySearchTest.java
├── LinkedListCycleIITest.java
└── WordLadderTest.java
└── recursion
└── WildCardMatchTest.java
/.idea/libraries/Maven__com_googlecode_concurrent_trees_concurrent_trees_1_0_0.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/.idea/libraries/Maven__commons_lang_commons_lang_2_3.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/.idea/libraries/Maven__junit_junit_4_11.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/.idea/libraries/Maven__org_hamcrest_hamcrest_core_1_3.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # algorithm
2 | This is repository is the commit of my algorithm exercise.
3 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/BestBuySellStock.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | /**
4 | * Created by lipeng on 2016/8/11.
5 | * https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
6 | */
7 | public class BestBuySellStock {
8 |
9 | public int maxProfit(int[] prices) {
10 | int profit = 0, low = Integer.MAX_VALUE;
11 | for (int price : prices) {
12 | if (price < low) {
13 | low = price;
14 | }
15 | else {
16 | profit = Math.max(profit, price - low);
17 | }
18 | }
19 | return profit;
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/BinaryTreeLevelOrder.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import com.pli.project.algorithm.leetcode.TreeNode;
4 |
5 | import java.util.ArrayList;
6 | import java.util.List;
7 |
8 | /**
9 | * Created by lipeng on 2016/8/16.
10 | * https://leetcode.com/problems/binary-tree-level-order-traversal/
11 | */
12 | public class BinaryTreeLevelOrder {
13 |
14 | public List> levelOrder(TreeNode root) {
15 | List> list = new ArrayList<>();
16 | helper(root, list, 0);
17 | return list;
18 | }
19 |
20 | private void helper(TreeNode root, List> list, int level) {
21 | if (root == null) {
22 | return;
23 | }
24 | if (level == list.size()) {
25 | list.add(new ArrayList<>());
26 | }
27 | list.get(level).add(root.val);
28 | helper(root.left, list, level + 1);
29 | helper(root.right, list, level + 1);
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/ClimbingLadder.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | /**
4 | * Created by lipeng on 2016/8/21.
5 | * https://leetcode.com/problems/climbing-stairs/
6 | */
7 | public class ClimbingLadder {
8 |
9 | public int climbStairs(int n) {
10 | int[] arr = new int[3];
11 | arr[0] = 1;
12 | arr[1] = 2;
13 | for (int i = 3; i <= n; i++) {
14 | arr[(i + 2) % 3] = arr[(i + 1) % 3] + arr[(i) % 3];
15 | }
16 | return arr[(n + 2) % 3];
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/CloneGraph.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import java.util.ArrayList;
4 | import java.util.HashMap;
5 | import java.util.List;
6 | import java.util.Map;
7 |
8 | /**
9 | * Created by lipeng on 2016/8/23.
10 | * https://leetcode.com/problems/clone-graph/
11 | */
12 | public class CloneGraph {
13 |
14 | class UndirectedGraphNode {
15 | int label;
16 | List neighbors;
17 | UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList(); }
18 | };
19 |
20 | Map map = new HashMap<>();
21 |
22 | public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
23 | if (map.containsKey(node) || node == null) {
24 | return map.get(node);
25 | }
26 | UndirectedGraphNode clone = new UndirectedGraphNode(node.label);
27 | map.put(node, clone);
28 | node.neighbors.forEach(p -> clone.neighbors.add(cloneGraph(p)));
29 | return clone;
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/ConvertToTitle.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | /**
4 | * Created by lipeng on 2016/8/24.
5 | */
6 | public class ConvertToTitle {
7 |
8 | public String convertToTitle(int n) {
9 | StringBuilder sb = new StringBuilder();
10 | while (n > 0) {
11 | n--;
12 | sb.insert(0, (char)(n % 26 + 'A'));
13 | n /= 26;
14 | }
15 | return sb.toString();
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/CountDigitOne.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | /**
4 | * Created by lipeng on 2016/8/19.
5 | */
6 | public class CountDigitOne {
7 |
8 | /*
9 | For n = 54321, k = 1, 10, 100, 1000, 10000
10 | when k = 100, should divide into 54, 3, 21
11 | l = 543,
12 | m = 543 % 100 = 3
13 | r = 54321 - 543 * 100 = 21
14 | l = 543 / 10 = 543
15 | */
16 | public int countDigitOne(int n) {
17 | int ans = 0;
18 | for (long k = 1; k <= n; k *= 10) {
19 | long tmp = n / k;
20 | long mid = tmp % 10;
21 | long right = n - tmp * k;
22 | long left = tmp / 10;
23 | ans += left * k;
24 | if (mid > 1) {
25 | ans += k;
26 | }
27 | else if (mid == 1) {
28 | ans += right + 1;
29 | }
30 | }
31 | return ans;
32 | }
33 |
34 | public static void main(String[] args) {
35 | // countDigitOne(12345);
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/CountNumberWithUniqueDigit.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | /**
4 | * Created by lipeng on 2016/8/24.
5 | * https://leetcode.com/problems/count-numbers-with-unique-digits/
6 | */
7 | public class CountNumberWithUniqueDigit {
8 |
9 | public int countNumbersWithUniqueDigits(int n) {
10 | if (n == 0) {
11 | return 1;
12 | }
13 | int ans = 10, base = 9;
14 | for (int i = 2; i <= 10 && i <= n; i++) {
15 | base *= 11 - i;
16 | ans += base;
17 | }
18 | return ans;
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/CountPrimes.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/16.
7 | * https://leetcode.com/problems/count-primes/
8 | * Count the number of prime numbers less than a non-negative number, n.
9 | * Pay attention it asks the number of prime LESS THAN n. Not saying equal to n.
10 | */
11 | public class CountPrimes {
12 |
13 | public int countPrimes(int n) {
14 | boolean[] dp = new boolean[n];
15 | int ans = 0;
16 | for (int i = 2; i < n; i++) {
17 | if (dp[i]) {
18 | continue;
19 | }
20 | ans++;
21 | for (int j = i + i; j < n; j += i) {
22 | dp[j] = true;
23 | }
24 | }
25 | return ans;
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/Excel1.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | /**
4 | * Created by lipeng on 2016/8/24.
5 | * From A -> 1, AB -> 28
6 | */
7 | public class Excel1 {
8 |
9 | public int titleToNumber(String s) {
10 | int ans = 0, base = 1;
11 | for (int i = s.length() - 1; i >= 0; i--) {
12 | char ch = s.charAt(i);
13 | ans += (ch - 'A' + 1) * base;
14 | base *= 26;
15 | }
16 | return ans;
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/FindDuplicate.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | /**
4 | * Created by lipeng on 2016/8/17.
5 | */
6 | public class FindDuplicate {
7 |
8 | public int findDuplicate(int[] nums) {
9 | int fast = nums.length, slow = nums.length;
10 | do {
11 | fast = nums[nums[fast - 1] - 1];
12 | slow = nums[slow - 1];
13 | } while (fast != slow);
14 | slow = nums.length;
15 | while (slow != fast) {
16 | slow = nums[slow - 1];
17 | fast = nums[fast - 1];
18 | }
19 | return slow;
20 | }
21 |
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/GrayCode.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * Created by lipeng on 2016/8/16.
8 | * https://leetcode.com/problems/gray-code/
9 | */
10 | public class GrayCode {
11 |
12 | public List grayCode(int n) {
13 | List ans = new ArrayList<>();
14 | ans.add(0);
15 | for (int i = 1, base = 1; i <= n; i++, base = base << 1) {
16 | for (int j = ans.size() - 1; j >= 0; j--) {
17 | ans.add(ans.get(j) | base);
18 | }
19 | }
20 | return ans;
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/HasCycle.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import com.pli.project.algorithm.leetcode.ListNode;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/23.
7 | * https://leetcode.com/problems/linked-list-cycle/
8 | */
9 | public class HasCycle {
10 |
11 | public boolean hasCycle(ListNode head) {
12 | ListNode slow = head, fast = head;
13 | do {
14 | if (fast == null || fast.next == null) {
15 | return false;
16 | }
17 | slow = slow.next;
18 | fast = fast.next.next;
19 | } while (slow != fast);
20 | return true;
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/HouseRobber.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | /**
4 | * Created by lipeng on 2016/8/20.
5 | */
6 | public class HouseRobber {
7 |
8 | public int rob2(int[] nums) {
9 | int[] maxRob = new int[nums.length + 2], max = new int[nums.length + 2];
10 | for (int i = 0; i < nums.length; i++) {
11 | maxRob[i + 2] = nums[i] + max[i];
12 | max[i + 2] = Math.max(maxRob[i + 2], max[i + 1]);
13 | }
14 | return max[nums.length + 1];
15 | }
16 |
17 | public int rob(int[] nums) {
18 | int rob = 0, noRob = 0;
19 | for (int i : nums) {
20 | int preRob = rob, preNoRob = noRob;
21 | rob = i + preNoRob;
22 | noRob = Math.max(preRob, preNoRob);
23 | }
24 | return Math.max(rob, noRob);
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/HouseRobberII.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | /**
4 | * Created by lipeng on 2016/8/20.
5 | */
6 | public class HouseRobberII {
7 |
8 | public int rob(int[] nums) {
9 | if (nums == nums || nums.length < 1) {
10 | return 0;
11 | }
12 | if (nums.length == 1) {
13 | return nums[0];
14 | }
15 | return Math.max(helper(nums, 0, nums.length - 2), helper(nums, 1, nums.length - 1));
16 | }
17 |
18 | private int helper(int[] nums, int i, int j) {
19 | int rob = 0, noRob = 0;
20 | for (int k = 1; k <= j; k++) {
21 | int r = rob, n = noRob;
22 | rob = nums[k] + n;
23 | noRob = Math.max(r, n);
24 | }
25 | return Math.max(rob, noRob);
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/HouseRobberIII.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import com.pli.project.algorithm.util.TreeNode;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/20.
7 | */
8 | public class HouseRobberIII {
9 |
10 | public int rob(TreeNode root) {
11 | int[] ans = helper(root);
12 | return Math.max(ans[0], ans[1]);
13 | }
14 |
15 | /* ans[] = {rob, noRob}
16 | rob = leftNoRob + rightNoRob + root.value;
17 | noRob = max(leftRob, leftNoRob) + max(rightRob, rightNoRob)
18 | */
19 | private int[] helper(TreeNode node) {
20 | if (node == null) {
21 | return new int[2];
22 | }
23 | int[] left = helper(node.left);
24 | int[] right = helper(node.right);
25 | int[] ans = new int[2];
26 | ans[0] = node.val + left[1] + right[1];
27 | ans[1] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
28 | return ans;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/IntegerBinaryPalindrome.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | /**
4 | * Created by lipeng on 2016/8/23.
5 | * Check if the binary of the number is palindrome
6 | */
7 | public class IntegerBinaryPalindrome {
8 |
9 | public boolean isPalindrome(int n) {
10 | int a = n, b = 0;
11 | while (b < n) {
12 | b = (b << 1) | (a & 1);
13 | a = a >> 1;
14 | }
15 | return b == n;
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/IntersectionOfTwoLL.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import com.pli.project.algorithm.leetcode.ListNode;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/14.
7 | * https://leetcode.com/problems/intersection-of-two-linked-lists/
8 | */
9 | public class IntersectionOfTwoLL {
10 |
11 | public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
12 | ListNode a = headA, b = headB; // need to define a, b
13 | while (a != b) {
14 | a = a == null ? headB : a.next;
15 | b = b == null ? headA : b.next;
16 | }
17 | return a;
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/Lca.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import com.pli.project.algorithm.util.TreeNode;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/9.
7 | */
8 | public class Lca {
9 |
10 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
11 | if (root == null || p == root || q == root) {
12 | return root;
13 | }
14 | TreeNode left = lowestCommonAncestor(root.left, p, q);
15 | TreeNode right = lowestCommonAncestor(root.right, p, q);
16 | if (left != null && right != null) {
17 | return root;
18 | }
19 | return left != null ? left : right;
20 | }
21 |
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/LinkedListCycle.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import com.pli.project.algorithm.leetcode.ListNode;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/12.
7 | * https://leetcode.com/problems/linked-list-cycle/
8 | */
9 | public class LinkedListCycle {
10 |
11 | public boolean hasCycle(ListNode head) {
12 | ListNode slow = head, fast = head.next.next;
13 | while (fast != null && fast.next != null) {
14 | slow = slow.next;
15 | fast = fast.next.next;
16 | if (slow == fast) {
17 | return true;
18 | }
19 | }
20 | return false;
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/LinkedListCycleII.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import com.pli.project.algorithm.leetcode.ListNode;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/23.
7 | * https://leetcode.com/problems/linked-list-cycle-ii/
8 | */
9 | public class LinkedListCycleII {
10 |
11 | public ListNode detectCycle(ListNode head) {
12 | ListNode slow = head, fast = head;
13 | do {
14 | if (fast == null || fast.next == null) {
15 | return null;
16 | }
17 | slow = slow.next;
18 | fast = fast.next.next;
19 | } while (slow == fast);
20 | while (head != slow) {
21 | slow = slow.next;
22 | head = head.next;
23 | }
24 | return slow;
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/LongestSubsqeuence.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/24.
7 | */
8 | public class LongestSubsqeuence {
9 |
10 | public int lengthOfLIS(int[] nums) {
11 | int[] dp = new int[nums.length];
12 | // Arrays.fill(dp, Integer.MAX_VALUE);
13 | int len = 0;
14 | for (int i : nums) {
15 | int index = Arrays.binarySearch(dp, 0, len, i);
16 | if (index < 0) {
17 | index = - (index + 1);
18 | }
19 | if (index == len) {
20 | len++;
21 | }
22 | dp[index] = i;
23 | }
24 | return len;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/LongestSubstringWithoutRepeatingCharacters.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | /**
7 | * Created by lipeng on 2016/8/11.
8 | */
9 | public class LongestSubstringWithoutRepeatingCharacters {
10 |
11 | public int lengthOfLongestSubstring(String s) {
12 | Set set = new HashSet<>();
13 | int left = 0, right = 0, ans = 0;
14 | while (right < s.length()) {
15 | if (set.contains(s.charAt(right))) { // has duplicate, move left until there is no duplicate between [left, right]
16 | set.remove(s.charAt(left++));
17 | }
18 | else {
19 | set.add(s.charAt(right++)); // has no duplicate between [left, right], move right
20 | ans = Math.max(ans, right - left);
21 | }
22 | }
23 | return ans;
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/MergeKSortedList.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import com.pli.project.algorithm.leetcode.ListNode;
4 |
5 | import java.util.Comparator;
6 | import java.util.PriorityQueue;
7 |
8 | /**
9 | * Created by lipeng on 2016/8/15.
10 | * https://leetcode.com/problems/merge-k-sorted-lists/
11 | */
12 | public class MergeKSortedList {
13 |
14 | public ListNode mergeKLists(ListNode[] lists) {
15 | PriorityQueue queue = new PriorityQueue<>((l1, l2) -> l1.val - l2.val);
16 | for (ListNode node : lists) {
17 | if (node == null) {
18 | continue;
19 | }
20 | queue.add(node);
21 | }
22 | ListNode dummyHead = new ListNode(-1), curr = dummyHead;
23 | while (!queue.isEmpty()) {
24 | curr.next = queue.poll();
25 | curr = curr.next;
26 | if (curr.next != null) {
27 | queue.add(curr.next);
28 | }
29 | }
30 | return dummyHead.next;
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/MergeKSortedList2.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import com.pli.project.algorithm.leetcode.ListNode;
4 |
5 | import java.util.Arrays;
6 | import java.util.Collections;
7 | import java.util.PriorityQueue;
8 | import java.util.Queue;
9 |
10 | /**
11 | * Created by lipeng on 2016/8/23.
12 | * https://leetcode.com/problems/merge-k-sorted-lists/
13 | */
14 | public class MergeKSortedList2 {
15 |
16 | public ListNode mergeKLists(ListNode[] lists) {
17 | Queue queue = new PriorityQueue<>((p1, p2) -> p1.val - p2.val);
18 | ListNode dummyHead = new ListNode(-1), curr = dummyHead;
19 | Arrays.stream(lists).filter(p -> p != null).forEach(p -> queue.add(p));
20 | while (!queue.isEmpty()) {
21 | ListNode node = queue.poll();
22 | curr.next = node;
23 | curr = node;
24 | if (node.next != null) {
25 | queue.add(node.next);
26 | }
27 | }
28 | curr.next = null;
29 | return dummyHead.next;
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/MinStack2.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import java.util.Stack;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/10.
7 | */
8 | public class MinStack2 {
9 |
10 | Stack s;
11 | Stack minBucket;
12 |
13 | public MinStack2() {
14 | s = new Stack<>();
15 | minBucket = new Stack<>();
16 | minBucket.push(Integer.MAX_VALUE);
17 | }
18 |
19 | public void push(int x) {
20 | s.push(x);
21 | minBucket.push(Math.min(minBucket.peek(), x));
22 | }
23 |
24 | public void pop() {
25 | s.pop();
26 | minBucket.pop();
27 | }
28 |
29 | public int top() {
30 | return s.peek();
31 | }
32 |
33 | public int getMin() {
34 | return minBucket.peek();
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/MinStack3.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import java.util.Stack;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/20.
7 | */
8 | public class MinStack3 {
9 |
10 | long min;
11 | Stack stack;
12 |
13 | public MinStack3() {
14 | stack = new Stack<>();
15 | }
16 |
17 | public void push(int x) {
18 | if (stack.size() == 0) {
19 | min = x;
20 | stack.push(0l);
21 | }
22 | else {
23 | stack.push(x - min);
24 | min = Math.min(min, x);
25 | }
26 | }
27 |
28 | public void pop() {
29 | long pop = stack.pop();
30 | if (pop < 0) {
31 | min = min - pop;
32 | }
33 | }
34 |
35 | public int top() {
36 | long top = stack.peek();
37 | if (top < 0) {
38 | return (int)min;
39 | }
40 | return (int)(top + min);
41 | }
42 |
43 | public int getMin() {
44 | return (int)min;
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/MoveZeros.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | /**
4 | * Created by lipeng on 2016/8/16.
5 | */
6 | public class MoveZeros {
7 |
8 | public static void moveZeroes(int[] nums) {
9 | int left = 0, right = 0;
10 | while (right < nums.length) {
11 | if (nums[right] != 0) {
12 | swap(nums, left++, right);
13 | }
14 | right++;
15 | }
16 | }
17 |
18 | private static void swap(int[] nums, int i, int j) {
19 | int tmp = nums[i];
20 | nums[i] = nums[j];
21 | nums[j] = tmp;
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/Nim.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | /**
4 | * Created by lipeng on 2016/8/22.
5 | * https://leetcode.com/problems/nim-game/
6 | * http://www.allenlipeng47.com/blog/index.php/2016/01/16/study-summaries-for-game-theory/
7 | */
8 | public class Nim {
9 |
10 | public boolean canWinNim(int n) {
11 | return n % 4 != 0;
12 | }
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/NumberOfIslands.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | /**
4 | * Created by lipeng on 2016/8/9.
5 | */
6 | public class NumberOfIslands {
7 |
8 | public int numIslands(char[][] grid) {
9 | int ans = 0;
10 | for (int i = 0; i < grid.length; i++) {
11 | for (int j = 0; j < grid[0].length; j++) {
12 | if (grid[i][j] == '1') {
13 | ans++;
14 | helper(grid, i, j);
15 | }
16 | }
17 | }
18 | return ans;
19 | }
20 |
21 | public void helper(char[][] grid, int i, int j) {
22 | if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || grid[i][j] != '1') {
23 | return;
24 | }
25 | grid[i][j] = 'a';
26 | helper(grid, i - 1, j);
27 | helper(grid, i + 1, j);
28 | helper(grid, i, j - 1);
29 | helper(grid, i, j + 1);
30 | }
31 |
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/PalindromeNumber.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | /**
4 | * Created by lipeng on 2016/8/23.
5 | * https://leetcode.com/problems/palindrome-number/
6 | */
7 | public class PalindromeNumber {
8 |
9 | // 1. negative number doesn't has palindrome
10 | // 2. number with last digit 0 is not palindrome. Such as 1310
11 | public boolean isPalindrome(int x) {
12 | if (x < 0 || x != 0 && x % 10 == 0) {
13 | return false;
14 | }
15 | long a = 0, b = x;
16 | while (a < x) {
17 | a = a * 10 + b % 10;
18 | b /= 10;
19 | }
20 | return a == x;
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/PatchingArray.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | /**
4 | * Created by lipeng on 2016/8/19.
5 | */
6 | public class PatchingArray {
7 |
8 | public int minPatches(int[] nums, int n) {
9 | long reach = 0;
10 | int i = 0, ans = 0;
11 | while (reach < n) {
12 | if (i < nums.length && reach + 1 >= nums[i]) {
13 | reach += nums[i];
14 | i++;
15 | }
16 | else {
17 | ans++;
18 | reach = reach * 2 + 1;
19 | }
20 | }
21 | return ans;
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/ProductArrayExceptSelf.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/11.
7 | * https://leetcode.com/problems/product-of-array-except-self/
8 | */
9 | public class ProductArrayExceptSelf {
10 |
11 | public int[] productExceptSelf(int[] nums) {
12 | int[] product = new int[nums.length];
13 | Arrays.fill(product, 1);
14 | int leftProduct = nums[0];
15 | for (int i = 1; i < nums.length; i++) {
16 | product[i] = leftProduct;
17 | leftProduct *= nums[i];
18 | }
19 | int rightProduct = nums[nums.length - 1];
20 | for (int i = nums.length - 2; i >= 0; i--) {
21 | product[i] *= rightProduct;
22 | rightProduct *= nums[i];
23 | }
24 | return product;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/QuickSort.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | /**
4 | * Created by lipeng on 2016/8/20.
5 | */
6 | public class QuickSort {
7 |
8 | public void quickSort(int[] nums) {
9 | partition(nums, 0, nums.length - 1);
10 | }
11 |
12 | private void partition(int[] nums, int left, int right) {
13 | int lo = left, hi = right;
14 | if (lo >= hi) {
15 | return;
16 | }
17 | int pivot = nums[lo];
18 | while (lo < hi) {
19 | while (lo < hi && pivot <= nums[hi]) {
20 | hi--;
21 | }
22 | nums[lo] = nums[hi];
23 | while (lo < hi && pivot >= nums[lo]) {
24 | lo++;
25 | }
26 | nums[hi] = nums[lo];
27 | }
28 | nums[lo] = pivot;
29 | partition(nums, left, lo - 1);
30 | partition(nums, lo + 1, right);
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/RemoveDuplicate.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | /**
4 | * Created by lipeng on 2016/8/21.
5 | * https://leetcode.com/problems/remove-duplicates-from-sorted-array/
6 | */
7 | public class RemoveDuplicate {
8 |
9 | public int removeDuplicates2(int[] nums) {
10 | int left = 0, right = 1;
11 | while (right < nums.length) {
12 | while (right < nums.length && nums[left] == nums[right]) {
13 | right++;
14 | }
15 | if (right >= nums.length) {
16 | break;
17 | }
18 | left++;
19 | nums[left] = nums[right];
20 | right++;
21 | }
22 | return left + 1;
23 | }
24 |
25 | public int removeDuplicates(int[] nums) {
26 | int left = 0;
27 | for (int right = 1; right < nums.length; right++) {
28 | if (nums[left] != nums[right]) {
29 | nums[++left] = nums[right];
30 | }
31 | }
32 | return left + 1;
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/ReverseInteger.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import com.pli.project.algorithm.exercise2014.IntegerSet;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/20.
7 | * https://leetcode.com/problems/reverse-integer/
8 | */
9 | public class ReverseInteger {
10 |
11 | public int reverse(int x) {
12 | int sign = 1;
13 | if (x < 0) {
14 | sign = -1;
15 | x = -x;
16 | }
17 | int ans = 0;
18 | while (x > 0) {
19 | if (Integer.MAX_VALUE / 10 < ans) { // ignore the overflow value.
20 | return 0;
21 | }
22 | int low = x % 10;
23 | ans = ans * 10 + low;
24 | x /= 10;
25 | }
26 | return ans * sign;
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/ReverseLinkedList.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import com.pli.project.algorithm.leetcode.ListNode;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/23.
7 | * https://leetcode.com/problems/reverse-linked-list/
8 | */
9 | public class ReverseLinkedList {
10 |
11 | public ListNode reverseList(ListNode head) {
12 | ListNode dummyHead = new ListNode(-1);
13 | while (head != null) {
14 | ListNode next = head.next;
15 | head.next = dummyHead.next;
16 | dummyHead.next = head;
17 | head = next;
18 | }
19 | return dummyHead.next;
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/ReverseWordInString.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | /**
4 | * Created by lipeng on 2016/8/23.
5 | */
6 | public class ReverseWordInString {
7 |
8 | public String reverseWords(String s) {
9 | char[] chs = s.trim().toCharArray();
10 | for (int i = 0, j = 0; j <= chs.length; j++) {
11 | if (j == chs.length || chs[j] == ' ') {
12 | reverse(chs, i, j - 1);
13 | i = j + 1;
14 | }
15 | }
16 | reverse(chs, 0, chs.length - 1);
17 | return new String(chs);
18 | }
19 |
20 | private void reverse(char[] chs, int i, int j) {
21 | while (i < j) {
22 | char ch = chs[i];
23 | chs[i] = chs[j];
24 | chs[j] = ch;
25 | i++;
26 | j--;
27 | }
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/RomanToInt.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | /**
7 | * Created by lipeng on 2016/8/22.
8 | */
9 | public class RomanToInt {
10 |
11 | public int romanToInt(String s) {
12 | Map map = new HashMap<>();
13 | map.put('I', 1);
14 | map.put('V', 5);
15 | map.put('X', 10);
16 | map.put('L', 50);
17 | map.put('C', 100);
18 | map.put('D', 500);
19 | map.put('M', 1000);
20 | int ans = 0, last = 0;
21 | for (int i = s.length() - 1; i >= 0; i--) {
22 | int curr = map.get(s.charAt(i));
23 | curr = curr < last ? -curr : curr;
24 | ans += curr;
25 | last = curr;
26 | }
27 | return ans;
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/RotateImage.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | /**
4 | * Created by lipeng on 2016/8/11.
5 | */
6 | public class RotateImage {
7 |
8 | public void rotate(int[][] matrix) {
9 | int top = 0, bottom = matrix.length - 1;
10 | while (top < bottom) {
11 | for (int i = 0; i < matrix[0].length; i++) {
12 | int tmp = matrix[top][i];
13 | matrix[top][i] = matrix[bottom][i];
14 | matrix[bottom][i] = tmp;
15 | }
16 | top++;
17 | bottom--;
18 | }
19 | for (int i = 1; i < matrix.length; i++) {
20 | for (int j = 0; j < i; j++) {
21 | int tmp = matrix[i][j];
22 | matrix[i][j] = matrix[j][i];
23 | matrix[j][i] = tmp;
24 | }
25 | }
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/SearchTwoDMatrix.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | /**
4 | * Created by lipeng on 2016/8/11.
5 | * https://leetcode.com/problems/search-a-2d-matrix-ii/
6 | */
7 | public class SearchTwoDMatrix {
8 |
9 | public boolean searchMatrix(int[][] matrix, int target) {
10 | int i = 0, j = matrix[0].length - 1;
11 | while (i < matrix.length && j >= 0) {
12 | if (matrix[i][j] == target) {
13 | return true;
14 | }
15 | if (target < matrix[i][j]) {
16 | j--;
17 | }
18 | else {
19 | i++;
20 | }
21 | }
22 | return false;
23 | }
24 |
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/SelfCrossing.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | /**
4 | * Created by lipeng on 2016/8/20.
5 | */
6 | public class SelfCrossing {
7 |
8 | public boolean isSelfCrossing(int[] x) {
9 | if (x.length <= 3) {
10 | return false;
11 | }
12 | for (int i = 3; i < x.length; i++) {
13 | if (i >= 3 && x[i] >= x[i - 2] && x[i - 1] <= x[i - 3]) {
14 | return true;
15 | }
16 | if (i >= 4 && x[i - 1] == x[i - 3] && x[i] + x[i - 4] >= x[i - 2]) {
17 | return true;
18 | }
19 | if (i >= 5 && x[i] + x[i - 4] >= x[i - 2] && x[i - 5] + x[i - 1] >= x[i - 3]
20 | && x[i - 2] >= x[i - 4] && x[i - 1] <= x[i -3]) {
21 | return true;
22 | }
23 | }
24 | return false;
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/SortColors.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | /**
4 | * Created by lipeng on 2016/8/21.
5 | * https://leetcode.com/problems/sort-colors/
6 | */
7 | public class SortColors {
8 |
9 | public void sortColors(int[] nums) {
10 | int pos0 = 0, pos1 = 0;
11 | for (int i = 0; i < nums.length; i++) {
12 | if (nums[i] == 1) {
13 | swap(nums, pos1++, i);
14 | }
15 | else if (nums[i] == 0) {
16 | swap(nums, pos1, i);
17 | swap(nums, pos0++, pos1++);
18 | }
19 | }
20 | }
21 |
22 | private void swap(int[] nums, int i, int j) {
23 | int tmp = nums[i];
24 | nums[i] = nums[j];
25 | nums[j] = tmp;
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/Sqrt.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/21.
7 | */
8 | public class Sqrt {
9 |
10 | public double mySqrt(int x) {
11 | double left = 0, right = x;
12 | while (left < right) {
13 | double mid = left + (right - left) / 2;
14 | double pow = Math.pow(mid, 2);
15 | if (Math.abs(pow - x) < 0.1) {
16 | return mid;
17 | }
18 | else if (pow > x) {
19 | right = mid;
20 | }
21 | else {
22 | left = mid;
23 | }
24 | }
25 | return 0;
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/SymmetryTree.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import com.pli.project.algorithm.leetcode.TreeNode;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/23.
7 | * https://leetcode.com/problems/symmetric-tree/
8 | */
9 | public class SymmetryTree {
10 |
11 | public boolean isSymmetric(TreeNode root) {
12 | return helper(root, root);
13 | }
14 |
15 | private boolean helper(TreeNode t1, TreeNode t2) {
16 | if (t1 == null && t2 == null) {
17 | return true;
18 | }
19 | if (t1 == null || t2 == null) {
20 | return false;
21 | }
22 | return t1.val == t2.val && helper(t1.left, t2.right) && helper(t1.right, t2.left);
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/ValidAnagram.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | /**
4 | * Created by lipeng on 2016/8/11.
5 | */
6 | public class ValidAnagram {
7 |
8 | public boolean isAnagram(String s, String t) {
9 | int[] count = new int[26];
10 | for (int i = 0; i < s.length(); i++) {
11 | count[s.charAt(i) - 'a']++;
12 | count[t.charAt(i) - 'a']--;
13 | }
14 | for (int i : count) {
15 | if (i != 0) {
16 | return false;
17 | }
18 | }
19 | return true;
20 | }
21 |
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/ValidParentheses.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import java.util.LinkedList;
4 | import java.util.Stack;
5 |
6 | /**
7 | * Created by lipeng on 2016/8/10.
8 | * https://leetcode.com/problems/valid-parentheses/
9 | */
10 | public class ValidParentheses {
11 |
12 | public boolean isValid(String s) {
13 | Stack l = new Stack<>();
14 | for (int i = 0; i < s.length(); i++) {
15 | char ch = s.charAt(i);
16 | if (ch == '(' || ch == '[' || ch == '{') {
17 | l.add(ch);
18 | continue;
19 | }
20 | if (!l.isEmpty() && (ch == ')' && l.peek() == '('
21 | || ch == ']' && !l.isEmpty() && l.peek() == '['
22 | || ch == '}' && !l.isEmpty() && l.peek() == '{')) {
23 | l.pop();
24 | }
25 | else {
26 | return false;
27 | }
28 | }
29 | return l.isEmpty();
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/ValidateBst.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import com.pli.project.algorithm.util.TreeNode;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/12.
7 | * https://leetcode.com/problems/validate-binary-search-tree/
8 | */
9 | public class ValidateBst {
10 |
11 | public boolean isValidBST(TreeNode root) {
12 | return helper(root, Long.MIN_VALUE, Long.MAX_VALUE);
13 | }
14 |
15 | private boolean helper(TreeNode root, long min, long max) {
16 | if (root == null) {
17 | return true;
18 | }
19 | if (root.val <= min || root.val >= max) {
20 | return false;
21 | }
22 | return helper(root.left, min , root.val) && helper(root.right, root.val, max);
23 | }
24 |
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/VerifyPreorderSerialization.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | /**
4 | * Created by lipeng on 2016/8/17.
5 | */
6 | public class VerifyPreorderSerialization {
7 |
8 | public boolean isValidSerialization(String preorder) {
9 | String[] strs = preorder.split(" ");
10 | int num = 1;
11 | for (String str : strs) {
12 | if (--num < 0) {
13 | return false;
14 | }
15 | if (!"#".equals(str)) {
16 | num += 2;
17 | }
18 | }
19 | return num == 0;
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/WordBreak.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import java.util.Set;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/11.
7 | */
8 | public class WordBreak {
9 |
10 | public boolean wordBreak(String s, Set wordDict) {
11 | boolean[] dp = new boolean[s.length() + 1];
12 | dp[0] = true;
13 | for (int i = 0; i < s.length(); i++) {
14 | if (!dp[i]) {
15 | continue;
16 | }
17 | for (String word : wordDict) {
18 | if (i + word.length() <= s.length() && s.substring(i, i + word.length()).equals(word)) {
19 | dp[i + word.length()] = true;
20 | }
21 | }
22 | }
23 | return dp[s.length()];
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/amz/l21MergeTwoSortedList.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import com.pli.project.algorithm.leetcode.ListNode;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/14.
7 | */
8 | public class l21MergeTwoSortedList {
9 |
10 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
11 | ListNode dummyHead = new ListNode(-1), curr = dummyHead;
12 | while (l1 != null && l2 != null) {
13 | if (l1.val < l2.val) {
14 | curr.next = l1;
15 | l1 = l1.next;
16 | }
17 | else {
18 | curr.next = l2;
19 | l2 = l2.next;
20 | }
21 | curr = curr.next;
22 | }
23 | if (l1 != null) {
24 | curr.next = l1;
25 | }
26 | else {
27 | curr.next = l2;
28 | }
29 | return dummyHead.next;
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/array/ContainerWithMostWater.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.array;
2 |
3 | /**
4 | * Created by lipeng on 2016/7/5.
5 | * https://leetcode.com/problems/container-with-most-water/
6 | * The solution is to calculate the area size of left and right pillar. Then left or right depending on which pillar is shorter.
7 | */
8 | public class ContainerWithMostWater {
9 |
10 | public int maxArea(int[] height) {
11 | int max = 0, left = 0, right = height.length - 1;
12 | while (left < right) {
13 | int currArea = (right - left) * Math.min(height[right], height[left]);
14 | max = Math.max(max, currArea);
15 | if (height[left] < height[right]) { // move the shorter pillar inside
16 | left++;
17 | }
18 | else {
19 | right--;
20 | }
21 | }
22 | return max;
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/array/FirstBadVersion.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.array;
2 |
3 | /**
4 | * Created by lipeng on 2016/1/17.
5 | * https://leetcode.com/problems/first-bad-version/
6 | */
7 | public class FirstBadVersion {
8 |
9 | /*
10 | public static int firstBadVersion(int n) {
11 | if (isBadVersion(0))
12 | return 0;
13 | int left = 1, right = n;
14 | while (left <= right) {
15 | int mid = left + (right - left) / 2;
16 | if (isBadVersion(mid)) {
17 | if (!isBadVersion(mid - 1))
18 | return mid;
19 | else
20 | right = mid - 1;
21 | }
22 | else
23 | left = mid + 1;
24 | }
25 | return -1;
26 | } */
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/array/HIndex.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.array;
2 |
3 |
4 | import java.util.Arrays;
5 |
6 | /**
7 | * Created by lipeng on 2016/1/18.
8 | */
9 | public class HIndex {
10 |
11 | public static int hIndex(int[] citations) {
12 | Arrays.sort(citations);
13 | int n = citations.length;
14 | for (int i = 0; i < n; i++) {
15 | int totalCitation = n - 1 - i + 1;
16 | if (citations[i] >= totalCitation)
17 | return totalCitation;
18 | }
19 | return 0;
20 | }
21 |
22 | public static void main(String[] args) {
23 | // int[] citations = {3, 0, 6, 1, 5};
24 | int[] citations = {5, 5, 5};
25 | System.out.println(hIndex(citations));
26 |
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/array/LongestContinuousOne2.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.array;
2 |
3 | /**
4 | * Created by lipeng on 2015/11/19.
5 | */
6 | public class LongestContinuousOne2 {
7 |
8 | public static int getLongestContinuous1(String s, int maxFlips) {
9 | int p1=0, p2=0, len = s.length(), num0=0, max=0;
10 | while(p2 maxFlips){
17 | while(s.charAt(p1)=='1')
18 | p1++;
19 | p1++; num0--;
20 | }
21 |
22 | p2++;
23 | max = Math.max(max, p2-p1);
24 | }
25 | return max;
26 | }
27 |
28 |
29 | public static void main(String[] args) {
30 | String str = "011010101";
31 | System.out.println(getLongestContinuous1(str, 1));
32 |
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/array/MaxSubarray.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.array;
2 |
3 | /**
4 | * Created by lipeng on 2016/6/26.
5 | * https://en.wikipedia.org/wiki/Maximum_subarray_problem
6 | * This is also called Kadane's algorithm. It is a traditional one!
7 | */
8 | public class MaxSubarray {
9 |
10 | public static int maxSubArray(int []arr) {
11 | int max = arr[0], currMax = arr[0];
12 | for (int i = 1; i < arr.length; i++) {
13 | currMax = Math.max(currMax + arr[i], arr[i]);
14 | max = Math.max(max, currMax);
15 | }
16 | return max;
17 | }
18 |
19 | public static void main(String[] args) {
20 | int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
21 | System.out.println(maxSubArray(arr));
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/array/MinStack.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.array;
2 |
3 | import java.util.ArrayDeque;
4 | import java.util.Deque;
5 |
6 | /**
7 | * Created by lipeng on 2016/7/4.
8 | */
9 | public class MinStack {
10 |
11 | Deque stack;
12 | Deque minStack;
13 |
14 | /** initialize your data structure here. */
15 | public MinStack() {
16 | stack = new ArrayDeque<>();
17 | minStack = new ArrayDeque<>();
18 | minStack.add(Integer.MAX_VALUE);
19 | }
20 |
21 | public void push(int x) {
22 | stack.push(x);
23 | if (x <= minStack.peek()) {
24 | minStack.push(x);
25 | }
26 | }
27 |
28 | public void pop() {
29 | int x = stack.pop();
30 | if (x == minStack.peek()) {
31 | minStack.pop();
32 | }
33 | }
34 |
35 | public int top() {
36 | return stack.peek();
37 | }
38 |
39 | public int getMin() {
40 | return minStack.peek();
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/array/NumberOfTriangle.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.array;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * Created by pli on 12/22/2015.
7 | * Given an array with all element greater than 0. Find the number of group which it can group to a triangle
8 | * Given {3, 4, 5}, return 1
9 | * Given {3, 4, 5, 6}, return 4
10 | */
11 | public class NumberOfTriangle {
12 |
13 | public static int getNumberOfTriangle(int[] arr) {
14 | assert arr!=null && arr.length>3;
15 | Arrays.sort(arr);
16 | int num = 0;
17 | for(int i=0; iarr[k])
21 | k++;
22 | num = num + k - j - 1;
23 | }
24 | }
25 | return num;
26 | }
27 |
28 | public static void main(String[] args) {
29 | int[] arr = {3, 4, 5, 6};
30 | System.out.println(getNumberOfTriangle(arr));
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/array/PartitionRandomPivot.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.array;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/12.
7 | */
8 | public class PartitionRandomPivot {
9 |
10 | public static int partition(int[] arr, int low, int high, int pivot) {
11 | int i = low;
12 | for (int j = low; j < high; j++) {
13 | if (arr[j] < pivot){
14 | swap(arr, i, j);
15 | i++;
16 | } else if(arr[j] == pivot){
17 | swap(arr, j, high);
18 | j--;
19 | }
20 | }
21 | swap(arr, i, high);
22 | return i;
23 | }
24 |
25 | public static void swap(int[] nums, int i, int j) {
26 | int tmp = nums[i];
27 | nums[i] = nums[j];
28 | nums[j] = tmp;
29 | }
30 |
31 | public static void main(String[] args) {
32 | int[] nums = {2, 5, 6, 4, 1, 3};
33 | partition(nums, 0, nums.length - 1, 4);
34 | System.out.println(Arrays.toString(nums));
35 |
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/array/ThreeSumSmaller.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.array;
2 |
3 | /**
4 | * Created by lipeng on 2016/1/24.
5 | */
6 | public class ThreeSumSmaller {
7 |
8 | public static int threeSumSmaller(int[] nums, int target) {
9 | int n = nums.length, ans = 0;
10 | for (int i = 0; i < n - 1; i++) {
11 | int left = i + 1, right = n - 1;
12 | while (left < right) {
13 | if (nums[i] + nums[left] + nums[right] < target)
14 | ans += right - (left++);
15 | else
16 | right--;
17 | }
18 | }
19 | return ans;
20 | }
21 |
22 | public static void main(String[] args) {
23 | int[] nums = {-2, 0, 1, 3};
24 | System.out.println(threeSumSmaller(nums, 2));
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/array/TwoWayPartition.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.array;
2 |
3 | /**
4 | * Created by lipeng on 2016/5/2.
5 | * Given an array and target. Partition array into left part less than target, right part equal to or greater than target.
6 | * In O(n) time.
7 | */
8 | public class TwoWayPartition {
9 |
10 | public static void twoWayPartition(int[] arr, int target) {
11 | if (arr == null || arr.length < 2) {
12 | return;
13 | }
14 | for (int i = -1, j = 0; j < arr.length; j++) {
15 | if (arr[j] < target) {
16 | int tmp = arr[i + 1];
17 | arr[i + 1] = arr[j];
18 | arr[j] = tmp;
19 | i++;
20 | }
21 | }
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/array/ValidPerfectSquare.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.array;
2 |
3 | /**
4 | * Created by lipeng on 2016/6/30.
5 | * https://leetcode.com/problems/valid-perfect-square/
6 | * If n is a valid perfect square, n = 1 + 3 + 5 + 7 + ...
7 | */
8 | public class ValidPerfectSquare {
9 |
10 | public boolean isPerfectSquare(int num) {
11 | int delta = 1;
12 | while (num > 0) {
13 | num -= delta;
14 | delta += 2;
15 | }
16 | return num == 0;
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/array/WaterJug.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.array;
2 |
3 | import java.math.BigInteger;
4 |
5 | /**
6 | * Created by lipeng on 2016/6/29.
7 | * https://leetcode.com/problems/water-and-jug-problem/
8 | */
9 | public class WaterJug {
10 |
11 | public static int gcd(int x, int y) {
12 | int diff = Math.abs(x - y);
13 | if (diff == 0) {
14 | return x;
15 | }
16 | else {
17 | return gcd(diff, Math.min(x, y));
18 | }
19 | }
20 |
21 | public static boolean canMeasureWater(int x, int y, int z) {
22 | if (x + y < z) {
23 | return false;
24 | }
25 | if (x == z || y == z) {
26 | return true;
27 | }
28 | return gcd(x, y) == 0;
29 | }
30 | public static void main(String[] args) {
31 | System.out.println(canMeasureWater(0, 2, 1));
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/divideandconquer/PointList.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.divideandconquer;
2 |
3 | /**
4 | * Created by lipeng on 2015/6/20.
5 | */
6 | public class PointList {
7 | public int x,y;
8 | public PointList next;
9 | public PointList(int x, int y){
10 | this.x = x;
11 | this.y = y;
12 | }
13 | public String toString(){
14 | if(this.next!=null){
15 | return "(" + x + "," + y + "), " + this.next.toString();
16 | }
17 | else {
18 | return "(" + x + "," + y + ")\r\n";
19 | }
20 | }
21 | }
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/dp/DistinctSubsequence.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.dp;
2 |
3 | /**
4 | * Created by lipeng on 2016/7/7.
5 | */
6 | public class DistinctSubsequence {
7 |
8 | public static int numDistinct(String S, String T) {
9 | int rowNum = T.length() + 1, colNum = S.length() + 1;
10 | int[][] dp = new int[rowNum][colNum];
11 | for (int i = 0; i < colNum; i++) {
12 | dp[0][i] = 1;
13 | }
14 | for (int row = 1; row < rowNum; row++) {
15 | for (int col = 1; col < colNum; col++) {
16 | dp[row][col] = dp[row][col - 1] + (S.charAt(col - 1) == T.charAt(row - 1) ? dp[row - 1][col - 1] : 0);
17 | }
18 | }
19 | return dp[rowNum - 1][colNum - 1];
20 | }
21 |
22 |
23 | public static void main(String[] args) {
24 | System.out.println(numDistinct("acdabefbc", "abec"));
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/dp/SumOfSet.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.dp;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Arrays;
5 | import java.util.HashSet;
6 |
7 | /**
8 | * Created by lipeng on 2015/12/2.
9 | */
10 | public class SumOfSet {
11 |
12 | /*
13 | Given a integer array, and a number n. Return true if n can be consisted by a subset of array.
14 | For example, arr[]={3, 2, 3, 5}, n=11, return true; arr[]={3, 2, 3, 5}, n=12, return false
15 |
16 | */
17 | public static boolean SumOfSet(int[] arr, int n) {
18 | assert arr!=null && arr.length>0;
19 | HashSet hs = new HashSet();
20 | for(int i:arr) {
21 | HashSet tmp = new HashSet();
22 | for(int j:hs)
23 | tmp.add(i+j);
24 | hs.addAll(tmp);
25 | hs.add(i);
26 | }
27 | return hs.contains(n);
28 | }
29 |
30 | public static void main(String[] args) {
31 | int[] arr = {3, 2, 3, 5};
32 | System.out.println(SumOfSet(arr, 12));
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/encode/Base62.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/allenlipeng47/algorithm/b62ab81f6f9d3ebd5db09093d5e4e8abd1e336a3/src/main/java/com/pli/project/algorithm/encode/Base62.java
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/exercise2014/AddLinkedList.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.exercise2014;
2 |
3 | public class AddLinkedList {
4 |
5 | public static void main(String[] args) {
6 | LinkList l = new LinkList(1);
7 | l.addToEnd(2);
8 | l.addToEnd(3);
9 | System.out.println();
10 | }
11 |
12 | public static void addToEnd(LinkList list, int value){
13 | if(list.next==null){
14 | list.next = new LinkList(value);
15 | return;
16 | }
17 | addToEnd(list.next, value);
18 | }
19 |
20 | }
21 |
22 | class LinkList{
23 | int value;
24 | public LinkList next;
25 | public LinkList(int value){
26 | this.value = value;
27 | }
28 |
29 | public void addToEnd(int value){
30 | if(this.next==null){
31 | this.next = new LinkList(value);
32 | return;
33 | }
34 | this.next.addToEnd(value);
35 | }
36 |
37 | }
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/exercise2014/BuildSumTree.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/allenlipeng47/algorithm/b62ab81f6f9d3ebd5db09093d5e4e8abd1e336a3/src/main/java/com/pli/project/algorithm/exercise2014/BuildSumTree.java
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/exercise2014/ConstructBSTPreOrder.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.exercise2014;
2 |
3 | import com.pli.project.algorithm.util.MyInteger;
4 | import com.pli.project.algorithm.util.Tree;
5 |
6 |
7 | public class ConstructBSTPreOrder {
8 |
9 | public static void main(String[] args) {
10 | int[] array = {4,3,1,2,7,5,8};
11 | MyInteger pos = new MyInteger(0);
12 | Tree tree = constructBSTByPreOrder(array, pos, Integer.MIN_VALUE, Integer.MAX_VALUE);
13 | System.out.println(tree);
14 | }
15 |
16 | public static Tree constructBSTByPreOrder(int[] array, MyInteger pos, int min, int max){
17 | if(array==null||pos.i>=array.length){
18 | return null;
19 | }
20 | if(array[pos.i]max){
21 | return null;
22 | }
23 | Tree tree = new Tree(array[pos.i]);
24 | pos.i++;
25 | tree.left = constructBSTByPreOrder(array, pos, min, tree.value);
26 | tree.right = constructBSTByPreOrder(array, pos, tree.value, max);
27 | return tree;
28 | }
29 |
30 |
31 | }
32 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/exercise2014/DynamicPlan.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/allenlipeng47/algorithm/b62ab81f6f9d3ebd5db09093d5e4e8abd1e336a3/src/main/java/com/pli/project/algorithm/exercise2014/DynamicPlan.java
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/exercise2014/FindKthInSortedArray.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/allenlipeng47/algorithm/b62ab81f6f9d3ebd5db09093d5e4e8abd1e336a3/src/main/java/com/pli/project/algorithm/exercise2014/FindKthInSortedArray.java
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/exercise2014/FindLargestBST.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/allenlipeng47/algorithm/b62ab81f6f9d3ebd5db09093d5e4e8abd1e336a3/src/main/java/com/pli/project/algorithm/exercise2014/FindLargestBST.java
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/exercise2014/FindWeightedMedianInMatrix.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.exercise2014;
2 |
3 | public class FindWeightedMedianInMatrix {
4 |
5 |
6 | public static void main(String[] args){
7 | int[][] array = {
8 | {0, 4, 0, 0},
9 | {0, 0, 0, 3},
10 | {1, 0, 0, 0},
11 | {1, 0, 5, 0},
12 | {5, 0, 0, 0},
13 | };
14 | int[][] element = {
15 | {0, 1, 4},
16 | {1, 3, 3},
17 | {2, 0, 1},
18 | {3, 0, 1},
19 | {3, 2, 5},
20 | {4, 0, 5},
21 | };
22 | int[][] vote = new int[array.length][array[0].length];
23 | for(int i=0; ip2.y?p2:p1;
18 | int length = Math.abs(p1.y - p2.y) + 1;
19 | int width = Math.abs(p1.x - p2.x) + 1;
20 | int section = length / width;
21 | // int last_sec =
22 | if(p_start.x<=p_end.x){
23 | //from left to right
24 | for(int i=p_start.y;iarray[i]){
25 | swap(array, i-1, i);
26 | }
27 | if(in)
23 | return;
24 | System.out.println(value);
25 | for(int i=0;i<10;i++){
26 | printRec(str+i, n);
27 | }
28 | }
29 |
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/exercise2014/TopK.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/allenlipeng47/algorithm/b62ab81f6f9d3ebd5db09093d5e4e8abd1e336a3/src/main/java/com/pli/project/algorithm/exercise2014/TopK.java
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/exercise2014/VerticallyPrintBiTree.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/allenlipeng47/algorithm/b62ab81f6f9d3ebd5db09093d5e4e8abd1e336a3/src/main/java/com/pli/project/algorithm/exercise2014/VerticallyPrintBiTree.java
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/exercise2014/WiselyPrintArray.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/allenlipeng47/algorithm/b62ab81f6f9d3ebd5db09093d5e4e8abd1e336a3/src/main/java/com/pli/project/algorithm/exercise2014/WiselyPrintArray.java
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/exercise2018/MatrixTransponse.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.exercise2018;
2 |
3 | import java.util.Arrays;
4 |
5 | public class MatrixTransponse {
6 |
7 | public static int[][] transposeMatrix(int[][] matrix) {
8 | if (matrix == null || matrix[0].length == 0) {
9 | return matrix;
10 | }
11 | for (int delta = 1; delta < matrix.length; delta++) {
12 | for (int i = 0; i < matrix.length - delta; i++) {
13 | int tmp = matrix[i][i + delta];
14 | matrix[i][i + delta] = matrix[i + delta][i];
15 | matrix[i + delta][i] = tmp;
16 | }
17 | }
18 | return matrix;
19 | }
20 |
21 | public static void main(String[] args) {
22 | int[][] matrix = {
23 | {1, 2, 3},
24 | {4, 5, 6},
25 | {7, 8, 9},
26 | };
27 | System.out.println(Arrays.deepToString(transposeMatrix(matrix)));
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/exercise2018/QueryManager.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.exercise2018;
2 |
3 | public class QueryManager {
4 | }
5 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/exercise2018/querymanager/QueryManger.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.exercise2018.querymanager;
2 |
3 | import com.pli.project.algorithm.exercise2018.querymanager.exception.CyclicRelationFoundException;
4 | import com.pli.project.algorithm.exercise2018.querymanager.exception.EmployeeNotFoundException;
5 |
6 | public interface QueryManger {
7 | public void setManger(int manager, int employee) throws CyclicRelationFoundException;
8 | public void setPeer(int managerFrom, int target) throws CyclicRelationFoundException, EmployeeNotFoundException;
9 | public boolean queryManager(int manager, int employee);
10 | }
11 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/exercise2018/querymanager/exception/CyclicRelationFoundException.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.exercise2018.querymanager.exception;
2 |
3 | public class CyclicRelationFoundException extends Exception {
4 | public CyclicRelationFoundException(String message) {
5 | super(message);
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/exercise2018/querymanager/exception/EmployeeNotFoundException.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.exercise2018.querymanager.exception;
2 |
3 | public class EmployeeNotFoundException extends Exception {
4 | public EmployeeNotFoundException(String message) {
5 | super(message);
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/gcd/BulkSwitch.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.gcd;
2 |
3 | import java.util.HashSet;
4 |
5 | /**
6 | * Created by lipeng on 2016/1/3.
7 | *
8 | */
9 | public class BulkSwitch {
10 |
11 | public static int bulbSwitch(int n) {
12 | int ans = 0;
13 | for(int i = 1; i * i <= n; i++)
14 | ans++;
15 | return ans;
16 | }
17 |
18 | public static void main(String[] args) {
19 | // System.out.println(bulbSwitch(99999));
20 | System.out.println(bulbSwitch(4));
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/graph/CycleDetect.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.graph;
2 |
3 | /**
4 | * Created by lipeng on 2015/11/30.
5 | */
6 | public class CycleDetect {
7 | }
8 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/hash/rollinghash/ExtendedEuclid.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.hash.rollinghash;
2 |
3 | /**
4 | * Created by lipeng on 2015/5/16.
5 | */
6 | public class ExtendedEuclid {
7 | // return array [d, a, b] such that d = gcd(p, q), ap + bq = d
8 | static int[] gcd(int p, int q) {
9 | if (q == 0)
10 | return new int[] { p, 1, 0 };
11 |
12 | int[] vals = gcd(q, p % q);
13 | int d = vals[0];
14 | int a = vals[2];
15 | int b = vals[1] - (p / q) * vals[2];
16 | return new int[] { d, a, b };
17 | }
18 |
19 | public static void main(String[] args) {
20 | int p = Integer.parseInt(args[0]);
21 | int q = Integer.parseInt(args[1]);
22 | int vals[] = gcd(p, q);
23 | System.out.println("gcd(" + p + ", " + q + ") = " + vals[0]);
24 | System.out.println(vals[1] + "(" + p + ") + " + vals[2] + "(" + q + ") = " + vals[0]);
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/BstIterator.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | import com.pli.project.algorithm.util.TreeNode;
4 |
5 | import java.util.Stack;
6 |
7 | /**
8 | * Created by lipeng on 2016/4/16.
9 | */
10 | public class BstIterator {
11 |
12 | Stack s;
13 |
14 | public BstIterator(TreeNode root) {
15 | s = new Stack<>();
16 | loadLeft(root);
17 | }
18 |
19 | private void loadLeft(TreeNode root) {
20 | while (root != null) {
21 | s.add(root);
22 | root = root.left;
23 | }
24 | }
25 |
26 | /** @return whether we have a next smallest number */
27 | public boolean hasNext() {
28 | return !s.isEmpty();
29 | }
30 |
31 | /** @return the next smallest number */
32 | public int next() {
33 | TreeNode curr = s.pop();
34 | loadLeft(curr.right);
35 | return curr.val;
36 | }
37 | }
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/ContainDuplicate.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | import java.util.HashSet;
4 |
5 | /**
6 | * Created by lipeng on 2016/3/23.
7 | */
8 | public class ContainDuplicate {
9 |
10 | public boolean containsDuplicate(int[] nums) {
11 | if (nums == null || nums.length <= 1) {
12 | return false;
13 | }
14 | HashSet hs = new HashSet<>();
15 | for (int i : nums) {
16 | if (hs.contains(i)) {
17 | return true;
18 | }
19 | hs.add(i);
20 | }
21 | return false;
22 | }
23 |
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/CountNumberWithUniqueDigit.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/6/15.
5 | * https://leetcode.com/problems/count-numbers-with-unique-digits/
6 | */
7 | public class CountNumberWithUniqueDigit {
8 |
9 | public static int countNumbersWithUniqueDigits(int n) {
10 | if (n == 0) {
11 | return 1;
12 | }
13 | int ans = 10, base = 9;
14 | for (int i = 2; i <= n && i <= 10; i++) {
15 | base = base * (9 - i + 2);
16 | ans += base;
17 | }
18 | return ans;
19 | }
20 |
21 | public static void main(String[] args) {
22 | System.out.println(countNumbersWithUniqueDigits(2));
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/ExcelSheet.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/4/18.
5 | */
6 | public class ExcelSheet {
7 |
8 | public static String convertToTitle(int n) {
9 | StringBuffer ans = new StringBuffer();
10 | while (n > 0) {
11 | n--;
12 | int remaining = n % 26;
13 | ans.insert(0, (char)('A' + remaining));
14 | n /= 26;
15 | }
16 | return ans.toString();
17 | }
18 |
19 | public static void main(String[] args) {
20 | System.out.println(convertToTitle(26));
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/ExcelSheetStrToNum.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/4/18.
5 | * https://leetcode.com/problems/excel-sheet-column-number/
6 | * From string to number, calculate from left to right.
7 | */
8 | public class ExcelSheetStrToNum {
9 |
10 | public static int titleToNumber(String s) {
11 | int len = s.length(), ans = 0;
12 | for (int i = 0; i < len; i++) {
13 | char ch = s.charAt(i);
14 | ans = ans * 26 + (ch - 'A' + 1);
15 | }
16 | return ans;
17 | }
18 |
19 | public static void main(String[] args) {
20 | String str = "AB";
21 | System.out.println(titleToNumber(str));
22 | }
23 |
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/FindPeakElement.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/4/21.
5 | * https://leetcode.com/problems/find-peak-element/
6 | */
7 | public class FindPeakElement {
8 |
9 | public static int findPeakElement(int[] nums) {
10 | int left = 0, right = nums.length - 1;
11 | while (left < right) {
12 | int mid = left + (right - left) / 2;
13 | if (nums[mid] < nums[mid - 1]) {
14 | right = mid - 1;
15 | }
16 | else if (nums[mid] < nums[mid + 1]) {
17 | left = mid + 1;
18 | }
19 | else {
20 | return nums[mid];
21 | }
22 | }
23 | return nums[left];
24 | }
25 |
26 | public static void main(String[] args) {
27 | int[] nums = {4, 3, 2, 1};
28 | System.out.println(findPeakElement(nums));
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/LinkedListCycleII.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/7/14.
5 | */
6 | public class LinkedListCycleII {
7 |
8 | public ListNode detectCycle(ListNode head) {
9 | ListNode slow = head, fast = head;
10 | while (true) {
11 | if (fast == null || fast.next == null) {
12 | return null;
13 | }
14 | slow = slow.next;
15 | fast = fast.next.next;
16 | if (slow == fast) {
17 | break;
18 | }
19 | }
20 | while (head != fast) {
21 | head = head.next;
22 | fast = fast.next;
23 | }
24 | return head;
25 | }
26 |
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/ListNode.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/7/13.
5 | */
6 | public class ListNode {
7 | public int val;
8 | public ListNode next;
9 | public ListNode(int x) { val = x; }
10 | public String toString() {
11 | if (next == null) {
12 | return String.valueOf(val);
13 | }
14 | else {
15 | return String.valueOf(val) + "->" + next;
16 | }
17 | }
18 | }
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/LongestStrAtMostKDistinctChar.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | import java.util.HashMap;
4 |
5 | /**
6 | * Created by lipeng on 2016/4/4.
7 | * http://cherylintcode.blogspot.com/2015/07/longest-substring-with-at-most-k.html
8 | */
9 | public class LongestStrAtMostKDistinctChar {
10 |
11 | public int longestStrKDistinct(String str, int k) {
12 | int[] rec = new int[256];
13 | int len = str.length(), ans = 0, num = 0;
14 | for (int left = 0, right = 0; right < len; right++) {
15 | char ch = str.charAt(right);
16 | if (rec[ch - 'a'] == 0) {
17 | num++;
18 | }
19 | rec[ch - 'a']++;
20 | while (num > k) {
21 | ch = str.charAt(left++);
22 | if (--rec[ch - 'a'] == 0) {
23 | num--;
24 | }
25 | }
26 | ans = Math.max(ans, right - left + 1);
27 | }
28 | return ans;
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/MinSizeSumArray.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/3/25.
5 | */
6 | public class MinSizeSumArray {
7 |
8 | public int minSubArrayLen(int s, int[] nums) {
9 | int i = 0, j = 0, ans = Integer.MAX_VALUE, sum = 0;
10 | while (j <= nums.length) {
11 | if (sum >= s) {
12 | ans = Math.min(ans, j - i);
13 | sum -= nums[i++];
14 | }
15 | else if (j < nums.length){
16 | sum += nums[j++];
17 | }
18 | else {
19 | j++;
20 | }
21 | }
22 | return ans == Integer.MAX_VALUE ? 0 : ans;
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/MissingNumber.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2015/9/1.
5 | */
6 | public class MissingNumber {
7 | public static int missingNumber(int[] nums) {
8 | if(nums==null){
9 | return -1;
10 | }
11 | int sum = (nums.length + 1) * (nums.length) / 2;
12 | for(int i=0; i getList();
21 | }
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/NextPermutation.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/9/8.
5 | */
6 | public class NextPermutation {
7 |
8 | public void nextPermutation(int[] nums) {
9 | int smallPos = nums.length - 2;
10 | while (smallPos >= 0 && nums[smallPos] >= nums[smallPos + 1]) {
11 | smallPos--;
12 | }
13 | int bigPos = nums.length - 1;
14 | while (bigPos > smallPos && nums[bigPos] <= nums[smallPos]) {
15 | bigPos--;
16 | }
17 | for (bigPos = nums.length - 1; bigPos < smallPos; bigPos--) {
18 | if (nums[bigPos] > nums[smallPos]) {
19 | break;
20 | }
21 | }
22 |
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/NumberOf1Bit.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/4/10.
5 | */
6 | public class NumberOf1Bit {
7 |
8 | // you need to treat n as an unsigned value
9 | public int hammingWeight(int n) {
10 | int ans = 0;
11 | while (n != 0) {
12 | n = n & (n - 1);
13 | ans++;
14 | }
15 | return ans;
16 | }
17 |
18 | public int hammingWeight2(int n) {
19 | int count = 0;
20 | for (;n!=0;n = n & (n-1))
21 | count++;
22 | return count;
23 | }
24 |
25 | public static void main(String[] args) {
26 | // NumberOf1Bit n = new NumberOf1Bit();
27 | // System.out.println(n.hammingWeight(-6));
28 | System.out.println(-6 >>> 4);
29 | }
30 |
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/NumberOfTrailingZeros.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/4/16.
5 | * https://leetcode.com/problems/factorial-trailing-zeroes/
6 | * We can know that 0 only happens when there is factor 5 and factor 2. Because factor 2 is ample.
7 | * So we count how many factor 5 there is from 1, 2, 3, ... , n
8 | * If n = 5. 1, 2, 3, 4, 5. there is 1 five.
9 | * If n = 11. 1, 2, 3, 4, 5, 6, 7, 8, 9, 10(5 * 3), 11. there are 2 five
10 | * If n = 25. 1, 2, 3, 4, 5, 6, 7, 8, 9, 10(5 * 2), 11, 12, 13, 14, 15(5 * 3), 16, 17, 18, 19, 20(5 * 4), 21, 22, 23, 24, 25(5 * 5).
11 | * There are 6 fives.
12 | */
13 | public class NumberOfTrailingZeros {
14 |
15 | public int trailingZeroes(int n) {
16 | return n <= 0 ? 0 : n / 5 + trailingZeroes(n / 5);
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/OddEvenList2.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/4/30.
5 | */
6 | public class OddEvenList2 {
7 |
8 | public class ListNode {
9 | int val;
10 | ListNode next;
11 | ListNode(int x) { val = x; }
12 | }
13 |
14 | public static ListNode oddEvenList(ListNode head) {
15 | if (head == null || head.next == null) {
16 | return head;
17 | }
18 | ListNode odd = head, even = head.next;
19 | while (even.next != null) {
20 | ListNode nextCurr = even.next.next;
21 | even.next.next = odd.next;
22 | odd.next = even.next;
23 | even.next = nextCurr;
24 | if (nextCurr == null) {
25 | break;
26 | }
27 | odd = odd.next;
28 | even = nextCurr;
29 | }
30 | return head;
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/PalindromeNumber.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/7/5.
5 | * https://leetcode.com/problems/palindrome-number/
6 | * The solution is to move the lower part to another number sum, and shrink x. After moved half, compare sum and x.
7 | */
8 | public class PalindromeNumber {
9 |
10 | public static boolean isPalindrome(int x) {
11 | if (x < 0 || x != 0 && x % 10 == 0) { // any number like 10, 20, 1210 are not palindrome number.
12 | return false;
13 | }
14 | int sum = 0;
15 | while (sum < x) {
16 | sum = sum * 10 + x % 10;
17 | x /= 10;
18 | }
19 | return x == sum || x == sum / 10;
20 | }
21 |
22 | public static void main(String[] args) {
23 | System.out.println(isPalindrome(10));
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/PowXN.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/8/12.
5 | * https://leetcode.com/problems/powx-n/
6 | */
7 | public class PowXN {
8 |
9 | public double myPow(double x, int n) {
10 | long logN = Math.abs((long)n); // use long type, in case an input is pow(2, -2147483648). n is greater than MaxInt
11 | double ans = 1;
12 | while (logN > 0) {
13 | if ((logN & 1) == 1) {
14 | ans = ans * x;
15 | }
16 | x = x * x;
17 | logN = logN >> 1;
18 | }
19 | return n > 0 ? ans : 1 / ans;
20 | }
21 |
22 |
23 | }
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/PowerOf4.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/4/18.
5 | */
6 | public class PowerOf4 {
7 |
8 | public static boolean isPowerOfFour(int num) {
9 | return (num & (num - 1)) == 0 && (num & 0x55555555) != 0;
10 | }
11 |
12 | public static void main(String[] args) {
13 | System.out.println(isPowerOfFour(1));
14 |
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/RangeBitWiseAnd.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/4/10.
5 | */
6 | public class RangeBitWiseAnd {
7 |
8 | public int rangeBitwiseAnd(int m, int n) {
9 | int move = 0;
10 | while (m != n) {
11 | m = m >> 1;
12 | n = n >> 1;
13 | move++;
14 | }
15 | return m << move;
16 | }
17 |
18 | public static void main(String[] args) {
19 |
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/RemoveLInkedListElement.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/4/6.
5 | */
6 | public class RemoveLInkedListElement {
7 |
8 | public class ListNode {
9 | int val;
10 | ListNode next;
11 | ListNode(int x) { val = x;}
12 | }
13 |
14 | public ListNode removeElements(ListNode head, int val) {
15 | ListNode dummyHead = new ListNode(0), pre = dummyHead;
16 | dummyHead.next = head;
17 | while (head != null) {
18 | if (head.val == val) {
19 | pre.next = head.next;
20 | }
21 | else {
22 | pre = head;
23 | }
24 | head = head.next;
25 | }
26 | return dummyHead.next;
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/ReverseLinkList.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/3/25.
5 | */
6 | public class ReverseLinkList {
7 |
8 | public class ListNode {
9 | int val;
10 | ListNode next;
11 | ListNode(int x) { val = x; }
12 | }
13 |
14 | public ListNode reverseList(ListNode head) {
15 | ListNode pre = null;
16 | while (head != null) {
17 | ListNode next = head.next;
18 | head.next = pre;
19 | head = next;
20 | }
21 | return pre;
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/SingleNumberII.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * https://leetcode.com/problems/single-number-ii/
5 | * Added the solution. For each bit in the nums, count the sum of 1. If sum % 3 == 0, it means this bit is 0, or this bit should be 1
6 | */
7 | public class SingleNumberII {
8 |
9 | public static int singleNumber(int[] nums) {
10 | int ans = 0;
11 | for (int i = 0; i < 32; i++) {
12 | int sum = 0, bit = 1 << i, base = 1 << i;
13 | for (int j = 0; j < nums.length; j++) {
14 | if ((nums[j] & bit) != 0) {
15 | sum++;
16 | }
17 | }
18 | if (sum % 3 != 0) {
19 | ans = ans | base;
20 | }
21 | }
22 | return ans;
23 | }
24 |
25 | public static void main(String[] args) {
26 | int[] A = {1, 0, 1, 0, 1, 0};
27 | System.out.println(singleNumber(A));
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/SumOfTwoIntegers.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/7/1.
5 | * https://leetcode.com/problems/sum-of-two-integers/
6 | */
7 | public class SumOfTwoIntegers {
8 |
9 |
10 | public static int getSum(int a, int b) {
11 | /*
12 | sum = a ^ b
13 | carrier = (a & b) << 1
14 | */
15 | while (b != 0) {
16 | int sum = a ^ b; // to get the current sum
17 | b = (a & b) << 1; // to get the carrier
18 | a = sum;
19 | }
20 | return a;
21 | }
22 |
23 | public static void main(String[] args) {
24 | System.out.println(getSum(5, -7));
25 |
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/TreeNode.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/7/13.
5 | */
6 | public class TreeNode {
7 | public int val;
8 | public TreeNode left;
9 | public TreeNode right;
10 | public TreeNode(int x) { val = x; }
11 | }
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/VerifyPreorderSerialization.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/4/30.
5 | */
6 | public class VerifyPreorderSerialization {
7 |
8 | public static boolean isValidSerialization(String preorder) {
9 | String[] str = preorder.split(",");
10 | int n = 1;
11 | for (int i = 0; i < str.length; i++) {
12 | if (--n < 0) {
13 | return false;
14 | }
15 | if (!str[i].equals("#")) {
16 | n += 2;
17 | }
18 | }
19 | return n == 0;
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/WordBreak.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | import java.util.Set;
4 |
5 | /**
6 | * Created by lipeng on 2016/7/18.
7 | */
8 | public class WordBreak {
9 |
10 | public boolean wordBreak(String s, Set wordDict) {
11 | s = " " + s;
12 | boolean[] mem = new boolean[s.length()];
13 | int len = mem.length;
14 | mem[0] = true;
15 | for (int i = 1; i < len; i++) {
16 | if (mem[i - 1]) {
17 | for (String word : wordDict) {
18 | if (i + word.length() <= len && s.substring(i, i + word.length()).equals(word)) {
19 | mem[i + word.length() - 1] = true;
20 | }
21 | }
22 | }
23 | }
24 | return mem[len - 1];
25 | }
26 |
27 |
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/l100SameTree.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/7/27.
5 | */
6 | public class l100SameTree {
7 |
8 | public boolean isSameTree(TreeNode p, TreeNode q) {
9 | if (p == null && q == null) {
10 | return true;
11 | }
12 | if (p == null || q == null) {
13 | return false;
14 | }
15 | return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
16 | }
17 |
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/l104MaxDeptBst.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/7/27.
5 | * https://leetcode.com/problems/maximum-depth-of-binary-tree/
6 | */
7 | public class l104MaxDeptBst {
8 |
9 | public int maxDepth(TreeNode root) {
10 | if (root == null) {
11 | return 0;
12 | }
13 | return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
14 | }
15 |
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/l110BalancedBst.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/7/26.
5 | * https://leetcode.com/problems/balanced-binary-tree/
6 | */
7 | public class l110BalancedBst {
8 |
9 | public boolean isBalanced(TreeNode root) {
10 | return helper(root) >= 0 ? true : false;
11 | }
12 |
13 | // if it is balanced, return height. Or return -1
14 | private int helper(TreeNode root) {
15 | if (root == null) {
16 | return 0;
17 | }
18 | int leftHeight = helper(root.left);
19 | if (leftHeight < 0) {
20 | return -1;
21 | }
22 | int rightHeight = helper(root.right);
23 | if (rightHeight < 0) {
24 | return -1;
25 | }
26 | if (Math.abs(leftHeight - rightHeight) <= 1) {
27 | return Math.max(leftHeight, rightHeight) + 1;
28 | }
29 | return -1;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/l111MinimumDepthBst.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/7/26.
5 | * https://leetcode.com/problems/minimum-depth-of-binary-tree/
6 | * Solutin is to traverse all the leaf node. When reach a leaf node, update ans with the currDept
7 | */
8 | public class l111MinimumDepthBst {
9 |
10 | private int ans = Integer.MAX_VALUE;
11 |
12 | public int minDepth(TreeNode root) {
13 | int[] ans = new int[1];
14 | ans[0] = Integer.MAX_VALUE;
15 | helper(root, 1, ans);
16 | return ans[0] == Integer.MAX_VALUE ? 0 : ans[0];
17 | }
18 |
19 | private void helper(TreeNode root, int currDepth, int[] ans) {
20 | if (root == null) {
21 | return;
22 | }
23 | if (root.left == null && root.right == null) {
24 | ans[0] = Math.min(ans[0], currDepth);
25 | }
26 | helper(root.left, currDepth + 1, ans);
27 | helper(root.right, currDepth + 1, ans);
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/l112SumPath.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * Created by lipeng on 2016/7/26.
8 | * https://leetcode.com/problems/path-sum/
9 | */
10 | public class l112SumPath {
11 |
12 | public boolean hasPathSum(TreeNode root, int sum) {
13 | if (root == null) {
14 | return false;
15 | }
16 | sum -= root.val;
17 | if (root.left == null && root.right == null && sum == 0) {
18 | return true;
19 | }
20 | return hasPathSum(root.left, sum) || hasPathSum(root.right, sum);
21 | }
22 |
23 |
24 |
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/l129SumRootToLeafNumbers.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/7/24.
5 | */
6 | public class l129SumRootToLeafNumbers {
7 |
8 | public static int sumNumbers(TreeNode root) {
9 | int[] ans = new int[1];
10 | helper(root, 0, ans);
11 | return ans[0];
12 | }
13 |
14 | private static void helper(TreeNode root, int curr, int[] total) {
15 | if (root == null) {
16 | return;
17 | }
18 | curr = curr * 10 + root.val;
19 | if (root.left == null && root.right == null) {
20 | total[0] += curr;
21 | }
22 | helper(root.left, curr, total);
23 | helper(root.right, curr, total);
24 | }
25 |
26 | public static void main(String[] args) {
27 |
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/l134GasStation.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/7/21.
5 | * https://leetcode.com/problems/gas-station/
6 | */
7 | public class l134GasStation {
8 |
9 | public int canCompleteCircuit(int[] gas, int[] cost) {
10 | // test see if there is a result.
11 | int total = 0;
12 | for (int i = 0; i < gas.length; i++) {
13 | total += gas[i] - cost[i];
14 | }
15 | if (total < 0) {
16 | return -1;
17 | }
18 | // calculate the aggregation until we find a position which the aggregation from it to the end is greater than or equal to 0
19 | int aggr = 0, ans = 0;
20 | for (int i = 0; i < gas.length; i++) {
21 | aggr += gas[i] - cost[i];
22 | if (aggr < 0) {
23 | ans = i + 1;
24 | aggr = 0;
25 | }
26 | }
27 | return ans;
28 | }
29 |
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/l19RemoveNthNodeFromList.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/9/1.
5 | * https://leetcode.com/problems/remove-nth-node-from-end-of-list/
6 | */
7 | public class l19RemoveNthNodeFromList {
8 |
9 | public ListNode removeNthFromEnd(ListNode head, int n) {
10 | ListNode dummy = new ListNode(0), fast = dummy, slow = dummy;
11 | dummy.next = head;
12 | for (int i = 0; i <= n; i++) {
13 | fast = fast.next;
14 | }
15 | while (fast != null) {
16 | fast = fast.next;
17 | slow = slow.next;
18 | }
19 | if (slow.next != null) {
20 | slow.next = slow.next.next;
21 | }
22 | return dummy.next;
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/l1TwoSum.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | import java.util.Arrays;
4 | import java.util.HashMap;
5 | import java.util.Map;
6 |
7 | /**
8 | * Created by lipeng on 2016/7/24.
9 | * https://leetcode.com/problems/two-sum/
10 | */
11 | public class l1TwoSum {
12 |
13 | public static int[] twoSum(int[] nums, int target) {
14 | Map hm = new HashMap<>();
15 | for (int i = 0; i < nums.length; i++) {
16 | if (hm.containsKey(target - nums[i])) {
17 | return new int[] {hm.get(target - nums[i]), i};
18 | }
19 | hm.put(nums[i], i);
20 | }
21 | return null;
22 | }
23 |
24 | public static void main(String[] args) {
25 | int[] nums = {2, 7, 11, 15};
26 | System.out.println(Arrays.toString(twoSum(nums, 9)));
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/l205IsomorphicString.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/9/1.
5 | * https://leetcode.com/problems/isomorphic-strings/
6 | * The idea is to record the position of the element.
7 | * When the position of 2 elements are not equal, then return false.
8 | * Each loop, update the current position.
9 | */
10 | public class l205IsomorphicString {
11 |
12 | public boolean isIsomorphic(String s, String t) {
13 | int[] pos = new int[512];
14 | for (int i = 0; i < s.length(); i++) {
15 | if (pos[s.charAt(i)] != pos[t.charAt(i) + 256]) {
16 | return false;
17 | }
18 | pos[s.charAt(i)] = pos[t.charAt(i)] = i + 1;
19 | }
20 | return true;
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/l27RemoveElements.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/9/1.
5 | * https://leetcode.com/problems/remove-element/
6 | */
7 | public class l27RemoveElements {
8 |
9 | public int removeElement(int[] nums, int val) {
10 | int left = 0;
11 | for (int right = 0; right < nums.length; right++) {
12 | if (nums[right] != val) {
13 | nums[left] = nums[right];
14 | left++;
15 | }
16 | }
17 | return left;
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/l374GuessNumber.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/8/31.
5 | * https://leetcode.com/problems/guess-number-higher-or-lower/
6 | */
7 | public class l374GuessNumber {
8 |
9 | public int guessNumber(int n) {
10 | int left = 1, right = n;
11 | while (left < right) {
12 | int mid = left + (right - left) / 2;
13 | int reply = guess(mid);
14 | if (reply == 0) {
15 | return mid;
16 | }
17 | else if (reply < 0) {
18 | right = mid - 1;
19 | }
20 | else {
21 | left = mid + 1;
22 | }
23 | }
24 | return left;
25 | }
26 |
27 | private int guess(int mid) {
28 | return 1;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/l383RansonNote.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | /**
7 | * Created by lipeng on 2016/8/29.
8 | * https://leetcode.com/problems/ransom-note/
9 | */
10 | public class l383RansonNote {
11 |
12 | public boolean canConstruct(String ransomNote, String magazine) {
13 | Map hm = new HashMap<>();
14 | for (char ch : ransomNote.toCharArray()) {
15 | int count = hm.getOrDefault(ch, 0);
16 | hm.put(ch, count + 1);
17 | }
18 | for (char ch : magazine.toCharArray()) {
19 | Integer count = hm.get(ch);
20 | if (count == null) {
21 | continue;
22 | }
23 | else if (count == 1) {
24 | hm.remove(ch);
25 | }
26 | else {
27 | hm.put(ch, count - 1);
28 | }
29 | }
30 | return hm.isEmpty();
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/l389LexicographicalNumber.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * Created by lipeng on 2016/8/31.
8 | * https://leetcode.com/problems/lexicographical-numbers/
9 | */
10 | public class l389LexicographicalNumber {
11 |
12 | public static List lexicalOrder(int n) {
13 | List ans = new ArrayList<>();
14 | for (int i = 1; i <= 9; i++) {
15 | dfs(i, n, ans);
16 | }
17 | return ans;
18 | }
19 |
20 | private static void dfs(int curr, int n, List ans) {
21 | if (curr > n) {
22 | return;
23 | }
24 | ans.add(curr);
25 | for (int i = 0; i <= 9; i++) {
26 | dfs(curr * 10 + i, n, ans);
27 | }
28 | }
29 |
30 | public static void main(String[] args) {
31 | System.out.println(lexicalOrder(40));
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/l49GroupAnagram.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Arrays;
5 | import java.util.HashMap;
6 | import java.util.List;
7 |
8 | /**
9 | * Created by lipeng on 2016/8/12.
10 | * https://leetcode.com/problems/anagrams/
11 | * The key idea is to store the sorted str as key.
12 | */
13 | public class l49GroupAnagram {
14 |
15 | public List> groupAnagrams(String[] strs) {
16 | HashMap> hm = new HashMap<>();
17 | for (String str : strs) {
18 | char[] chs = str.toCharArray();
19 | Arrays.sort(chs);
20 | String keyStr = String.valueOf(chs);
21 | List currList = hm.getOrDefault(keyStr, new ArrayList<>());
22 | currList.add(str);
23 | hm.put(keyStr, currList);
24 | }
25 | return new ArrayList(hm.values());
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/l83RemoveDuplicateFromSortedList.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/8/7.
5 | * https://leetcode.com/problems/remove-duplicates-from-sorted-list/
6 | */
7 | public class l83RemoveDuplicateFromSortedList {
8 |
9 | public ListNode deleteDuplicates(ListNode head) {
10 | ListNode curr = head;
11 | while (curr != null) {
12 | while (curr.next != null && curr.next.val == curr.val) {
13 | curr.next = curr.next.next;
14 | }
15 | curr = curr.next;
16 | }
17 | return head;
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/l96UniqueBst.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | /**
4 | * Created by lipeng on 2016/8/2.
5 | */
6 | public class l96UniqueBst {
7 |
8 | public int numTrees(int n) {
9 | int[] dp = new int[n + 1];
10 | dp[0] = 1;
11 | for (int i = 1; i < dp.length; i++) {
12 | for (int j = 1; j <= i; j++) {
13 | dp[i] += dp[j - 1] * dp[i - j];
14 | }
15 | }
16 | return dp[n];
17 | }
18 |
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/leetcode/test.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by lipeng on 2016/4/16.
3 | */
4 | console.log("abcd")
5 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/lintcode/NumberOfPlaneInSky.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.lintcode;
2 |
3 | import java.util.*;
4 |
5 | /**
6 | * Created by lipeng on 2016/9/7.
7 | */
8 | public class NumberOfPlaneInSky {
9 |
10 | public class Interval {
11 | int start, end;
12 |
13 | Interval(int start, int end) {
14 | this.start = start;
15 | this.end = end;
16 | }
17 | }
18 |
19 | public static int countOfAirplanes(List airplanes) {
20 | int ans = 0;
21 | Queue queue = new PriorityQueue();
22 | Collections.sort(airplanes, (a1, a2) -> a1.start - a2.start);
23 | for (Interval i : airplanes) {
24 | while (!queue.isEmpty() && i.start >= queue.peek()) {
25 | queue.poll();
26 | }
27 | queue.add(i.end);
28 | ans = Math.max(ans, queue.size());
29 | }
30 | return ans;
31 | }
32 |
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/ms/BalanceIndex.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.ms;
2 |
3 | /**
4 | * Created by lipeng on 2016/3/18.
5 | */
6 | public class BalanceIndex {
7 |
8 | public int findBalancePoint(int[] arr) {
9 | int lo = 0, hi = arr.length - 1, sumLeft = 0, sumRight = 0;
10 | while (lo < hi) {
11 | if (sumLeft < sumRight) {
12 | sumLeft += arr[lo++];
13 | }
14 | else {
15 | sumRight += arr[hi--];
16 | }
17 | }
18 | return lo;
19 | }
20 |
21 | public static void main(String[] args) {
22 | int[] arr = {1, 3, 2, 1};
23 | BalanceIndex balanceIndex = new BalanceIndex();
24 | System.out.println(balanceIndex.findBalancePoint(arr));
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/ms/BurstBalloon.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.ms;
2 |
3 | /**
4 | * Created by lipeng on 2016/3/20.
5 | */
6 | public class BurstBalloon {
7 |
8 |
9 |
10 | }
11 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/ms/CountingBit.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.ms;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * Created by lipeng on 2016/3/19.
7 | */
8 | public class CountingBit {
9 |
10 | public int[] countBits(int num) {
11 | num++;
12 | int[] ans = new int[num];
13 | for (int i = 1; i < num; i++) {
14 | ans[i] = ans[i & (i - 1)] + 1;
15 | }
16 | return ans;
17 | }
18 |
19 | public static void main(String[] args) {
20 | CountingBit count = new CountingBit();
21 | System.out.println(Arrays.toString(count.countBits(5)));
22 | }
23 |
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/ms/ExcelRowNumberToLabel.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.ms;
2 |
3 | import java.util.Stack;
4 |
5 | /**
6 | * Created by lipeng on 2016/3/18.
7 | */
8 | public class ExcelRowNumberToLabel {
9 |
10 | public String convertToTitle(int number) {
11 | StringBuffer sb = new StringBuffer();
12 | while (number > 0) {
13 | number--;
14 | sb.insert(0, (char)('A' + number % 26));
15 | number /= 26;
16 | }
17 | return sb.toString();
18 | }
19 |
20 | public int restoreNumber(String str) {
21 | int num = 0;
22 | for (int i = 0; i < str.length(); i++) {
23 | num = num * 26 + str.charAt(i) - 'A' + 1;
24 | }
25 | return num;
26 | }
27 |
28 | public static void main(String[] args) {
29 | ExcelRowNumberToLabel excel = new ExcelRowNumberToLabel();
30 | String label = excel.convertToTitle(27);
31 | System.out.println(label);
32 | System.out.println(excel.restoreNumber(label));
33 | }
34 |
35 |
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/ms/FindProduct.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.ms;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * Created by lipeng on 2016/3/18.
8 | */
9 | public class FindProduct {
10 |
11 | public List findProduct(int n) {
12 | int product = 2;
13 | List ans = new ArrayList<>();
14 | while (n > 1) {
15 | if (n % product == 0) {
16 | ans.add(product);
17 | n /= product;
18 | } else {
19 | product++;
20 | }
21 | }
22 | return ans;
23 | }
24 |
25 | public static void main(String[] args) {
26 | FindProduct findProduct = new FindProduct();
27 | System.out.println(findProduct.findProduct(101));
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/ms/HouseRobberI.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.ms;
2 |
3 | /**
4 | * Created by lipeng on 2016/3/17.
5 | */
6 | public class HouseRobberI {
7 |
8 | public int rob(int[] nums) {
9 | if (nums == null || nums.length < 1) {
10 | return 0;
11 | }
12 | int noRob = 0, rob = nums[0];
13 | for (int i = 1; i < nums.length; i++) {
14 | int newRob = nums[i] + noRob;
15 | noRob = Math.max(noRob, rob);
16 | rob = newRob;
17 | }
18 | return Math.max(rob, noRob);
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/ms/ImplementQueueByStack.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.ms;
2 |
3 | /**
4 | * Created by lipeng on 2016/3/17.
5 | */
6 | public class ImplementQueueByStack {
7 | }
8 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/ms/JumpGame.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.ms;
2 |
3 | /**
4 | * Created by lipeng on 2016/3/19.
5 | */
6 | public class JumpGame {
7 |
8 | public boolean canJump(int[] nums) {
9 | if (nums == null || nums.length <= 1) {
10 | return true;
11 | }
12 | int max = 0;
13 | for (int i = 0; i < nums.length && max >= i; i++) {
14 | max = Math.max(max, i + nums[i]);
15 | }
16 | return max >= nums.length - 1;
17 | }
18 |
19 | public static void main(String[] args) {
20 | JumpGame j = new JumpGame();
21 | int[] nums = {3, 2, 1, 0, 4};
22 | System.out.println(j.canJump(nums));
23 | }
24 |
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/ms/Lcs.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.ms;
2 |
3 | import com.pli.project.algorithm.util.TreeNode;
4 |
5 | /**
6 | * Created by lipeng on 2016/3/17.
7 | */
8 | public class Lcs {
9 |
10 | public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
11 | if (root == null || root == p || root == q) {
12 | return null;
13 | }
14 | TreeNode left = lowestCommonAncestor(root.left, p, q);
15 | TreeNode right = lowestCommonAncestor(root.right, p, q);
16 | if (left != null && right != null) {
17 | return root;
18 | }
19 | else if (left != null) {
20 | return left;
21 | }
22 | else {
23 | return right;
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/ms/PaintHouse.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.ms;
2 |
3 | /**
4 | * Created by lipeng on 2016/3/20.
5 | */
6 | public class PaintHouse {
7 |
8 | public static int getPaintCost(int[][] cost) {
9 | int r = 0, g = 0, b = 0;
10 | for (int i = 0; i < cost.length; i++) {
11 | int rr = 0, gg = 0, bb = 0;
12 | rr = cost[i][0] + Math.min(b, g);
13 | gg = cost[i][1] + Math.min(r, b);
14 | bb = cost[i][2] + Math.min(r, g);
15 | r = rr;
16 | b = bb;
17 | g = gg;
18 | }
19 | return Math.min(Math.min(r, g), b);
20 | }
21 |
22 | public static void main(String[] args) {
23 | int[][] cost = {
24 | {1, 2, 3},
25 | {3, 2, 1},
26 | {1, 2, 2},
27 | {2, 2, 1}
28 | };
29 | System.out.println(getPaintCost(cost));
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/ms/RotateArray.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.ms;
2 |
3 | /**
4 | * Created by lipeng on 2016/3/17.
5 | */
6 | public class RotateArray {
7 |
8 | public void rotate(int[] nums, int k) {
9 | k = k % nums.length;
10 | reverse(nums, 0, k - 1);
11 | reverse(nums, k, nums.length - 1);
12 | reverse(nums, 0, nums.length - 1);
13 | }
14 |
15 | private void reverse(int[] nums, int start, int end) {
16 | while (start < end) {
17 | int tmp = nums[start];
18 | nums[start++] = nums[end];
19 | nums[end--] = tmp;
20 | }
21 | }
22 |
23 |
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/ms/RoundRobin.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.ms;
2 |
3 | /**
4 | * Created by lipeng on 2016/3/18.
5 | */
6 | public class RoundRobin {
7 |
8 | public void roundRobin(int team) {
9 | int round = team - 1;
10 | int[] arr = new int[team];
11 | for (int i = 0; i < team; i++) {
12 | arr[i] = i;
13 | }
14 | for (int i = 0; i < round; i++) {
15 | for (int j = 0; j < team >> 1; j++) {
16 | System.out.print(arr[j] + "," + arr[j + team / 2] + "\t");
17 | }
18 | System.out.println();
19 | int tmp = arr[0];
20 | for (int j = 0; j < team - 2; j++) {
21 | arr[j] = arr[j + 1];
22 | }
23 | arr[team - 2] = tmp;
24 | }
25 | }
26 |
27 | public static void main(String[] args) {
28 | RoundRobin roundRobin = new RoundRobin();
29 | roundRobin.roundRobin(4);
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/ms/StockCoolDown.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.ms;
2 |
3 | /**
4 | * Created by lipeng on 2016/3/19.
5 | */
6 | public class StockCoolDown {
7 |
8 | public int maxProfit(int[] prices) {
9 | if (prices == null || prices.length <= 1) {
10 | return 0;
11 | }
12 | int[] sell = new int[prices.length];
13 | int[] notsell = new int[prices.length];
14 | sell[1] = Math.max(prices[1] - prices[0], 0);
15 | for (int i = 2; i < prices.length; i++) {
16 | int diff = prices[i] - prices[i - 1];
17 | sell[i] = Math.max(sell[i - 1] + diff, notsell[i - 2] + diff);
18 | notsell[i] = Math.max(sell[i - 1], notsell[i - 1]);
19 | }
20 | return Math.max(sell[prices.length - 1], notsell[prices.length - 1]);
21 | }
22 |
23 | public static void main(String[] args) {
24 | int[] prices = {1, 2, 3, 0, 2};
25 | StockCoolDown stock = new StockCoolDown();
26 | System.out.println(stock.maxProfit(prices));
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/ms/StringToInteger.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.ms;
2 |
3 | /**
4 | * Created by lipeng on 2016/3/18.
5 | */
6 | public class StringToInteger {
7 |
8 | public int getInteger(String str) {
9 | int ans = 0;
10 | int sign = 1;
11 | int i = 0;
12 | if (str.charAt(0) == '-') {
13 | sign = -1;
14 | i = 1;
15 | }
16 | for (; i < str.length(); i++) {
17 | char ch = str.charAt(i);
18 | ans = ans * 10 + (ch - '0');
19 | }
20 | return ans * sign;
21 | }
22 |
23 | public static void main(String[] args) {
24 | StringToInteger s = new StringToInteger();
25 | System.out.println(s.getInteger("-1234"));
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/ms/TopologySorting.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.ms;
2 |
3 | /**
4 | * Created by lipeng on 2016/3/17.
5 | */
6 | public class TopologySorting {
7 |
8 |
9 |
10 | }
11 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/numbertheory/CountDigitOne.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.numbertheory;
2 |
3 | /**
4 | * Created by lipeng on 2016/2/6.
5 | * https://leetcode.com/problems/number-of-digit-one/
6 | */
7 | public class CountDigitOne {
8 |
9 | public static int countDigitOne(int n) {
10 | if (n <=0) {
11 | return 0;
12 | }
13 | int len = (int)Math.log10(n) + 1;
14 | int left, right, mid, tmp, ans = 0;
15 | for (int i = 0, unit = 1; i < len; i++, unit *= 10) {
16 | tmp = n / unit;
17 | left = tmp / 10;
18 | mid = tmp - tmp / 10 * 10;
19 | right = n - tmp * unit;
20 | ans += left * unit;
21 | if (mid > 1) {
22 | ans += unit;
23 | }
24 | else if (mid == 1) {
25 | ans += right + 1;
26 | }
27 | }
28 | return ans;
29 | }
30 |
31 |
32 | public static void main(String[] args) {
33 | System.out.println(countDigitOne(11));
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/numbertheory/DigitalRoot.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.numbertheory;
2 |
3 | /**
4 | * Created by lipeng on 2016/1/24.
5 | * https://leetcode.com/problems/add-digits/
6 | */
7 | public class DigitalRoot {
8 |
9 | // bascially, return the modular 9 of num. But we need to exclude 2 exceptions:
10 | // 1. when num is 0. return 0
11 | // 2. when modular is 0, should return 0;
12 | // eaiest one is return num - (num - 1) / 9 * 9
13 | public static int addDigits(int num) {
14 | if (num == 0)
15 | return 0;
16 | int mod = num % 9;
17 | if (mod == 0)
18 | return 9;
19 | else
20 | return mod;
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/numbertheory/HappyNumber.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.numbertheory;
2 |
3 | import java.util.HashSet;
4 |
5 | /**
6 | * Created by lipeng on 2016/1/22.
7 | * http://www.lintcode.com/en/problem/happy-number/
8 | */
9 | public class HappyNumber {
10 |
11 | public static boolean isHappy(int n) {
12 | // Write your code here
13 | HashSet hs = new HashSet();
14 | while (!hs.contains(n)) {
15 | hs.add(n);
16 | int next = 0;
17 | while (n != 0) {
18 | int unit = n - n / 10 * 10;
19 | n /= 10;
20 | next += Math.pow(unit, 2);
21 | }
22 | if (next == 1) {
23 | return true;
24 | }
25 | n = next;
26 | }
27 | return false;
28 | }
29 |
30 | public static void main(String[] args) {
31 | System.out.println(isHappy(2));
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/numbertheory/PascalTriangle.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.numbertheory;
2 |
3 | import com.pli.project.algorithm.exercise2014.IntegerSet;
4 |
5 | import java.util.ArrayList;
6 | import java.util.InputMismatchException;
7 | import java.util.List;
8 |
9 | /**
10 | * Created by lipeng on 2016/1/6.
11 | */
12 | public class PascalTriangle {
13 |
14 | public static List getRow(int rowIndex) {
15 | List list = new ArrayList();
16 | list.add(1);
17 | if(rowIndex == 0)
18 | return list;
19 | for(int m = 1; m < rowIndex + 1; m++) {
20 | int pre = list.get(list.size() - 1);
21 | list.add(pre / m * (rowIndex - m + 1));
22 | }
23 | return list;
24 | }
25 |
26 | public static void main(String[] args) {
27 | List list = getRow(30);
28 | System.out.println(list);
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/numbertheory/PatchingArray.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.numbertheory;
2 |
3 | /**
4 | * Created by pli on 1/28/2016.
5 | */
6 | public class PatchingArray {
7 |
8 |
9 |
10 |
11 | public static int minPatches(int[] nums, int n) {
12 | int i = 0, count = 0;
13 | long reach = 0;
14 | while (reach < n) {
15 | if (i < nums.length && reach + 1 >= nums[i]) {
16 | reach += nums[i++];
17 | }
18 | else {
19 | reach = reach * 2 + 1;
20 | count++;
21 | }
22 | }
23 | return count;
24 | }
25 |
26 | public static void main(String[] args) {
27 | int[] nums = {1, 3}; int n = 6;
28 | // int[] nums = {1, 5, 10}; int n = 20;
29 | // int[] nums = {1, 2, 2}; int n = 5;
30 | // int[] nums = {1, 2, 4, 13, 43}; int n = 100;
31 | System.out.println(minPatches(nums, n));
32 |
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/numbertheory/PerfectSquare.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.numbertheory;
2 |
3 | /**
4 | * Created by lipeng on 2015/5/25.
5 | */
6 | public class PerfectSquare {
7 |
8 | public static int num_squares(int n){
9 | int[] table = new int[n+1];
10 | int max = (int)Math.floor(Math.sqrt(n));
11 | int squared;
12 |
13 | for (int i=0; i<=n; i++){
14 | table[i] = i;
15 | }
16 | for (int i=2; i<=max; i++){
17 | squared = (int)Math.pow(i,2);
18 | for (int j=0; j<=n; j++){
19 | if (squared <= j)
20 | table[j] = Math.min(table[j], table[j - squared] + 1);
21 | }
22 | }
23 | return table[n];
24 | }
25 |
26 | public static void main(String[] args) {
27 | int result = num_squares(13);
28 | System.out.println(result);
29 | }
30 | }
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/numbertheory/PowerOfThree.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.numbertheory;
2 |
3 | /**
4 | * Created by lipeng on 2016/1/10.
5 | * https://leetcode.com/discuss/78735/two-ways-and-o-1
6 | * Other solutions:
7 | * return (n == 1 || n == 3 || n == 9 || n == 27 || n == 81 || n == 243 || n == 729 || n == 2187 || n == 6561 || n == 19683 || n == 59049 || n == 177147 || n == 531441 || n == 1594323 || n == 4782969 || n == 14348907 || n == 43046721 || n == 129140163 || n == 387420489 || n == 1162261467);
8 | * return n>0?!(1162261467 % n):0;
9 | */
10 | public class PowerOfThree {
11 |
12 | public static boolean isPowerOfThree(int n) {
13 | while (n >= 3) {
14 | if (n % 3 != 0)
15 | return false;
16 | n /= 3;
17 | }
18 | if (n == 1)
19 | return true;
20 | else
21 | return false;
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/numbertheory/PowerOfTwo.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.numbertheory;
2 |
3 | /**
4 | * Created by lipeng on 2016/2/18.
5 | */
6 | public class PowerOfTwo {
7 |
8 | public static boolean isPowerOfTwo(int n) {
9 | if (n <= 0) {
10 | return false;
11 | }
12 | return n == (-n & n);
13 | }
14 |
15 | public static void main(String[] args) {
16 | System.out.println(isPowerOfTwo(8));
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/numbertheory/PrintPrimeNumbers.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/allenlipeng47/algorithm/b62ab81f6f9d3ebd5db09093d5e4e8abd1e336a3/src/main/java/com/pli/project/algorithm/numbertheory/PrintPrimeNumbers.java
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/numbertheory/SuperUglyNumber.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.numbertheory;
2 |
3 | /**
4 | * Created by pli on 1/5/2016.
5 | */
6 | public class SuperUglyNumber {
7 |
8 | public static int nthSuperUglyNumber(int[] primes, int n) {
9 | int pn = primes.length;
10 | int[] index = new int[pn];
11 | int[] nums = new int[n];
12 | nums[0] = 1;
13 | for(int i = 1; i < n; i++) {
14 | int min = Integer.MAX_VALUE;
15 | for(int j = 0; j < pn; j++) {
16 | int curr = nums[index[j]] * primes[j];
17 | min = curr < min ? curr : min;
18 | }
19 | nums[i] = min;
20 | for(int j = 0; j < pn; j++)
21 | if(nums[i] == nums[index[j]] * primes[j])
22 | index[j]++;
23 | }
24 | return nums[n - 1];
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/numbertheory/UglyNumber.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.numbertheory;
2 |
3 | /**
4 | * Created by lipeng on 2016/1/23.
5 | */
6 | public class UglyNumber {
7 |
8 | public static boolean isUgly(int num) {
9 | return isUgly(num, new int[] {2, 3, 5});
10 | }
11 |
12 | public static boolean isUgly(int num, int[] primes) {
13 | if (num == 0)
14 | return false;
15 | int n = primes.length;
16 | for (int i = 0; i < n; i++) {
17 | while (num % primes[i] == 0)
18 | num /= primes[i];
19 | }
20 | if (num == 1)
21 | return true;
22 | return false;
23 | }
24 |
25 | public static void main(String[] args) {
26 | System.out.println(isUgly(0));
27 | }
28 |
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/os/Sync/Mutex.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.os.Sync;
2 |
3 | /**
4 | * Created by lipeng on 2015/12/21.
5 | */
6 |
7 | class PrintDemo {
8 |
9 | public synchronized void print() {
10 | for(int i=0; i<100; i++) {
11 | for(int j=0; j<5; j++)
12 | System.out.print(0);
13 | System.out.println();
14 | }
15 | }
16 |
17 | }
18 |
19 | public class Mutex implements Runnable{
20 |
21 | PrintDemo print = new PrintDemo();
22 |
23 | public Mutex(PrintDemo print) {
24 | this.print = print;
25 | }
26 |
27 | public void run() {
28 | print.print();
29 | }
30 |
31 | public static void main(String[] args) {
32 | PrintDemo printDemo = new PrintDemo();
33 | Thread t0 = new Thread(new Mutex(printDemo));
34 | Thread t1 = new Thread(new Mutex(printDemo));
35 | t0.start();
36 | t1.start();
37 | }
38 |
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/os/Sync/NoSync.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.os.Sync;
2 |
3 | /**
4 | * Created by lipeng on 2015/12/21.
5 | */
6 |
7 | class PrintDemo1 {
8 |
9 | public void print() {
10 | for(int i=0; i<100; i++) {
11 | for(int j=0; j<5; j++)
12 | System.out.print(0);
13 | System.out.println();
14 | }
15 | }
16 |
17 | }
18 |
19 | public class NoSync implements Runnable{
20 |
21 | PrintDemo1 print = new PrintDemo1();
22 |
23 | public NoSync(PrintDemo1 print) {
24 | this.print = print;
25 | }
26 |
27 | public void run() {
28 | print.print();
29 | }
30 |
31 | public static void main(String[] args) {
32 | PrintDemo1 printDemo1 = new PrintDemo1();
33 | Thread t0 = new Thread(new NoSync(printDemo1));
34 | Thread t1 = new Thread(new NoSync(printDemo1));
35 | t0.start();
36 | t1.start();
37 | }
38 |
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/os/Sync/SyncOnMethod.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.os.Sync;
2 |
3 | /**
4 | * Created by lipeng on 2015/12/21.
5 | */
6 |
7 | class PrintDemo2 {
8 |
9 | public synchronized void print() {
10 | for(int i=0; i<100; i++) {
11 | for(int j=0; j<5; j++)
12 | System.out.print(0);
13 | System.out.println();
14 | }
15 | }
16 |
17 | }
18 |
19 | public class SyncOnMethod implements Runnable{
20 |
21 | PrintDemo print = new PrintDemo();
22 |
23 | public SyncOnMethod(PrintDemo print) {
24 | this.print = print;
25 | }
26 |
27 | public void run() {
28 | print.print();
29 | }
30 |
31 | public static void main(String[] args) {
32 | PrintDemo printDemo2 = new PrintDemo();
33 | Thread t0 = new Thread(new SyncOnMethod(printDemo2));
34 | Thread t1 = new Thread(new SyncOnMethod(printDemo2));
35 | t0.start();
36 | t1.start();
37 | }
38 |
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/os/Sync/SyncOnVariable.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.os.Sync;
2 |
3 | /**
4 | * Created by lipeng on 2015/12/21.
5 | */
6 |
7 | class PrintDemo3 {
8 |
9 | public void print() {
10 | for(int i=0; i<100; i++) {
11 | for(int j=0; j<5; j++)
12 | System.out.print(0);
13 | System.out.println();
14 | }
15 | }
16 |
17 | }
18 |
19 | public class SyncOnVariable implements Runnable{
20 |
21 | PrintDemo3 print = new PrintDemo3();
22 |
23 | public SyncOnVariable(PrintDemo3 print) {
24 | this.print = print;
25 | }
26 |
27 | public void run() {
28 | synchronized (print) {
29 | print.print();
30 | }
31 | }
32 |
33 | public static void main(String[] args) {
34 | PrintDemo3 printDemo3 = new PrintDemo3();
35 | Thread t0 = new Thread(new SyncOnVariable(printDemo3));
36 | Thread t1 = new Thread(new SyncOnVariable(printDemo3));
37 | t0.start();
38 | t1.start();
39 | }
40 |
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/os/Sync/readme:
--------------------------------------------------------------------------------
1 | In Java, mutex can be done by Object synchronization or method synchronization.
2 | When more than one thread call same method or object, and if there is no synchronization, then there is no order guarantee.
3 | If we add synchronization on Object we use or method, then the object or method can be visited mutually exclusive.
4 |
5 | NoSync.java shows an example when there is no mutex setup. So, there print 0 is in a mess.
6 | SyncOnMethod uses synchronization on same method. So same method is visited mutually.
7 | SyncOnVariable uses synchronization on same object, which is PrintDemo. So this object is visited mutually.
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/practice/AddTwoNumbers.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.practice;
2 |
3 |
4 | import com.pli.project.algorithm.leetcode.ListNode;
5 |
6 | /**
7 | * Created by lipeng on 2016/8/10.
8 | */
9 | public class AddTwoNumbers {
10 |
11 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
12 | ListNode dummyHead = new ListNode(-1), curr = dummyHead;
13 | int carrier = 0;
14 | while (l1 != null || l2 != null || carrier != 0) {
15 | int num = 0;
16 | if (l1 != null) {
17 | num += l1.val;
18 | l1 = l1.next;
19 | }
20 | if (l2 != null) {
21 | num += l2.val;
22 | l2 = l2.next;
23 | }
24 | num += carrier;
25 | curr.next = new ListNode(num - num / 10 * 10);
26 | carrier = num / 10;
27 | curr = curr.next;
28 | }
29 | return dummyHead.next;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/practice/BinarySearch.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.practice;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * Created by lipeng on 2015/12/12.
8 | */
9 | public class BinarySearch {
10 |
11 |
12 | public static void main(String[] args) {
13 |
14 | }
15 |
16 | public int findLeftInclusive(int[] nums, int target) {
17 | if (target < nums[0]) {
18 | return -1;
19 | }
20 | int left = 0, right = nums.length - 1;
21 | while (left < right) {
22 | int mid = left + (right - left) / 2;
23 | if (target >= nums[mid]) {
24 | if (target < nums[mid + 1]) {
25 | return mid;
26 | }
27 | else {
28 | left = mid + 1;
29 | }
30 | }
31 | else {
32 | right = mid - 1;
33 | }
34 | }
35 | return left;
36 | }
37 |
38 | }
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/practice/InOrder.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.practice;
2 |
3 | import com.pli.project.algorithm.leetcode.TreeNode;
4 |
5 | import java.util.ArrayList;
6 | import java.util.List;
7 | import java.util.Stack;
8 |
9 | /**
10 | * Created by lipeng on 2016/9/14.
11 | */
12 | public class InOrder {
13 |
14 | public List inorderTraversal(TreeNode root) {
15 | Stack stack = new Stack<>();
16 | List ans = new ArrayList<>();
17 | loadLeft(root, stack);
18 | while (!stack.isEmpty()) {
19 | TreeNode curr = stack.pop();
20 | ans.add(curr.val);
21 | loadLeft(curr.right, stack);
22 | }
23 | return ans;
24 | }
25 |
26 | private void loadLeft(TreeNode root, Stack stack) {
27 | while (root != null) {
28 | stack.add(root);
29 | root = root.left;
30 | }
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/practice/LinkedListCycleII.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.practice;
2 |
3 | import com.pli.project.algorithm.leetcode.ListNode;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/12.
7 | * https://leetcode.com/problems/linked-list-cycle-ii/
8 | */
9 | public class LinkedListCycleII {
10 |
11 | public ListNode detectCycle(ListNode head) {
12 | ListNode slow = head, fast = head;
13 | while (fast != null && fast.next != null) {
14 | slow = slow.next;
15 | fast = fast.next.next;
16 | if (slow == fast) {
17 | break;
18 | }
19 | }
20 | if (fast == null || fast.next == null) {
21 | return null;
22 | }
23 | slow = head;
24 | while (slow != fast) {
25 | slow = slow.next;
26 | fast = fast.next;
27 | }
28 | return fast;
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/practice/LongestIncreasingSubseq.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.practice;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * Created by lipeng on 2016/9/8.
7 | */
8 | public class LongestIncreasingSubseq {
9 |
10 | public static int lengthOfLIS(int[] nums) {
11 | int[] dp = new int[nums.length];
12 | int size = 0;
13 | for (int i : nums) {
14 | int idx = Arrays.binarySearch(dp, 0, size, i);
15 | if (idx < 0) {
16 | idx = -(idx + 1);
17 | }
18 | dp[idx] = i;
19 | if (idx == size) {
20 | size++;
21 | }
22 | }
23 | return size;
24 | }
25 |
26 | public static void main(String[] args) {
27 | int[] nums = {10, 9, 2, 5, 3, 7, 101, 18};
28 | System.out.println(lengthOfLIS(nums));
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/practice/MinSubSum.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.practice;
2 |
3 | /**
4 | * Created by lipeng on 2016/9/14.
5 | * https://leetcode.com/problems/minimum-size-subarray-sum/
6 | */
7 | public class MinSubSum {
8 |
9 | public static int minSubArrayLen(int s, int[] nums) {
10 | int left = 0, right = 0, ans = Integer.MAX_VALUE, sum = 0;
11 | while (right <= nums.length) {
12 | if (sum >= s) {
13 | ans = Math.min(ans, right - left);
14 | sum -= nums[left++];
15 | }
16 | else if (right < nums.length){
17 | sum += nums[right++];
18 | }
19 | else {
20 | break;
21 | }
22 | }
23 | return ans == Integer.MAX_VALUE ? 0 : ans;
24 | }
25 |
26 | public static void main(String[] args) {
27 | int[] nums = {1, 4, 4};
28 | System.out.println(minSubArrayLen(4, nums));
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/practice/PatchingArray.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.practice;
2 |
3 | /**
4 | * Created by lipeng on 2016/9/8.
5 | * https://leetcode.com/problems/patching-array/
6 | */
7 | public class PatchingArray {
8 |
9 | public int minPatches(int[] nums, int n) {
10 | int ans = 0, i = 0;
11 | long reach = 0;
12 | while (reach < n){
13 | if (i < nums.length && reach + 1 >= nums[i]) {
14 | reach += nums[i++];
15 | }
16 | else {
17 | reach += reach + 1;
18 | ans++;
19 | }
20 | }
21 | return ans;
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/practice/PowXNTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.practice;
2 |
3 | import com.pli.project.algorithm.leetcode.PowXN;
4 | import org.junit.Test;
5 |
6 | /**
7 | * Created by lipeng on 2016/8/12.
8 | * https://leetcode.com/problems/powx-n/
9 | */
10 | public class PowXNTest {
11 |
12 | @Test
13 | public void test1() {
14 | PowXN p = new PowXN();
15 | // assert p.myPow(4, 3) == 64;
16 | // assert p.myPow(8, 3) == 512;
17 | System.out.println(p.myPow(8.88023, 3));
18 | assert p.myPow(8.88023, 3) == 700.28148;
19 | }
20 |
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/practice/ReverseLinkedList.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.practice;
2 |
3 | import com.pli.project.algorithm.leetcode.ListNode;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/10.
7 | */
8 | public class ReverseLinkedList {
9 |
10 | public ListNode reverseList(ListNode head) {
11 | ListNode dummyHead = new ListNode(-1), curr = head;
12 | while (curr != null) {
13 | ListNode next = curr.next;
14 | curr.next = dummyHead.next;
15 | dummyHead.next = curr;
16 | curr = next;
17 | }
18 | return dummyHead.next;
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/probability/ReturnWithProbabilityProportionalToItsWeight.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/allenlipeng47/algorithm/b62ab81f6f9d3ebd5db09093d5e4e8abd1e336a3/src/main/java/com/pli/project/algorithm/probability/ReturnWithProbabilityProportionalToItsWeight.java
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/recursion/Combination.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.recursion;
2 |
3 | /**
4 | * Created by pli on 12/21/2015.
5 | */
6 | public class Combination {
7 |
8 | public static void combination(char[] chs) {
9 | combinationHelper(chs, 0, new StringBuffer());
10 | }
11 |
12 | public static void combinationHelper(char[] chs, int index, StringBuffer sb) {
13 | for(int i=index; i {
9 | public boolean isCollection();
10 |
11 | public Collection> getCollection();
12 |
13 | public T getElement();
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/recursion/NextElement/readme.txt:
--------------------------------------------------------------------------------
1 | Given a interface, implement the iterator for this interface.
2 |
3 | interface Data {
4 | // Does this Data hold a collection?
5 | public boolean isCollection();
6 | // Returns the collection contained by
7 | // this Data, or null if it is a single element
8 | public Collection> getCollection();
9 | // Returns the single element contained
10 | //by this Data, or null if it is collection
11 | public T getElement();
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/sort/GrayCode.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.sort;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * Created by lipeng on 2016/1/2.
8 | */
9 | public class GrayCode {
10 |
11 | public static List grayCode(int n) {
12 | List ans = new ArrayList();
13 | ans.add(0);
14 | for(int i = 0, base = 1; i < n; i++, base = base << 1) {
15 | for (int j = ans.size() - 1; j >= 0; j--)
16 | ans.add(ans.get(j) | base);
17 | }
18 | return ans;
19 | }
20 |
21 | public static void main(String[] args) {
22 | List ans = grayCode(2);
23 | System.out.println(ans);
24 | System.out.println();
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/string/ReverseSentence.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.string;
2 |
3 | /**
4 | * Created by lipeng on 2015/12/12.
5 | * Given "hello world" -> "world hello"
6 | * Given "abc def ghi" -> "ghi def abc"
7 | */
8 | public class ReverseSentence {
9 |
10 | public static String reverseSentence(String str) {
11 | assert str!=null;
12 | StringBuffer result = new StringBuffer();
13 | int endPos = str.length();
14 | for(int pos=str.lastIndexOf(" "); pos>=0; endPos=pos, pos=str.lastIndexOf(" ", pos-1)) {
15 | result.append(str.substring(pos+1, endPos) + " ");
16 | }
17 | result.append(str.substring(0, endPos));
18 | return result.toString().trim();
19 | }
20 |
21 |
22 | public static void main(String[] args) {
23 | String str = "";
24 | System.out.println(reverseSentence(str));
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/test.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm;
2 |
3 | import com.pli.project.algorithm.exercise2014.IntegerSet;
4 | import com.pli.project.algorithm.util.TreeNode;
5 | import org.omg.PortableServer.LIFESPAN_POLICY_ID;
6 | import sun.awt.IconInfo;
7 |
8 | import java.io.ByteArrayOutputStream;
9 | import java.io.PrintStream;
10 | import java.math.BigInteger;
11 | import java.util.*;
12 | import java.util.concurrent.BlockingQueue;
13 |
14 | /**
15 | * Created by lipeng on 2015/12/12.
16 | */
17 | public class test {
18 |
19 | public static void main(String[] args) {
20 | }
21 |
22 |
23 |
24 |
25 | }
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/tree/HouseRobberIII.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.tree;
2 |
3 | import com.pli.project.algorithm.util.TreeNode;
4 |
5 | /**
6 | * Created by lipeng on 2016/3/14.
7 | */
8 | public class HouseRobberIII {
9 |
10 | public int rob(TreeNode root) {
11 | return Math.max(robHelper(root, true), robHelper(root, false));
12 | }
13 |
14 | public int robHelper(TreeNode root, boolean canRob) {
15 | if (root == null) {
16 | return 0;
17 | }
18 | int robLeft = robHelper(root.left, true);
19 | int robRight = robHelper(root.right, true);
20 | if (!canRob) {
21 | return robLeft + robRight;
22 | }
23 | int noRobLeft = robHelper(root.left, false);
24 | int noRobRight = robHelper(root.right, false);
25 | return Math.max(root.val + noRobLeft + noRobRight, robLeft + robRight);
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/tree/LowestCommonAncestry.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.tree;
2 |
3 | /**
4 | * Created by lipeng on 2016/1/29
5 | * https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/.
6 | */
7 | public class LowestCommonAncestry {
8 |
9 | public static class TreeNode {
10 | int val;
11 | TreeNode left;
12 | TreeNode right;
13 | TreeNode(int x) { val = x; }
14 | }
15 |
16 | public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
17 | if (root == p || root == q || root == null) {
18 | return root;
19 | }
20 | TreeNode left = lowestCommonAncestor(root.left, p, q);
21 | TreeNode right = lowestCommonAncestor(root.right, p, q);
22 | if (left != null && right != null) {
23 | return root;
24 | }
25 | if (left != null) {
26 | return left;
27 | }
28 | return right;
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/tree/suffixtree/util/LcsRec.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.tree.suffixtree.util;
2 |
3 | /**
4 | * Created by pli on 12/18/2015.
5 | * This is a record used for lcs search
6 | */
7 | public class LcsRec {
8 |
9 | public int firstPos; // position where common string happens in first string
10 | public int secondPos; // position where common string happens in first string
11 | public int length; // length of common string
12 |
13 | public LcsRec() {
14 | firstPos = -1;
15 | secondPos = -1;
16 | length = 0;
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/tree/suffixtree/util/SuffixEdge.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.tree.suffixtree.util;
2 |
3 | /**
4 | * Created by pli on 12/15/2015.
5 | */
6 | public class SuffixEdge {
7 |
8 | public int start; // start position of string on edge
9 |
10 | public int end; // -1 means it has no out-going node, it is an end edge
11 |
12 | public int strStart; // the start point where the whole substring is
13 |
14 | public SuffixNode parent;
15 |
16 | public SuffixNode child;
17 |
18 | public SuffixEdge(SuffixNode parent, int start) {
19 | this.parent = parent;
20 | this.start = start;
21 | end = -1;
22 | }
23 |
24 | }
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/tree/suffixtree/util/SuffixNode.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.tree.suffixtree.util;
2 |
3 | /**
4 | * Created by pli on 12/14/2015.
5 | */
6 | public class SuffixNode {
7 |
8 | public static final int CHARARCTER_SIZE = 256;
9 |
10 | public SuffixEdge[] edges = new SuffixEdge[CHARARCTER_SIZE];
11 | public SuffixNode suffixLink;
12 |
13 | public void addEdge(char c, SuffixEdge edge) {
14 | edges[c-'0'] = edge;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/util/MaxHeap.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/allenlipeng47/algorithm/b62ab81f6f9d3ebd5db09093d5e4e8abd1e336a3/src/main/java/com/pli/project/algorithm/util/MaxHeap.java
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/util/MyBoolean.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.util;
2 |
3 | public class MyBoolean {
4 | public boolean bool;
5 | public MyBoolean(boolean bool){
6 | this.bool = bool;
7 | }
8 | public MyBoolean(){
9 | this.bool = false;
10 | }
11 | public String toString(){
12 | return String.valueOf(bool);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/util/MyInteger.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.util;
2 |
3 | public class MyInteger{
4 | public int i = 0;
5 | public MyInteger(int i){
6 | this.i = i;
7 | }
8 | public MyInteger(){}
9 |
10 | public String toString(){
11 | return String.valueOf(i);
12 | }
13 | }
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/util/SegIntervalNode.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.util;
2 |
3 | public class SegIntervalNode {
4 | int index;
5 | int left;
6 | int right;
7 | int cover;
8 |
9 | public SegIntervalNode() {
10 | }
11 |
12 | public SegIntervalNode(int index, int left, int right) {
13 | this.index = index;
14 | this.left = left;
15 | this.right = right;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/com/pli/project/algorithm/util/Tree.pptx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/allenlipeng47/algorithm/b62ab81f6f9d3ebd5db09093d5e4e8abd1e336a3/src/main/java/com/pli/project/algorithm/util/Tree.pptx
--------------------------------------------------------------------------------
/src/main/js/IntersectionofTwoArrays.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by lipeng on 2016/6/6.
3 | */
4 | /**
5 | * @param {number[]} nums1
6 | * @param {number[]} nums2
7 | * @return {number[]}
8 | * Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
9 | */
10 | var intersection = function(nums1, nums2) {
11 | var hm = {};
12 | for (var n in nums1) {
13 | hm[n] = 1;
14 | }
15 | var ans = {};
16 | for (var n in nums2) {
17 | if (hm[n]) {
18 | ans[n] = 1;
19 | }
20 | }
21 | return Object.keys(ans);
22 | };
23 |
24 | var a = [1, 2, 2, 1]
25 | var b = [2, 2];
26 | console.log(intersection(a, b));
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/SystemOut.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm;
2 |
3 | import org.junit.After;
4 | import org.junit.Before;
5 | import org.junit.Test;
6 |
7 | import java.io.ByteArrayOutputStream;
8 | import java.io.PrintStream;
9 |
10 | /**
11 | * The way to test system.out.print();
12 | * Created by lipeng on 2016/8/22.
13 | */
14 | public class SystemOut {
15 |
16 | private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
17 | private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
18 |
19 | @Before
20 | public void setUpStreams() {
21 | System.setOut(new PrintStream(outContent));
22 | System.setErr(new PrintStream(errContent));
23 | }
24 |
25 | @After
26 | public void cleanUpStreams() {
27 | System.setOut(null);
28 | System.setErr(null);
29 | }
30 |
31 | @Test
32 | public void out() {
33 | System.out.print("hello");
34 | assert "hello".equals(outContent.toString());
35 | }
36 |
37 |
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/AddBinaryTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/22.
7 | */
8 | public class AddBinaryTest {
9 |
10 | @Test
11 | public void test1() {
12 | AddBinary a = new AddBinary();
13 | assert a.addBinary("11", "1").equals("100");
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/BstRightSideViewTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | /**
4 | * Created by lipeng on 2016/8/20.
5 | * https://leetcode.com/problems/binary-tree-right-side-view/
6 | */
7 | public class BstRightSideViewTest {
8 | }
9 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/BstTopViewTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import com.pli.project.algorithm.util.TreeNode;
4 | import org.junit.Test;
5 |
6 | /**
7 | * Created by lipeng on 2016/8/19.
8 | */
9 | public class BstTopViewTest {
10 |
11 | @Test
12 | public void test1() {
13 | BstTopView b = new BstTopView();
14 | TreeNode t1 = new TreeNode(1);
15 | TreeNode t2 = new TreeNode(2);
16 | TreeNode t3 = new TreeNode(3);
17 | TreeNode t4 = new TreeNode(4);
18 | TreeNode t5 = new TreeNode(5);
19 | TreeNode t6 = new TreeNode(6);
20 | TreeNode t7 = new TreeNode(7);
21 | t1.left = t2; t1.right = t3;
22 | t2.left = t4; t2.right = t5;
23 | t5.right = t6;
24 | t6.right = t7;
25 | b.top_view(t1);
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/ClimbingLadderTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/21.
7 | */
8 | public class ClimbingLadderTest {
9 |
10 | @Test
11 | public void test1() {
12 | ClimbingLadder c = new ClimbingLadder();
13 | assert c.climbStairs(3) == 3;
14 | assert c.climbStairs(4) == 5;
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/CombinationSumIITest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.List;
6 |
7 | /**
8 | * Created by lipeng on 2016/8/22.
9 | */
10 | public class CombinationSumIITest {
11 |
12 | @Test
13 | public void test1() {
14 | CombinationSumII c = new CombinationSumII();
15 | int[] candidates = {10, 1, 2, 7, 6, 1, 5};
16 | List> ans = c.combinationSum2(candidates, 8);
17 | System.out.println(ans);
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/CombinationSumTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.ArrayList;
6 | import java.util.List;
7 |
8 | /**
9 | * Created by lipeng on 2016/8/22.
10 | */
11 | public class CombinationSumTest {
12 |
13 | @Test
14 | public void test1() {
15 | CombinationSum c = new CombinationSum();
16 | int[] candidates = {2, 3, 6, 7};
17 | List> set = c.combinationSum(candidates, 7);
18 | System.out.println(set);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/ConvertToTitleTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/24.
7 | */
8 | public class ConvertToTitleTest {
9 |
10 | @Test
11 | public void test1() {
12 | ConvertToTitle c = new ConvertToTitle();
13 | System.out.println(c.convertToTitle(1));
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/CountDigitOneTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/19.
7 | */
8 | public class CountDigitOneTest {
9 |
10 | @Test
11 | public void test1() {
12 | CountDigitOne c = new CountDigitOne();
13 | assert c.countDigitOne(2) == 1;
14 | assert c.countDigitOne(10) == 2;
15 | assert c.countDigitOne(11) == 4;
16 | assert c.countDigitOne(1410065408) == 1737167499;
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/CountNumberWithUniqueDigitTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/24.
7 | */
8 | public class CountNumberWithUniqueDigitTest {
9 |
10 | @Test
11 | public void test1() {
12 | CountNumberWithUniqueDigit c = new CountNumberWithUniqueDigit();
13 | assert c.countNumbersWithUniqueDigits(0) == 1;
14 | assert c.countNumbersWithUniqueDigits(1) == 10;
15 | assert c.countNumbersWithUniqueDigits(2) == 91;
16 | assert c.countNumbersWithUniqueDigits(3) == 739;
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/CountPrimesTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.Arrays;
6 |
7 | /**
8 | * Created by lipeng on 2016/8/16.
9 | * https://leetcode.com/problems/count-primes/
10 | */
11 | public class CountPrimesTest {
12 |
13 | @Test
14 | public void test1() {
15 | CountPrimes c = new CountPrimes();
16 | assert c.countPrimes(3) == 1;
17 | assert c.countPrimes(2) == 0;
18 | assert c.countPrimes(3) == 1;
19 | assert c.countPrimes(6) == 3;
20 | assert c.countPrimes(7) == 3;
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/FindDuplicateTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/17.
7 | */
8 | public class FindDuplicateTest {
9 |
10 | @Test
11 | public void test1() {
12 | int[] nums = {1, 4, 3, 3, 2};
13 | FindDuplicate f = new FindDuplicate();
14 | System.out.println(f.findDuplicate(nums));
15 | }
16 |
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/FindKthLargest2Test.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/20.
7 | */
8 | public class FindKthLargest2Test {
9 |
10 | @Test
11 | public void test1() {
12 | int[] nums = {4, 3, 2, 5, 1};
13 | FindKthLargest2 f = new FindKthLargest2();
14 | assert f.findKthLargest(nums, 1) == 5;
15 | assert f.findKthLargest(nums, 2) == 4;
16 | assert f.findKthLargest(nums, 4) == 2;
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/FlipGameIITest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.HashMap;
6 | import java.util.Map;
7 |
8 | /**
9 | * Created by lipeng on 2016/8/22.
10 | * https://discuss.leetcode.com/category/368/flip-game-ii
11 | */
12 | public class FlipGameIITest {
13 |
14 | @Test
15 | public void test1() {
16 | FlipGameII f = new FlipGameII();
17 | assert f.canWin("++") == true;
18 | assert f.canWin("+++") == true;
19 | assert f.canWin("++++") == true;
20 | assert f.canWin("+++++") == false;
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/GrayCodeTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.ArrayList;
6 | import java.util.List;
7 |
8 | /**
9 | * Created by lipeng on 2016/8/16.
10 | */
11 | public class GrayCodeTest {
12 |
13 | @Test
14 | public void test1() {
15 | GrayCode g = new GrayCode();
16 | List list = g.grayCode(2);
17 | assert list.get(0) == 0;
18 | assert list.get(1) == 1;
19 | assert list.get(2) == 3;
20 | assert list.get(3) == 2;
21 | list = g.grayCode(0);
22 | assert list.get(0) == 0;
23 | assert list.size() == 1;
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/HouseRobberTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/20.
7 | */
8 | public class HouseRobberTest {
9 |
10 | @Test
11 | public void test1() {
12 | HouseRobber h = new HouseRobber();
13 | assert h.rob(new int[]{0}) == 0;
14 | assert h.rob(new int[]{1, 1, 1}) == 2;
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/IntToRomanTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.HashMap;
6 | import java.util.Map;
7 | import java.util.Stack;
8 |
9 | /**
10 | * Created by lipeng on 2016/8/22.
11 | * https://leetcode.com/problems/integer-to-roman/
12 | */
13 | public class IntToRomanTest {
14 |
15 | @Test
16 | public void test1() {
17 | IntToRoman i = new IntToRoman();
18 | assert i.intToRoman(621).equals("DCXXI");
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/IntegerBinaryPalindromeTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/23.
7 | */
8 | public class IntegerBinaryPalindromeTest {
9 |
10 | @Test
11 | public void test1() {
12 | IntegerBinaryPalindrome i = new IntegerBinaryPalindrome();
13 | assert i.isPalindrome(6) == true;
14 | assert i.isPalindrome(7) == true;
15 | assert i.isPalindrome(408) == true;
16 | assert i.isPalindrome(409) == false;
17 |
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/IntersectionOfTwoLLTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import com.pli.project.algorithm.leetcode.ListNode;
4 | import org.junit.Test;
5 |
6 | /**
7 | * Created by lipeng on 2016/8/14.
8 | * https://leetcode.com/problems/intersection-of-two-linked-lists/
9 | */
10 | public class IntersectionOfTwoLLTest {
11 |
12 | @Test
13 | public void test1() {
14 | ListNode l1 = new ListNode(1);
15 | ListNode l2 = new ListNode(2);
16 | l1.next = l2;
17 | IntersectionOfTwoLL i = new IntersectionOfTwoLL();
18 | assert i.getIntersectionNode(l1, null) == null;
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/LRUCacheTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/9.
7 | */
8 | public class LRUCacheTest {
9 |
10 | @Test
11 | public void test1() {
12 | LRUCache l = new LRUCache(3);
13 | l.set(1, 1);
14 | l.set(2, 2);
15 | l.set(3, 3);
16 | assert l.get(1) == 1;
17 | assert l.get(2) == 2;
18 | l.set(4, 4);
19 | assert l.get(3) == -1;
20 | }
21 |
22 | @Test
23 | public void test2() {
24 | LRUCache l = new LRUCache(1);
25 | l.set(2, 1);
26 | assert l.get(2) == 1;
27 | l.set(3, 2);
28 | assert l.get(2) == -1;
29 | assert l.get(3) == 2;
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/LetterCombinationOfPhoneNumberTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.ArrayList;
6 | import java.util.HashMap;
7 | import java.util.List;
8 | import java.util.Map;
9 |
10 | /**
11 | * Created by lipeng on 2016/8/10.
12 | */
13 | public class LetterCombinationOfPhoneNumberTest {
14 |
15 | @Test
16 | public void test1() {
17 | LetterCombinationOfPhoneNumber l = new LetterCombinationOfPhoneNumber();
18 | List list = l.letterCombinations("234");
19 | assert list.contains("adg");
20 | assert list.contains("afg");
21 | assert list.contains("cfi");
22 | assert list.contains("bdi");
23 | System.out.println(list);
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/LongestPalindromeSubStringTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/10.
7 | */
8 | public class LongestPalindromeSubStringTest {
9 |
10 | @Test
11 | public void test1() {
12 | LongestPalindromeSubString l = new LongestPalindromeSubString();
13 | assert l.longestPalindrome("a").equals("a");
14 | assert l.longestPalindrome("abba").equals("abba");
15 | assert l.longestPalindrome("abbaa").equals("abba");
16 | assert l.longestPalindrome("ababaa").equals("ababa");
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/LongestSubsqeuenceTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import com.pli.project.algorithm.dp.LongestSubsequenceInString;
4 | import org.junit.Test;
5 |
6 | import java.util.Arrays;
7 |
8 | /**
9 | * Created by lipeng on 2016/8/24.
10 | */
11 | public class LongestSubsqeuenceTest {
12 |
13 | @Test
14 | public void test1() {
15 | LongestSubsqeuence l = new LongestSubsqeuence();
16 | System.out.println(l.lengthOfLIS(new int[]{1, 2, 3, 4, 5}));
17 | System.out.println(l.lengthOfLIS(new int[]{10, 9, 2, 5, 3, 7, 101, 18}));
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/LongestSubstringAtMostKDiffTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.HashSet;
6 | import java.util.Set;
7 |
8 | /**
9 | * Created by lipeng on 2016/8/20.
10 | */
11 | public class LongestSubstringAtMostKDiffTest {
12 |
13 | @Test
14 | public void test1() {
15 | LongestSubstringAtMostKDiff l = new LongestSubstringAtMostKDiff();
16 | assert l.getLongest("acccddee", 2) == 5;
17 | assert l.getLongest("acccddee", 3) == 7;
18 | assert l.getLongest("aacccddee", 4) == 9;
19 | assert l.getLongest("", 4) == 0;
20 | assert l.getLongest("a", 4) == 1;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/LongestSubstringWithoutRepeatingCharactersTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/11.
7 | */
8 | public class LongestSubstringWithoutRepeatingCharactersTest {
9 |
10 | @Test
11 | public void test1() {
12 | LongestSubstringWithoutRepeatingCharacters l = new LongestSubstringWithoutRepeatingCharacters();
13 | assert l.lengthOfLongestSubstring("abcabcbb") == 3;
14 | assert l.lengthOfLongestSubstring("bbbbb") == 1;
15 | assert l.lengthOfLongestSubstring("pwwkew") == 3;
16 | assert l.lengthOfLongestSubstring("abcdebghijk") == 9;
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/MergeKSortedListTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import com.pli.project.algorithm.leetcode.ListNode;
4 | import org.junit.Test;
5 |
6 | import java.util.PriorityQueue;
7 |
8 | /**
9 | * Created by lipeng on 2016/8/15.
10 | */
11 | public class MergeKSortedListTest {
12 |
13 | @Test
14 | public void test1() {
15 | ListNode l1 = new ListNode(1);
16 | ListNode l2 = new ListNode(5);
17 | ListNode l3 = new ListNode(2);
18 | ListNode l4 = new ListNode(4);
19 | ListNode l5 = new ListNode(3);
20 | ListNode l6 = new ListNode(6);
21 | l1.next = l2;
22 | l3.next = l4;
23 | l5.next = l6;
24 | ListNode[] nodes = new ListNode[]{l1, l3, l5};
25 | MergeKSortedList m = new MergeKSortedList();
26 | System.out.println(m.mergeKLists(nodes));
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/MinStackTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.Stack;
6 |
7 | /**
8 | * Created by lipeng on 2016/8/11.
9 | * https://leetcode.com/problems/min-stack/
10 | */
11 | public class MinStackTest {
12 |
13 | @Test
14 | public void test1() {
15 | MinStack m = new MinStack();
16 | m.push(5);
17 | assert m.min == 5;
18 | m.push(4);
19 | assert m.min == 4;
20 | m.push(6);
21 | assert m.min == 4;
22 | m.push(1);
23 | assert m.min == 1;
24 | m.push(3);
25 | assert m.min == 1;
26 | m.pop();
27 | assert m.min == 1;
28 | m.pop();
29 | assert m.min == 4;
30 | m.pop();
31 | assert m.min == 4;
32 | }
33 |
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/MoveZerosTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.Arrays;
6 |
7 | /**
8 | * Created by lipeng on 2016/8/16.
9 | */
10 | public class MoveZerosTest {
11 |
12 | @Test
13 | public void test1() {
14 | int[] nums = {0, 1, 0, 3, 12};
15 | MoveZeros m = new MoveZeros();
16 | m.moveZeroes(nums);
17 | System.out.println(Arrays.toString(nums));
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/MyAtoiTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/23.
7 | */
8 | public class MyAtoiTest {
9 |
10 | @Test
11 | public void test1() {
12 | MyAtoi m = new MyAtoi();
13 | assert m.myAtoi("123") == 123;
14 | assert m.myAtoi("-123") == -123;
15 | assert m.myAtoi("-1234444444444444444444") == Integer.MIN_VALUE;
16 | assert m.myAtoi(" 010") == 10;
17 | assert m.myAtoi("-2147483647") == Integer.MIN_VALUE;
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/NutsAndBoltsMatchTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.Arrays;
6 |
7 | /**
8 | * Created by lipeng on 2016/8/12.
9 | */
10 | public class NutsAndBoltsMatchTest {
11 |
12 | @Test
13 | public void test1() {
14 | NutsAndBoltsMatch n = new NutsAndBoltsMatch();
15 | int[] bolts = {4, 3, 2, 1, 6, 5};
16 | int[] nuts = {2, 5, 6, 4, 1, 3};
17 | n.nutsBolts(bolts, nuts);
18 | System.out.println(Arrays.toString(bolts));
19 | System.out.println(Arrays.toString(nuts));
20 | for (int i = 0; i < bolts.length; i++) {
21 | assert bolts[i] == nuts[i];
22 | }
23 | }
24 |
25 |
26 | }
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/PalindromeNumberTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/23.
7 | */
8 | public class PalindromeNumberTest {
9 |
10 | @Test
11 | public void test1() {
12 | PalindromeNumber p = new PalindromeNumber();
13 | assert p.isPalindrome(121) == true;
14 | assert p.isPalindrome(7461647) == true;
15 | assert p.isPalindrome(74616472) == false;
16 | assert p.isPalindrome(2147483647) == false;
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/PatchingArrayTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/19.
7 | */
8 | public class PatchingArrayTest {
9 |
10 | @Test
11 | public void test1() {
12 | PatchingArray p = new PatchingArray();
13 | assert p.minPatches(new int[]{1, 5, 10}, 20) == 2;
14 | assert p.minPatches(new int[]{1, 2, 2}, 5) == 0;
15 | assert p.minPatches(new int[]{1, 3}, 6) == 1;
16 | System.out.println(p.minPatches(new int[]{1, 2, 1}, 5));
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/PermutationTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.ArrayList;
6 | import java.util.List;
7 |
8 | /**
9 | * Created by lipeng on 2016/8/23.
10 | */
11 | public class PermutationTest {
12 |
13 | @Test
14 | public void test1() {
15 | Permutation p = new Permutation();
16 | List> list = p.permute(new int[]{1, 2, 3});
17 | System.out.println(list);
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/ProductArrayExceptSelfTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.Arrays;
6 |
7 | /**
8 | * Created by lipeng on 2016/8/11.
9 | */
10 | public class ProductArrayExceptSelfTest {
11 |
12 | @Test
13 | public void test1() {
14 | ProductArrayExceptSelf p = new ProductArrayExceptSelf();
15 | int[] ans = p.productExceptSelf(new int[] {1, 2, 3, 4});
16 | assert ans[0] == 24;
17 | assert ans[1] == 12;
18 | assert ans[2] == 8;
19 | assert ans[3] == 6;
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/QuickSortTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/20.
7 | */
8 | public class QuickSortTest {
9 |
10 | @Test
11 | public void test1() {
12 | int[] nums = {5, 3, 1, 4, 2};
13 | QuickSort q = new QuickSort();
14 | q.quickSort(nums);
15 | assert nums[0] == 1;
16 | assert nums[1] == 2;
17 | assert nums[2] == 3;
18 | assert nums[3] == 4;
19 | assert nums[4] == 5;
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/ReconstructIteneraryTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.*;
6 |
7 | /**
8 | * Created by lipeng on 2016/8/21.
9 | */
10 | public class ReconstructIteneraryTest {
11 |
12 | @Test
13 | public void test1() {
14 | String[][] tickets1 = {
15 | {"MUC", "LHR"},
16 | {"JFK", "MUC"},
17 | {"SFO", "SJC"},
18 | {"LHR", "SFO"}
19 | };
20 | ReconstructItenerary r = new ReconstructItenerary();
21 | System.out.println(r.findItinerary(tickets1));
22 |
23 | String[][] tickets2 = {
24 | {"JFK","SFO"},
25 | {"JFK","ATL"},
26 | {"SFO","ATL"},
27 | {"ATL","JFK"},
28 | {"ATL","SFO"}
29 | };
30 | System.out.println(r.findItinerary(tickets2));
31 | }
32 |
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/RemoveDupFromSlIITest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/21.
7 | */
8 | public class RemoveDupFromSlIITest {
9 |
10 | @Test
11 | public void test1() {
12 | RemoveDupFromSlII r = new RemoveDupFromSlII();
13 | int[] nums = {1, 1, 1, 2, 2, 3};
14 | assert r.removeDuplicates(nums) == 5;
15 | assert nums[0] == 1;
16 | assert nums[1] == 1;
17 | assert nums[2] == 2;
18 | assert nums[3] == 2;
19 | assert nums[4] == 3;
20 | }
21 |
22 |
23 | @Test
24 | public void test2() {
25 | RemoveDupFromSlII r = new RemoveDupFromSlII();
26 | int[] nums = {1, 1, 1};
27 | assert r.removeDuplicates(nums) == 2;
28 | assert nums[0] == 1;
29 | assert nums[1] == 1;
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/RemoveDupLetttersTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.Stack;
6 |
7 | /**
8 | * Created by lipeng on 2016/8/21.
9 | */
10 | public class RemoveDupLetttersTest {
11 |
12 | @Test
13 | public void test1() {
14 | RemoveDupLettters r = new RemoveDupLettters();
15 | System.out.println(r.removeDuplicateLetters("bcabc"));
16 | assert r.removeDuplicateLetters("bcabc").equals("abc");
17 | assert r.removeDuplicateLetters("cbacdcbc").equals("acdb");
18 | assert r.removeDuplicateLetters("bbcaac").equals("bac");
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/RemoveDuplicateTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/21.
7 | */
8 | public class RemoveDuplicateTest {
9 |
10 | @Test
11 | public void test1() {
12 | RemoveDuplicate r = new RemoveDuplicate();
13 | int[] nums = {1, 1, 2};
14 | assert r.removeDuplicates(nums) == 2;
15 | assert nums[0] == 1;
16 | assert nums[1] == 2;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/ReverseIntegerTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/20.
7 | */
8 | public class ReverseIntegerTest {
9 |
10 | @Test
11 | public void test1() {
12 | ReverseInteger r = new ReverseInteger();
13 | assert r.reverse(123) == 321;
14 | assert r.reverse(-123) == -321;
15 | assert r.reverse(1534236469) == 0;
16 | }
17 |
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/ReverseWordInStringTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/23.
7 | */
8 | public class ReverseWordInStringTest {
9 |
10 | @Test
11 | public void test1() {
12 | ReverseWordInString r = new ReverseWordInString();
13 | System.out.println(r.reverseWords("the sky is blue"));
14 | assert r.reverseWords("the sky is blue").equals("blue is sky the");
15 | assert r.reverseWords(" ").equals("");
16 | }
17 |
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/RomanToIntTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.HashMap;
6 | import java.util.Map;
7 |
8 | /**
9 | * Created by lipeng on 2016/8/22.
10 | */
11 | public class RomanToIntTest {
12 |
13 | @Test
14 | public void test1() {
15 | RomanToInt r = new RomanToInt();
16 | assert r.romanToInt("DCXXI") == 621;
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/SelfCrossingTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/20.
7 | */
8 | public class SelfCrossingTest {
9 |
10 | @Test
11 | public void test1() {
12 | SelfCrossing s = new SelfCrossing();
13 | assert s.isSelfCrossing(new int[] {2, 1, 1, 2}) == true;
14 | assert s.isSelfCrossing(new int[] {1, 2, 3, 4}) == false;
15 | assert s.isSelfCrossing(new int[] {1, 1, 1, 1}) == true;
16 | assert s.isSelfCrossing(new int[] {3, 3, 3, 2, 1, 1}) == false;
17 | assert s.isSelfCrossing(new int[] {3, 3, 2, 2, 1, 1}) == false;
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/SortColorTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.Arrays;
6 |
7 | /**
8 | * Created by lipeng on 2016/8/21.
9 | */
10 | public class SortColorTest {
11 |
12 | @Test
13 | public void test1() {
14 | SortColors s = new SortColors();
15 | int[] nums = {2, 2, 2, 1, 1, 1, 0, 0, 1, 2};
16 | s.sortColors(nums);
17 | System.out.println(Arrays.toString(nums));
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/SqrtTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/21.
7 | */
8 | public class SqrtTest {
9 |
10 | @Test
11 | public void test1() {
12 | Sqrt s = new Sqrt();
13 | // assert s.mySqrt(5) == 2;
14 | // assert s.mySqrt(1) == 1;
15 | System.out.println(s.mySqrt(5));
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/TrappingRainWaterTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/10.
7 | */
8 | public class TrappingRainWaterTest {
9 |
10 | @Test
11 | public void test1() {
12 | TrappingRainWater t = new TrappingRainWater();
13 | int[] nums = {0,1,0,2,1,0,1,3,2,1,2,1};
14 | assert t.trap(nums) == 6;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/Twitter2Test.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.*;
6 |
7 | /**
8 | * Created by lipeng on 2016/8/15.
9 | */
10 | public class Twitter2Test {
11 |
12 |
13 | @Test
14 | public void test1() {
15 | Twitter2 t = new Twitter2();
16 | t.postTweet(1, 5);
17 | List l = t.getNewsFeed(1);
18 | assert l.get(0) == 5;
19 | t.follow(1, 2);
20 | t.postTweet(2, 6);
21 | l = t.getNewsFeed(1);
22 | assert l.get(0) == 6;
23 | assert l.get(1) == 5;
24 | t.unfollow(1, 2);
25 | l = t.getNewsFeed(1);
26 | assert l.get(0) == 5;
27 | }
28 |
29 | @Test
30 | public void test2() {
31 | Twitter2 t = new Twitter2();
32 | System.out.println(t.getNewsFeed(1));
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/TwitterTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.*;
6 |
7 | /**
8 | * Created by lipeng on 2016/8/24.
9 | */
10 | public class TwitterTest {
11 |
12 | @Test
13 | public void test1() {
14 | Twitter t = new Twitter();
15 | t.postTweet(1, 5);
16 | System.out.println(t.getNewsFeed(1));
17 | t.follow(1, 2);
18 | t.postTweet(2, 6);
19 | System.out.println(t.getNewsFeed(1));
20 | t.unfollow(1, 2);
21 | System.out.println(t.getNewsFeed(1));
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/VerifyPreorderSerializationTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/17.
7 | */
8 | public class VerifyPreorderSerializationTest {
9 |
10 | @Test
11 | public void test() {
12 | VerifyPreorderSerialization v = new VerifyPreorderSerialization();
13 | assert v.isValidSerialization("9,3,4,#,#,1,#,#,2,#,6,#,#") == true;
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/amz/WordBreakTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.amz;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.HashSet;
6 | import java.util.Set;
7 |
8 | /**
9 | * Created by lipeng on 2016/8/11.
10 | */
11 | public class WordBreakTest {
12 |
13 | @Test
14 | public void test1() {
15 | Set dict = new HashSet<>();
16 | dict.add("leet");
17 | dict.add("code");
18 | WordBreak w = new WordBreak();
19 | assert w.wordBreak("leetcode", dict) == true;
20 | }
21 |
22 | @Test
23 | public void test2() {
24 | Set dict = new HashSet<>();
25 | dict.add("cat");
26 | dict.add("sat");
27 | dict.add("to");
28 | WordBreak w = new WordBreak();
29 | assert w.wordBreak("catsatto", dict) == true;
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/leetcode/CombinationSumIIITest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | import org.junit.Before;
4 | import org.junit.Test;
5 |
6 | import java.util.ArrayList;
7 | import java.util.Arrays;
8 | import java.util.LinkedList;
9 | import java.util.List;
10 |
11 | /**
12 | * Created by lipeng on 2016/3/23.
13 | */
14 | public class CombinationSumIIITest {
15 |
16 | CombinationSumIII c;
17 | List> list;
18 |
19 | @Before
20 | public void setUp() {
21 | c = new CombinationSumIII();
22 | }
23 |
24 | @Test
25 | public void test() {
26 | list = new ArrayList<>();
27 | list.add(new ArrayList<>(Arrays.asList(1, 2, 4)));
28 | assert c.combinationSum3(3, 7).equals(list);
29 | list = new ArrayList<>();
30 | list.add(new ArrayList<>(Arrays.asList(1, 2, 6)));
31 | list.add(new ArrayList<>(Arrays.asList(1, 3, 5)));
32 | list.add(new ArrayList<>(Arrays.asList(2, 3, 4)));
33 | assert c.combinationSum3(3, 9).equals(list);
34 | }
35 |
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/leetcode/ContainDuplicateTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | import org.junit.Before;
4 | import org.junit.Test;
5 |
6 | /**
7 | * Created by lipeng on 2016/3/23.
8 | */
9 | public class ContainDuplicateTest {
10 |
11 | ContainDuplicate c;
12 |
13 | @Before
14 | public void setUp() {
15 | c = new ContainDuplicate();
16 | }
17 |
18 | @Test
19 | public void test() {
20 | assert c.containsDuplicate(null) == false;
21 | assert c.containsDuplicate(new int[] {1}) == false;
22 | assert c.containsDuplicate(new int[] {1, 1}) == true;
23 | assert c.containsDuplicate(new int[] {1, 2, 1}) == true;
24 | assert c.containsDuplicate(new int[] {1, 2, 3}) == false;
25 | }
26 |
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/leetcode/MinSizeSumArrayTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | import org.junit.After;
4 | import org.junit.Before;
5 | import org.junit.Test;
6 |
7 | /**
8 | * Created by lipeng on 2016/3/25.
9 | */
10 | public class MinSizeSumArrayTest {
11 |
12 | MinSizeSumArray m;
13 |
14 | @Before
15 | public void setUp() {
16 | m = new MinSizeSumArray();
17 | }
18 |
19 | @Test
20 | public void test() {
21 | int[] nums = {3, 6, 2, 4, 6};
22 | assert m.minSubArrayLen(9, nums) == 2;
23 | assert m.minSubArrayLen(7, nums) == 2;
24 | assert m.minSubArrayLen(5, nums) == 1;
25 | assert m.minSubArrayLen(15, nums) == 4;
26 | assert m.minSubArrayLen(30, nums) == 0;
27 |
28 | nums = new int[] {1, 2, 3, 4, 5};
29 | assert m.minSubArrayLen(11, nums) == 3;
30 | }
31 |
32 | @After
33 | public void tearDown() {
34 | m = null;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/leetcode/RandomizedCollectionTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.*;
6 |
7 | /**
8 | * Created by lipeng on 2016/8/14.
9 | */
10 | public class RandomizedCollectionTest {
11 |
12 | @Test
13 | public void test1() {
14 | RandomizedCollection r = new RandomizedCollection();
15 | r.insert(1);
16 | r.insert(2);
17 | r.insert(2);
18 | r.insert(2);
19 | r.insert(1);
20 | r.insert(3);
21 | r.insert(3);
22 | r.remove(2);
23 | assert r.list.get(0) == 1;
24 | assert r.list.get(1) == 3;
25 | assert r.list.get(2) == 2;
26 | assert r.list.get(3) == 2;
27 | assert r.list.get(4) == 1;
28 | assert r.list.get(5) == 3;
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/leetcode/RandomizedSetTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.*;
6 |
7 | /**
8 | * Created by lipeng on 2016/8/14.
9 | * https://leetcode.com/problems/insert-delete-getrandom-o1/
10 | */
11 | public class RandomizedSetTest {
12 |
13 | @Test
14 | public void test1() {
15 | RandomizedSet r = new RandomizedSet();
16 | r.insert(0);
17 | r.insert(1);
18 | r.insert(2);
19 | r.insert(3);
20 | r.remove(3);
21 | assert r.list.get(0) == 0;
22 | assert r.list.get(1) == 1;
23 | assert r.list.get(2) == 2;
24 | r.remove(0);
25 | assert r.list.get(0) == 2;
26 | assert r.list.get(1) == 1;
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/leetcode/ScheduleCourseTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | import org.junit.Before;
4 | import org.junit.Test;
5 |
6 | /**
7 | * Created by lipeng on 2016/3/25.
8 | */
9 | public class ScheduleCourseTest {
10 |
11 | ScheduleCourse s;
12 |
13 | @Before
14 | public void setUp() {
15 | s = new ScheduleCourse();
16 | }
17 |
18 | @Test
19 | public void test() {
20 | int[][] courses = {
21 | {4, 2},
22 | {4, 3},
23 | {3, 0},
24 | {3, 1}
25 | };
26 | assert s.canFinish(5, courses) == true;
27 |
28 | courses = new int[][]{
29 | {0, 1},
30 | {1, 0}
31 | };
32 | assert s.canFinish(2, courses) == false;
33 |
34 | courses = new int[][]{};
35 | assert s.canFinish(2, courses);
36 | }
37 |
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/leetcode/ShortestPalindromeTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | import org.junit.Before;
4 | import org.junit.Test;
5 |
6 | import java.util.ArrayList;
7 | import java.util.Arrays;
8 | import java.util.List;
9 |
10 | /**
11 | * Created by lipeng on 2016/3/23.
12 | */
13 | public class ShortestPalindromeTest {
14 |
15 | ShortestPalindrome s;
16 |
17 | @Before
18 | public void setUp() {
19 | s = new ShortestPalindrome();
20 | }
21 |
22 | @Test
23 | public void test() {
24 | assert s.shortestPalindrome("").equals("");
25 | assert s.shortestPalindrome("aacecaaa").equals("aaacecaaa");
26 | assert s.shortestPalindrome("abcd").equals("dcbabcd");
27 | }
28 |
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/leetcode/WordDictionaryTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | import com.pli.project.algorithm.array.WordDistanceI;
4 | import org.junit.After;
5 | import org.junit.Before;
6 | import org.junit.Test;
7 |
8 | /**
9 | * Created by lipeng on 2016/3/23.
10 | */
11 | public class WordDictionaryTest {
12 |
13 | WordDictionary w;
14 |
15 | @Before
16 | public void setUp() {
17 | w = new WordDictionary();
18 | }
19 |
20 | @Test
21 | public void test1() {
22 | w.addWord("abcd");
23 | w.addWord("abc");
24 | assert w.search("abc") == true;
25 | assert w.search("abcd") == true;
26 | assert w.search("ab") == false;
27 | assert w.search("abcde") == false;
28 | assert w.search("ab.") == true;
29 | }
30 |
31 | @Test
32 | public void test2() {
33 | w.addWord("a");
34 | assert w.search(".") == true;
35 | }
36 |
37 | @After
38 | public void tearDown() {
39 | w = null;
40 | }
41 |
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/leetcode/l376WiggleSubsequenceTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | import org.junit.Test;
4 |
5 | /**
6 | * Created by lipeng on 2016/8/29.
7 | */
8 | public class l376WiggleSubsequenceTest {
9 |
10 | @Test
11 | public void test1() {
12 | l376WiggleSubsequence l = new l376WiggleSubsequence();
13 | assert l.wiggleMaxLength(new int[]{1,7,4,9,2,5}) == 6;
14 | assert l.wiggleMaxLength(new int[]{1,17,5,10,13,15,10,5,16,8}) == 7;
15 | assert l.wiggleMaxLength(new int[]{1,2,3,4,5,6,7,8,9}) == 2;
16 | assert l.wiggleMaxLength(new int[]{1,1}) == 1;
17 | assert l.wiggleMaxLength(new int[]{1,1, 1}) == 1;
18 | assert l.wiggleMaxLength(new int[]{1,2}) == 2;
19 | assert l.wiggleMaxLength(new int[]{3, 3, 3, 2, 5}) == 3;
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/leetcode/l43MultiplyTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.Arrays;
6 |
7 | /**
8 | * Created by lipeng on 2016/8/29.
9 | */
10 | public class l43MultiplyTest {
11 |
12 | @Test
13 | public void test1() {
14 | l43Multiply l = new l43Multiply();
15 | System.out.println(l.multiply("755", "48"));
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/leetcode/l49GroupAnagramTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.leetcode;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.ArrayList;
6 | import java.util.HashMap;
7 | import java.util.List;
8 |
9 | /**
10 | * Created by lipeng on 2016/8/12.
11 | */
12 | public class l49GroupAnagramTest {
13 |
14 | @Test
15 | public void test1() {
16 | l49GroupAnagram l = new l49GroupAnagram();
17 | String[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
18 | System.out.println(l.groupAnagrams(strs));
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/practice/AddTwoNumbersTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.practice;
2 |
3 | import com.pli.project.algorithm.leetcode.ListNode;
4 | import org.junit.Test;
5 |
6 | /**
7 | * Created by lipeng on 2016/8/10.
8 | */
9 | public class AddTwoNumbersTest {
10 |
11 |
12 |
13 | @Test
14 | public void test1() {
15 | AddTwoNumbers a = new AddTwoNumbers();
16 | ListNode l11 = new ListNode(2);
17 | ListNode l12 = new ListNode(4);
18 | ListNode l13 = new ListNode(3);
19 | l11.next = l12; l12.next = l13;
20 | ListNode l21 = new ListNode(5);
21 | ListNode l22 = new ListNode(6);
22 | ListNode l23 = new ListNode(4);
23 | l21.next = l22; l22.next = l23;
24 | ListNode l = a.addTwoNumbers(l11, l21);
25 | assert l.val == 7 && l.next.val == 0 && l.next.next.val == 8;
26 | System.out.println(l);
27 | }
28 | }
29 |
30 |
31 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/practice/BinarySearchTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.practice;
2 |
3 | import com.pli.project.algorithm.tree.BinaryIndexedTree;
4 | import org.junit.Test;
5 |
6 | import java.util.ArrayList;
7 | import java.util.List;
8 |
9 | /**
10 | * Created by lipeng on 2015/12/12.
11 | */
12 | public class BinarySearchTest {
13 |
14 | @Test
15 | public void test1() {
16 | BinarySearch b = new BinarySearch();
17 | int[] nums = {1, 2, 3, 5, 6};
18 | assert b.findLeftInclusive(nums, 3) == 2;
19 | assert b.findLeftInclusive(nums, 4) == 2;
20 | assert b.findLeftInclusive(nums, 1) == 0;
21 | assert b.findLeftInclusive(nums, 0) == -1;
22 | assert b.findLeftInclusive(nums, 6) == 4;
23 | assert b.findLeftInclusive(nums, 7) == 4;
24 | }
25 |
26 |
27 | }
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/practice/LinkedListCycleIITest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.practice;
2 |
3 | import com.pli.project.algorithm.leetcode.ListNode;
4 | import org.junit.Test;
5 |
6 | /**
7 | * Created by lipeng on 2016/8/12.
8 | */
9 | public class LinkedListCycleIITest {
10 |
11 | @Test
12 | public void test1() {
13 | ListNode l1 = new ListNode(1);
14 | l1.next = l1;
15 | LinkedListCycleII l = new LinkedListCycleII();
16 | assert l.detectCycle(l1) == l1;
17 | }
18 |
19 | public ListNode detectCycle(ListNode head) {
20 | ListNode slow = head, fast = head;
21 | while (fast != null && fast.next != null) {
22 | slow = slow.next;
23 | fast = fast.next.next;
24 | }
25 | if (fast == null || fast.next == null) {
26 | return null;
27 | }
28 | while (slow != fast) {
29 | slow = slow.next;
30 | fast = fast.next;
31 | }
32 | return fast;
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/src/test/java/com/pli/project/algorithm/recursion/WildCardMatchTest.java:
--------------------------------------------------------------------------------
1 | package com.pli.project.algorithm.recursion;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.assertFalse;
6 | import static org.junit.Assert.assertTrue;
7 |
8 | /**
9 | * Created by lipeng on 2015/11/1.
10 | */
11 | public class WildCardMatchTest {
12 |
13 | @Test
14 | public void testCase1(){
15 | assertTrue(WildCardMatch.matchReg("aa", "aa"));
16 | assertTrue(WildCardMatch.matchReg("aa", "a*"));
17 | assertFalse(WildCardMatch.matchReg("aaa", "aa"));
18 | assertTrue(WildCardMatch.matchReg("aa", ".*"));
19 | assertTrue(WildCardMatch.matchReg("ab", ".*"));
20 | assertFalse(WildCardMatch.matchReg("aab", "c*a*b"));
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------