├── .gitignore ├── 01Matrix ├── 01Matrix.cpp └── 01Matrix.java ├── 1bitAnd2bitChar └── 1bitAnd2bitChar.cpp ├── 24Game └── 24Game.cpp ├── 2KeysKeyboard ├── 2Keyskeyboard.cpp └── 2Keyskeyboard.java ├── 3Sum ├── 3Sum.cpp └── 3Sum.java ├── 3SumClosest └── 3SumClosest.cpp ├── 3SumSmaller └── 3SumSmaller.cpp ├── 4Sum └── 4Sum.cpp ├── 4keysKeyboard └── 4keysKeyboard.cpp ├── DesignSkiplist └── designSkiplist.java ├── JewelsAndStones ├── JewelsAndStones.cpp └── JewelsAndStones.java ├── LFUCache └── LFUCache.cpp ├── LRUCache ├── LRUCache.cpp ├── LRUCache.java ├── LRUCache2.cpp └── LRUCache3.cpp ├── Leetcode.iml ├── N-Queens ├── nQueens.cpp ├── nQueens.java ├── nQueens_firstIdea.java └── nQueens_firstIdea_improve.java ├── README.md ├── accountsMerge ├── accountsMerge_dfs.cpp └── accountsMerge_unionfind.cpp ├── addAndSearchWord ├── addAndSearchWord.cpp ├── addAndSearchWord.java └── addAndSearchWord_2.cpp ├── addBinary ├── addBinary.cpp └── addBinary2.cpp ├── addBoldTagInString ├── addBoldTagInString.cpp └── addBoldTagInString_faster.cpp ├── addDigits └── addDigits.cpp ├── addOneRowToTree └── addOneRowTree.cpp ├── addStrings └── addStrings.cpp ├── addTwoNumbers ├── addTwoNumbers.cpp └── addTwoNumbers.java ├── addTwoNumbersII └── addTwoNumbersII.cpp ├── additiveNumber └── additiveNumber.cpp ├── alienDictionary ├── alienDictionary.cpp └── alienDictionary_2.cpp ├── ambiguousCoordinates └── ambiguousCoordinates.cpp ├── androidUnlockPatterns └── androidUnlockPatterns.cpp ├── arithmeticSlices └── arithmeticSlices.cpp ├── arrangingCoins └── arrangingCoins.cpp ├── arrayPartitionI └── arrayPartition1.cpp ├── assignCookies └── assignCookies.cpp ├── asteroidCollision ├── asteroidCollision.cpp └── asteroidCollision.java ├── averageOfLevelsInBinaryTree └── averageOfLevelsInBinaryTree.cpp ├── backspaceStringCompare ├── backspaceStringCompare.cpp └── backspaceStringCompare_2.cpp ├── balancedBinaryTree ├── balancedBinaryTree.cpp ├── balancedBinaryTree.java └── balancedBinaryTree2.cpp ├── base7 └── base7.cpp ├── baseballGame └── baseballGame.cpp ├── basicCalculator ├── basicCalculator.cpp ├── basicCalculator_opstack.cpp └── basicCalculator_recursion.cpp ├── basicCalculatorII ├── basicCalculatorII.cpp ├── basicCalculatorII_nostack.cpp └── basicCalculatorII_opstack.cpp ├── basicCalculatorIII ├── basicCalculatorIII.cpp └── basicCalculatorIII_opstack.cpp ├── beautifulArrangement └── beautifulArrangement.cpp ├── beautifulArrangementII └── beautifulArrangementII.cpp ├── bestTimeToBuyAndSellStockIII └── bestTimeToBuyAndSellStockIII.cpp ├── bestTimeToBuyAndSellStockIV ├── bestTimeToBuyAndSellStockIV.cpp ├── bestTimeToBuyAndSellStockIV_1.cpp └── bestTimeToBuyAndSellStockIV_2.cpp ├── bestTimeToBuyAndSellStockWithCooldown └── bestTimeToBuyAndSellStockWithCooldown.cpp ├── bestTimeToBuyAndSellStockWithTransactionFee ├── bestTimeToBuyAndSellStockWithTransactionFee.cpp └── bestTimeToBuyAndSellStockWithTransactionFee.java ├── bestTimeToBuyandSellStock └── bestTimeToBuyAndSellStock.cpp ├── bestTimeToBuyandSellStock2 ├── bestTimeToBuyandSellStock2.cpp └── bestTimeToBuyandSellStock2_1.cpp ├── bigCountries └── bigCountries.cpp ├── binaryGap └── binaryGap.cpp ├── binaryNumberWithAlternatingBits └── binaryNumberWithAlternatingBits.cpp ├── binarySearchTreeIterator ├── binaryTreeSearchIterator.cpp ├── binaryTreeSearchIterator.java └── binaryTreeSearchIterator_2.cpp ├── binaryTreeInorderTraversal ├── binaryTreeInorderTraversal.cpp ├── binaryTreeInorderTraversal.java └── binaryTreeInorderTraversal2.cpp ├── binaryTreeLevelOrderTraversal ├── binaryTreeLevelOrderTraversal.cpp ├── binaryTreeLevelOrderTraversal.java └── binaryTreeLevelOrderTraversalII.java ├── binaryTreeLevelOrderTraversalII ├── binaryTreeLevelOrderTraversalII.cpp └── binaryTreeLevelOrderTraversalII.java ├── binaryTreeLongestConsecutiveSequence ├── binaryTreeLongestConsecutiveSequence_dfs.cpp └── binaryTreeLongestConsecutiveSequence_recursion.cpp ├── binaryTreeLongestConsecutiveSequenceII └── binaryTreeLongestConsecutiveSequenceII.cpp ├── binaryTreeMaximumPathSum ├── binaryTreeMaximumPathSum.cpp ├── binaryTreeMaximumPathSum.java └── binaryTreeMaximumPathSum_2.cpp ├── binaryTreePaths └── binaryTreePaths.cpp ├── binaryTreePostorderTraversal ├── binaryTreePostorderTraversal.cpp ├── binaryTreePostorderTraversal.java ├── binaryTreePostorderTraversal2.cpp └── binaryTreePostorderTraversal3.cpp ├── binaryTreePreorderTraversal ├── binaryTreePreorderTraversal.cpp ├── binaryTreePreorderTraversal.java ├── binaryTreePreorderTraversal2.cpp ├── binaryTreePreorderTraversal3.cpp └── binaryTreePreorderTraversal_recursion.cpp ├── binaryTreeRightSideView └── binaryTreeRightSideView.cpp ├── binaryTreeTilt └── binaryTreeTilt.cpp ├── binaryTreeUpsideDown └── binaryTreeUpsideDown.cpp ├── binaryTreeVerticalOrderTraversal ├── binaryTreeVerticalOrderTraversal.cpp └── binaryTreeVerticalOrderTraversal_2.cpp ├── binaryTreeZigzagOrderTraversal ├── binaryTreeZigzagLevelOrderTraversal.cpp └── binaryTreeZigzagLevelOrderTraversal.java ├── binaryWatch └── binaryWatch.cpp ├── boldWordsInString ├── boldWordsInString.cpp └── boldWordsInString_2.cpp ├── bombEnemy ├── bombEnemy.cpp └── bombEnemy2.cpp ├── boundaryOfBinaryTree ├── boundaryOfBinaryTree.cpp └── boundaryOfBinaryTree2.cpp ├── brickWall └── brickWall.cpp ├── bricksFallingWhenHit └── bricksFallingWhenHit.cpp ├── buddyStrings └── buddyStrings.cpp ├── bulbSwitcher └── bulbSwitcher.cpp ├── bulbSwitcherII └── bulbSwitcherII.cpp ├── bulbSwitcherIII ├── bulbSwitcherIII.java └── bulbSwitcherIII_unionFind.java ├── bullsAndCows └── bullsAndCows.cpp ├── burstBalloons ├── burstBalloons.cpp ├── burstBalloons.java ├── burstBalloons2.cpp └── burstBalloons_bruteforce.cpp ├── busRoutes └── busRoutes.cpp ├── canIWin ├── canIWin.cpp ├── canIWin.java ├── canIWin_naive.java └── canIWin_opt.java ├── canPlaceFlowers └── canPlaceFlowers.cpp ├── candy └── candy.cpp ├── carFleet └── carFleet.cpp ├── cheapestFlightsWithinKStops └── cheapestFlightsWithinKStops.cpp ├── classesMoreThan5Students └── classesMoreThan5Students ├── climbingStairs └── climbingStairs.cpp ├── cloneGraph ├── cloneGraph.cpp ├── cloneGraph.java ├── cloneGraph2.cpp └── cloneGraph3.cpp ├── closestBSTValue ├── closestBSTValue.cpp ├── closestBSTValue2.cpp └── closestBSTValue3.cpp ├── closestBSTValueII ├── closestBSTValueII.cpp └── closestBSTValueII_2.cpp ├── closestLeafInABinaryTree └── closestLeafInABinaryTree.cpp ├── coinChange ├── coinChange.cpp └── coinChange.java ├── coinChangeII ├── coinChangeII.cpp ├── coinChangeII.java └── coinChangeII_2.cpp ├── combinationSum ├── combinationSum.cpp └── combinationSum.java ├── combinationSumII ├── combinationSumII.cpp └── combinationSumII.java ├── combinationSumIII └── combinationSumIII.cpp ├── combinationSumIV ├── combinationSumIV.cpp └── combinationSumIV.java ├── combinations └── combinations.cpp ├── combineTwoTables └── combineTwoTables ├── compareVersionNumbers ├── compareVersionNumbers.cpp ├── compareVersionNumbers1.cpp └── compareVersionNumbers2.cpp ├── complexNumberMultiplication └── complexNumberMultiplication.cpp ├── consecutiveNumbers └── consecutiveNumbers ├── constructBinaryTreeFromInorderAndPostorder ├── constructBinaryTreeFromInorderAndPostorderTraversal.cpp └── constructBinaryTreeFromInorderAndPostorderTraversal.java ├── constructBinaryTreeFromPreorderAndInorder └── constructBinaryTreFromPreorederAndInorderTraversal.cpp ├── constructBinaryTreeFromString └── constructBinaryTreeFromString.cpp ├── constructStringFromBinaryTree ├── constructStringFromBinaryTree.cpp └── constructStringFromBinaryTree.java ├── constructTheRectangle └── constructTheRectangle.cpp ├── containerWithMostWater └── containerWithMostWater.cpp ├── containsDup2 └── containsDup2.cpp ├── containsDuplicate └── containsDup.cpp ├── contiguousArray └── contiguousArray.cpp ├── continuousSubarraySum └── continuousSubarraySum.cpp ├── convertBSTtoGreaterTree └── convertBSTtoGreaterTree.cpp ├── convertBSTtoSortedDoubleLinkedlist ├── convertBSTtoSortedDoubleLinkedlist.cpp └── convertBSTtoSortedDoubleLinkedlist_2.cpp ├── convertBinaryNumberInLinkedListToInteger └── convertBinaryNumberInLinkedListToInteger.cpp ├── convertSortedArrayToBinarySearchTree ├── convertSortedArrayToBinarySearchTree.cpp └── convertSortedArrayToBinarySearchTree.java ├── convertSortedListToBST ├── convertSortedListToBST.cpp └── convertSortedListToBST_delete.cpp ├── convertaNumberToHexadecimal └── convertANumberToHexadecimal.cpp ├── convexPolygon └── convexPolygon.cpp ├── copyListWithRandomPointer └── copyListWithRandomPointer.cpp ├── countAndSay └── countAndSay.cpp ├── countBinarySubstrings └── countBinarySubstrings.cpp ├── countCompleteTreeNodes └── countCompleteTreeNodes.cpp ├── countDaysWithoutMeetings └── countDaysWithoutMeetings.java ├── countNumbersWithUniqueDigits └── countNumbersWithUniqueDigits.cpp ├── countOfRangeSum └── countOfRangeSum.cpp ├── countOfSmallerNumbersAfterSelf ├── countOfSmallerNumbersAfterSelf.cpp ├── countOfSmallerNumbersAfterSelf.java ├── countOfSmallerNumbersAfterSelf2.cpp └── countOfSmallerNumbersAfterSelfII.cpp ├── countPairsThatFormACompleteDayI └── countPairsThatFormACompleteDayI.java ├── countPairsThatFormACompleteDayII └── countPairsThatFormACompleteDayII.java ├── countPrimes └── countPrimes.cpp ├── countSubmatricesWithEqualFrequencyOfXandY └── countSubmatricesWithEqualFrequencyOfXandY.java ├── countingBits └── countingBits.cpp ├── courseSchedule ├── courseSchedule.cpp ├── courseSchedule.java ├── courseSchedule_adjacentList.cpp └── courseSchedule_adjacentList.java ├── courseScheduleII ├── courseScheduleII.cpp ├── courseScheduleII.java └── courseScheduleII_list.java ├── crackingTheSafe └── crackingTheSafe.cpp ├── createMaximumNumber └── createMaximumNumber.cpp ├── customersWhoNeverOrder └── customersWhoNeverOrder ├── cutOffTreesForGolfEvent ├── cutOffTreesForGolfEvent.cpp └── cutOffTreesForGolfEvent.java ├── dailyTemperatures └── dailyTemperatures.cpp ├── decodeString ├── decodeString.cpp └── decodeString_recursion.cpp ├── decodeWays ├── decodeWays.cpp └── decodeWays.java ├── decodeWaysII ├── decodeWaysII.cpp └── decodeWaysII_rollingArray.cpp ├── defangingAnIPAddress └── defangingAnIPAddress.cpp ├── degreeOfanArray └── degreeOfanArray.cpp ├── deleteDupEmails └── deleteDupEmails ├── deleteNodeInALinkedlist ├── deleteNodeInALinkedList.cpp └── deleteNodeInALinkedList_1.cpp ├── deleteNodeInaBST └── deleteNodeInaBST.cpp ├── deleteOperationForTwoStrings ├── deleteOperationForTwoStrings.cpp ├── deleteOperationForTwoStrings.java └── deleteOperationForTwoStrings_2.cpp ├── departmentHighestSalary └── departmentHighestSalary ├── designCompressedStringIterator ├── designCompressedStringIterator.cpp └── designCompressedStringIterator2.cpp ├── designHitCounter ├── designHitCounter.cpp ├── designHitCounter2.cpp ├── designHitCounter3.cpp └── designHitCounter4.cpp ├── designPhoneDirectory └── designPhoneDirectory.cpp ├── designSearchAutocompleteSystem └── designSearchAutocompleteSystem.cpp ├── designSnakeGame ├── designSnakeGame.cpp └── designSnakeGame_2.cpp ├── designTicTacToe └── designTicTacToe.cpp ├── designTwitter └── designTwitter.cpp ├── detectCapital ├── detectCapital.cpp └── detectCapital2.cpp ├── diagonalTraverse └── diagonalTraverse.cpp ├── diameterOfBinaryTree └── diameterOfBinaryTree.cpp ├── distributeCandies └── distributeCandies.cpp ├── divideTwoIntegers └── divideTwoIntegers.cpp ├── dominoAndTrominoTiling ├── dominoAndTrominoTiling.cpp └── dominoAndTrominoTiling_2.cpp ├── dungeonGame ├── dungeonGame.cpp └── dungeonGame.java ├── duplicateEmails └── duplicateEmails ├── editDistance ├── editDistance.cpp └── editDistance.java ├── employeeImportance ├── employeeImportance.cpp └── employeeImportance.java ├── employeesEarningMoreThanTheirManagers └── employeesEarnMoreThanTheirManagers ├── encodeAndDecodeStrings └── encodeAndDecodeStrings.cpp ├── encodeAndDecodeTinyURL └── encodeAndDecodeTinyURL.cpp ├── equalTreePartition └── equalTreePartition.cpp ├── escapeTheGhosts └── escapeTheGhosts.cpp ├── evaluateDivision ├── evaluateDivision.cpp ├── evaluateDivision.java └── evaluateDivision_2.cpp ├── evaluateReversePolishNotation └── evaluateReversePolishNotation.cpp ├── examRoom ├── examRoom.cpp └── examRoom2.cpp ├── excelSheetColumnNumber └── excelSheetColumnNumber.cpp ├── excelSheetColumnTitle └── excelSheetColumnTitle.cpp ├── exclusiveTimeOfFunctions ├── exclusiveTimeOfFunctions.cpp └── exclusiveTimeOfFunctions2.cpp ├── expressionAddOperators └── expressionAddOperators.cpp ├── expressiveWords ├── expressiveWords.cpp └── expressiveWords.java ├── factorCombinations ├── factorCombinations.cpp └── factorCombinations_2.cpp ├── factorialTrailingZeroes └── factorialTrailingZeroes.cpp ├── fibonacciNumber └── fibonacciNumber.cpp ├── findAllAnagramsInaString ├── findAllAnagramsInastring.cpp └── findAllAnagramsInastring.java ├── findAllDuplicatesInAnArray └── findAllDuplicatesInAnArray.cpp ├── findAllNumDisappearedInArray └── findAllNumDisappearedInArray.cpp ├── findAnagramMappings ├── findAnagramMappings.cpp └── findAnagramMappings.java ├── findAndReplaceInString └── findAndReplaceInString.cpp ├── findAndReplacePattern └── findAndReplacePattern.cpp ├── findBottomLeftTreeValue └── findBottomLeftTreeValue.cpp ├── findDuplicateFileInSystem └── findDuplicateFileInSystem.cpp ├── findDuplicateSubtrees ├── findDuplicateSubtrees.cpp └── findDuplicateSubtrees.java ├── findEventualSafeStates ├── findEventualSafeStates.cpp └── findEventualSafeStates.java ├── findFirstAndLastPositionOfElementInSortedArray ├── findFirstAndLastPositionOfElementInSortedArray.cpp ├── findFirstAndLastPositionOfElementInSortedArray.java └── searchForARange2.cpp ├── findKClosestElements ├── findKClosestElements.cpp ├── findKClosestElements.java └── findKClosestElements_binarysearch.cpp ├── findKPairsWithSmallestSums ├── findKPairsWithSmallestSums.cpp └── findKPairsWithSmallestSums.java ├── findLargestValueInEachTreeRow └── findLargestValueInEachTreeRow.cpp ├── findLeavesofBinaryTree └── findLeavesofBinaryTree.cpp ├── findMedianFromDataStream ├── findMedianFromDataStream.cpp ├── findMedianFromDataStream.java └── findMedianFromDataStream_2.cpp ├── findMinimumInRotatedSortedArray ├── findMinimumInRotatedSortedArray.cpp ├── findMinimumInRotatedSortedArray.java └── findMinimumInRotatedSortedArray2.cpp ├── findMinimumInRotatedSortedArrayII ├── findMinimumInRotatedSortedArrayII.cpp ├── findMinimumInRotatedSortedArrayII.java └── findMinimumInRotatedSortedArrayII2.cpp ├── findModeInBinarySearchTree ├── findModeInBinarySearchTree.cpp └── findModeInBinarySearchTree.java ├── findNumberOfWaysToReachTheK-thStair └── FindNumberOfWaysToReachTheK-thStair.java ├── findPeakElement ├── findPeakElement.cpp └── findPeakElement.java ├── findPermutation └── findPermutation.cpp ├── findPivotIndex └── findPivotIndex.cpp ├── findRightInterval ├── findRightInterval.cpp └── findRightInterval.java ├── findSmallestLetterGreaterThanTarget ├── findSmallestLetterGreaterThanTarget.cpp └── findSmallestLetterGreaterThanTarget.java ├── findSubarrayWithBitwiseORClosestToK └── findSubarrayWithBitwiseORClosestToK.java ├── findTheCelebrity └── findTheCelebrity.cpp ├── findTheChildWhoHasTheBallAfterKSeconds └── findTheChildWhoHasTheBallAfterKSeconds.java ├── findTheDifference ├── findTheDifference.cpp └── findTheDifference2.cpp ├── findTheDistanceValueBetweenTwoArrays ├── findTheDistanceValueBetweenTwoArrays.cpp ├── findTheDistanceValueBetweenTwoArrays_binarySearch.cpp └── findTheDistanceValueBetweenTwoArrays_binarySearch.java ├── findTheDuplicateNumber ├── findTheDuplicateNumber.cpp └── findTheDuplicateNumber_2.cpp ├── findTheMaximumLengthOfValidSubsequenceI └── findTheMaximumLengthOfValidSubsequenceI.java ├── findTheMaximumLengthOfValidSubsequenceII └── findTheMaximumLengthOfValidSubsequenceII.java ├── findTheMinimumAreaToCoverAllOnesI └── findTheMinimumAreaToCoverAllOnesI.java ├── findTheNthValueAfterKSeconds └── findTheNthValueAfterKSeconds.java ├── firstBadVersion ├── firstBadVersion.cpp └── firstBadVersion.java ├── firstMissingPositive └── firstMissingPositive.cpp ├── firstUniqueCharacterInaString └── firstUniqueCharacterInaString.cpp ├── fizzBuzz └── fizzBuzz.cpp ├── flatten2DVector └── flatten2DVector.cpp ├── flattenBinaryTreeToLinkedList ├── flattenBinaryTreeToLinkedList.cpp ├── flattenBinaryTreeToLinkedList.java ├── flattenBinaryTreeToLinkedList2.cpp ├── flattenBinaryTreeToLinkedList3.cpp └── flattenBinaryTreeToLinkedList4.cpp ├── flattenNestedListIterator └── flattenNestedListIterator.cpp ├── flipGame └── flipGame.cpp ├── flipGameII └── flipGameII.cpp ├── flippingAnImage └── flippingAnImage.cpp ├── floodfill ├── floodfill.cpp └── floodfill_bfs.cpp ├── fractionAdditionAndSubtraction └── fractionAdditionAndSubtraction.cpp ├── fractionToRecurringDecimal ├── fractionToRecurringDecimal.cpp └── fractionToRecurringDecimal.java ├── friendCircles └── friendCircles.cpp ├── frogJump ├── frogJump.cpp ├── frogJump.java └── frogJump_map.cpp ├── gameOfLife └── gameOfLife.cpp ├── gasStation └── gasStation.cpp ├── generalizedAbbreviation └── generalizedAbbreviation.cpp ├── generateBinaryStringsWithoutAdjacentZeros └── generateBinaryStringsWithoutAdjacentZeros.java ├── generateParentheses ├── generateParentheses.cpp └── generateParentheses_2.cpp ├── graphValidTree ├── graphValidTree_bfs.cpp ├── graphValidTree_bfs_easy.cpp ├── graphValidTree_dfs.cpp └── graphValidTree_unionfind.cpp ├── grayCode └── grayCode.cpp ├── groupAnagrams ├── groupAnagrams.cpp └── groupAnagrams_2.cpp ├── groupShiftedStrings └── groupShiftedStrings.cpp ├── guessNumberHigherOrLower └── guessNumberHigerOrLower.cpp ├── guessNumberHigherOrLowerII ├── guessNumberHigherOrLowerII.cpp └── guessNumberHigherOrLowerII.java ├── guessTheWord └── guessTheWord.cpp ├── hIndex ├── hIndex.cpp └── hIndex2.cpp ├── hIndexII ├── hIndexII.cpp └── hIndexII.java ├── hammingDistance └── hanmmingDistance.cpp ├── handOfStraights ├── handOfStraights.cpp └── handOfStraights_2.cpp ├── happyNumber └── happyNumber.cpp ├── heaters └── heaters.cpp ├── highFive └── highFive.cpp ├── houseRobber ├── houseRobber.cpp ├── houseRobber.java ├── houseRobber3.cpp ├── houseRobber_2.cpp └── houseRobber_2.java ├── houseRobberII ├── houseRobberII.cpp └── houseRobberII.java ├── houseRobberIII ├── houseRobberIII.cpp └── houseRobberIII.java ├── howManyNumberAreSmallerThanTheCurrentNumber ├── howManyNumberAreSmallerThanTheCurrentNumber_arrHash.java └── howManyNumberAreSmallerThanTheCurrentNumber_lowerbound.java ├── imageOverlap └── imageOverlap.cpp ├── imageSmoother └── imageSmoother.cpp ├── implementMagicDictionary └── implementMagicDictionary.cpp ├── implementQueueUsingStacks ├── implementQueueUsingStacks.cpp └── implementQueueUsingStacks_1.cpp ├── implementStackUsingQueues └── implementStackUsingQueues.cpp ├── implementStrStr ├── implementStrStr.cpp └── implementStrStr2.cpp ├── implementTire └── implementTire.cpp ├── increasingSubsequences └── increasingSubsequence.cpp ├── increasingTripletSubsequence ├── increasingTripletSubsequence.cpp └── increasingTripletSubsequence_2.cpp ├── inorderSuccessorInBST ├── inorderSuccessorInBST.cpp ├── inorderSuccessorInBST2.cpp └── inorderSuccessorInBST3.cpp ├── insertDeleteGetRandom └── insertDeleteGetRandom.cpp ├── insertInterval └── insertInterval.cpp ├── insertIntoACyclicSortedList └── insertIntoACyclicSortedList.cpp ├── insertionSortList └── insertSortList.cpp ├── integerBreak └── integerBreak.cpp ├── integerReplacement └── integerReplacement.cpp ├── integerToEnglishWords └── integerToEnglishWords.cpp ├── integerToRoman └── integerToRoman.cpp ├── intersectionOfTwoArrays └── intersectionOfTwoArrays.cpp ├── intersectionOfTwoArraysII └── intersectionOfTwoArraysII.cpp ├── intersectionOfTwoLinkedLists └── intersectionOfTwoLinkedLists.cpp ├── invertBinaryTree ├── invertBinaryTree.cpp └── invertBinaryTree.java ├── isGraphBipartite ├── isGraphBipartite.cpp ├── isGraphBipartite.java └── isGraphBipartite_2.java ├── isSubsequence └── isSubsequence.cpp ├── islandPerimeter └── islandPerimeter.cpp ├── isomorphicStrings ├── isomorphicStrings.cpp └── isomorphicStrings_2.cpp ├── judgeRouteCircle └── judgeRouteCircle.cpp ├── jumpGame ├── jumpGame.cpp └── jumpGame_2.cpp ├── kClosestPointsToOrign └── kClosestPointsToOrign.cpp ├── kEmptySlots ├── kEmptySlots.cpp └── kEmptySlots2.cpp ├── kdiffPairsInArray ├── kdiffPairsInArray.cpp └── kdiffPairsInArray.java ├── keyboardRow └── keyboardRow.cpp ├── killProcess └── killProcess.cpp ├── knightProbabilityInChessboard └── knightProbabilityInChessboard.cpp ├── kthLargestElementInAStream └── kthLargestElementInAStream.cpp ├── kthLargestElementInAnArray ├── kthLargestElementInAnArray.cpp ├── kthLargestElementInAnArray.java ├── kthLargestElementInAnArray_2.cpp └── kthLargestElementInAnArray_3.cpp ├── kthSmallestElementInABST └── kthSmallestElementInaBST.cpp ├── kthSmallestElementInASortedMatrix ├── kthSmallestElementInASortedMatrix.cpp ├── kthSmallestElementInASortedMatrix.java ├── kthSmallestElementInASortedMatrix_1.cpp ├── kthSmallestElementInASortedMatrix_2.cpp ├── kthSmallestElementInASortedMatrix_3.cpp └── kthSmallestElementInASortedMatrix_pq.java ├── kthSymbolInGrammar ├── kthSymbolInGrammar.cpp └── kthSymbolInGrammar.java ├── largestBSTSubtree └── largestBSTSubtree.cpp ├── largestDivisibleSubset ├── largestDivisibleSubset.cpp └── largestDivisibleSubset.java ├── largestNumber └── largestNumber.cpp ├── largestNumberAtLeastTwiceOfOthers ├── largestNumberAtLeastTwiceOfOthers.cpp └── largestNumberAtLeastTwiceOfOthers2.cpp ├── largestPalindromeProduct └── largestPalindromeProduct.cpp ├── largestPlusSign ├── largestPlusSign.cpp ├── largestPlusSign.java └── largestPlusSign_2.cpp ├── largestRectangleInHistogram └── largestRectangleInHistogram.cpp ├── largestSumOfAverages ├── largestSumOfAverages.cpp └── largestSumOfAverages.java ├── largestTriangleArea └── largestTriangleArea.cpp ├── lengthOfLastWord └── lengthOfLastWord.cpp ├── letterCombinationsOfAPhoneNumber ├── letterCombinations.cpp ├── letterCombinations_dfs.cpp └── letterCombinations_dfs.java ├── lexicographicallyMinimumStringAfterRemovingStars └── LexicographicallyMinimumStringAfterRemovingStars.java ├── licenseKeyFormatting └── licenseKeyFormatting.cpp ├── lineReflection ├── lineReflection.cpp ├── lineReflection_2.cpp └── lineReflection_3.cpp ├── linkedListCycle ├── LinkedListCycle.java └── linkedListCycle.cpp ├── linkedListCycleII └── linkedListCycleII.cpp ├── linkedListRandomNode └── linkedListRandomNode.cpp ├── linkedlistComponents └── linkedlistComponents.cpp ├── loggerRateLimiter ├── loggerRateLimiter.cpp └── loggerRateLimiter.java ├── lonelyPixelI └── lonelyPixelI.cpp ├── lonelyPixelII └── lonelyPixelII.cpp ├── longestAbsoluteFilePath ├── longestAbsoluteFilePath.cpp ├── longestAbsoluteFilePath.java ├── longestAbsoluteFilePath_2.cpp └── longestAbsoluteFilePath_3.cpp ├── longestCommonPrefix └── longestCommonPrefix.cpp ├── longestConsecutiveSequence ├── longestConsecutiveSequence.cpp └── longestConsecutiveSequence_unionfind.cpp ├── longestContinuousIncreasingSubsequence ├── longestContinuousIncreasingSubsequence.cpp └── longestContinuousIncreasingSubsequence.java ├── longestHarmoniousSubsequence └── longestHarmoniousSubsequence.cpp ├── longestIncreasingPathInAMatrix ├── longestIncreasingPathInAMatrix.cpp └── longestIncreasingPathInAMatrix_2.cpp ├── longestIncreasingSubsequence ├── longestIncreasingSubsequence.cpp ├── longestIncreasingSubsequence_nlogn.cpp └── longestIncreasingSubsequence_nlogn.java ├── longestLineOfConsecutiveOneInMatrix └── longestLineOfConsecutiveOneInMatrix.cpp ├── longestPalindrome └── longestPalindrome.cpp ├── longestPalindromicSubsequence ├── longestPalindromicSubsequence.cpp └── longestPalindromicSubsequence.java ├── longestPalindromicSubstring ├── longestPalinadromicSubstring.cpp ├── longestPalinadromicSubstring.java └── longestPalinadromicSubstring2.cpp ├── longestSubstringWithAtLeastKRepeatingCharaters └── longestSubstringWithAtLeastKRepeatingCharacters.cpp ├── longestSubstringWithAtMostKDistinctCharaters ├── longestSubstringWithAtMostKDistinctCharacters.cpp └── longestSubstringWithAtMostKDistinctCharacters_cnt.cpp ├── longestSubstringWithAtMostTwoDistinctCharaters ├── longestSubstringWithAtMostTwoDistinctCharacters.cpp └── longestSubstringWithAtMostTwoDistinctCharacters_cnt.cpp ├── longestSubstringWithoutRepeatingCharacters ├── longestSubstringWithoutRepeatingCharacters.java ├── longestSubstringWithoutRepeatingCharacters1.cpp ├── longestSubstringWithoutRepeatingCharacters2.cpp ├── longestSubstringWithoutRepeatingCharacters3.cpp └── myStack.cpp ├── longestUncommonSubsequenceI └── longestUncommonSubsequenceI.cpp ├── longestUncommonSubsequenceII ├── longestUncommonSubsequenceII.cpp └── longestUncommonSubsequenceII.java ├── longestUnivaluePath ├── longestUnivaluePath.cpp ├── longestUnivaluePath.java ├── longestUnivaluePath_2.cpp └── longestUnivaluePath_3.cpp ├── longestWordInDictionary ├── longestWordInDictionary.cpp ├── longestWordInDictionary.java ├── longestWordInDictionary_sorting.cpp └── longestWordInDictionary_trie.cpp ├── longestWordInDictionaryThroughDeleting ├── longestWordInDicThroughDeleting.cpp ├── longestWordInDicThroughDeleting.java └── longestWordInDicThroughDeleting2.cpp ├── lowestCommonAncestorOfABinarySearchTree ├── lowestCommonAncestorOfABinarySearchTree.cpp ├── lowestCommonAncestorOfABinarySearchTree.java ├── lowestCommonAncestorOfABinarySearchTree2.cpp └── lowestCommonAncestorOfABinarySearchTree3.cpp ├── lowestCommonAncestorOfaBinaryTree ├── lowestCommonAncestorOfaBinaryTree.cpp └── lowestCommonAncestorOfaBinaryTree.java ├── magicalString ├── magicalString.cpp └── magicalString.java ├── majorityElement ├── majorityElement.cpp └── majorityElement_2.cpp ├── majorityElementII └── majorityElementII.cpp ├── makeTwoArraysEqualByReversingSubarrays └── makeTwoArraysEqualByReversingSubarrays.java ├── matchsticksToSquare └── matchsticksToSquare.cpp ├── maxAreaOfIsland ├── MaxAreaOfIsland.java ├── maxAreaOfIsland.cpp └── maxAreaOfIsland_bfs.cpp ├── maxChunksToMakeSorted └── maxChunksToMakeSorted.cpp ├── maxConsecutiveOnes └── maxConsecutiveOnes.cpp ├── maxConsecutiveOnesII └── maxConsecutiveOnesII.cpp ├── maxIncreaseToKeepCitySkyline └── maxIncreaseToKeepCitySkyline.cpp ├── maxStack └── maxStack.cpp ├── maximalRectangle └── maximalRectangle.cpp ├── maximalSquare ├── maximalSquare.cpp └── maximalSquare.java ├── maximizeTotalCostOfAlternatingSubarrays └── maximizeTotalCostOfAlternatingSubarrays.java ├── maximumAverageSubarrayI └── maximumAverageSubarrayI.cpp ├── maximumBinaryTree └── maximumBinaryTree.cpp ├── maximumDepthOfBinaryTree └── maximumDepthOfBinaryTree.cpp ├── maximumDistanceInArrays └── maximumDistanceInArrays.cpp ├── maximumGap └── maximumGap.cpp ├── maximumHeightOfATriangle └── maximumHeightOfATriangle.java ├── maximumLengthOfPairChain └── maximumLengthOfPairChain.cpp ├── maximumPointsAfterEnemyBattles └── maximumPointsAfterEnemyBattles.java ├── maximumProductOfThreeNumbers ├── maximumProductOfThreeNumbers.cpp └── maximumProductOfThreeNumbers_1.cpp ├── maximumProductOfWordLengths └── maximumProductOfWordLengths.cpp ├── maximumProductSubarray ├── maximumProductSubarray.cpp └── maximumProductSubarray.java ├── maximumSizeSubarraySumEqualsK └── maximumSizeSubarraySumEqualsK.cpp ├── maximumSubarray ├── maxSubArray.cpp ├── maxSubArray.java ├── maxSubArray_2.cpp ├── maxSubArray_2.java ├── maxSubArray_3.cpp └── maxSubArray_4.cpp ├── maximumSumOf3NonOverlappingSubarrays └── maximumSumOf3NonOverlappingSubarrays.cpp ├── maximumSwap ├── maximumSwap.cpp └── maximumSwap2.cpp ├── maximumTotalDamageWithSpellCasting └── maximumTotalDamageWithSpellCasting.java ├── maximumTotalRewardUsingOperationsI └── maximumTotalRewardUsingOperationsI.java ├── maximumVacationDays └── maximumVacationDays.cpp ├── maximumWidthOfBinaryTree ├── maximumWidthOfBinaryTree.cpp └── maximumWidthOfBinaryTree.java ├── maximumXORofTwoNumbersInAnArray ├── maximumXORofTwoNumbersInAnArray.cpp └── maximumXORofTwoNumbersInAnArrayII.cpp ├── medianOfTwoSortedArrays ├── medianOftwoSortedArrays.cpp └── medianOftwoSortedArrays2.cpp ├── meetingRooms └── meetingRooms.cpp ├── meetingRoomsII ├── meetingRoomsII.cpp ├── meetingRoomsII.java └── meetingRoomsII_2.cpp ├── meetingScheduler └── meetingScheduler.cpp ├── mergeIntervals ├── Solutions.java ├── mergeIntervals.cpp └── mergeIntervals.java ├── mergeSortedArray └── mergeSortedArray.cpp ├── mergeTwoBinaryTree ├── mergeTwoBinaryTrees.cpp └── mergeTwoBinaryTrees.java ├── mergeTwoList ├── mergeTwoSortedList.cpp └── mergeTwoSortedList2.cpp ├── mergekSortedLists ├── mergekSortedLists.cpp └── mergekSortedLists.java ├── middleOfLinkedList └── middleOfLinkedList.cpp ├── minCostClimbingStairs └── minCostClimbingStairs.cpp ├── minMoveToEqualArrayElements └── minMoveToEqualArrayElements.cpp ├── minStack ├── MinStack.java ├── minStack.cpp ├── minStack2.cpp └── minStack2.java ├── minesweeper ├── minesweeper.cpp ├── minesweeper.java └── minesweeper_2.cpp ├── miniParser └── miniParser.cpp ├── minimizeMaxDistanceToGasStation ├── minimizeMaxDistanceToGasStation.cpp └── minimizeMaxDistanceToGasStation2.cpp ├── minimumAbsoluteDifferenceInBST └── minimumAbsoluteDifferenceInBST.cpp ├── minimumCostToHireKWorkers ├── minimumCostToHireKWorkers.cpp ├── minimumCostToHireKWorkers.java └── minimumCostToHireKWorkers_bruteforce.cpp ├── minimumDepthOfBinaryTree ├── minimumDepthOfBinaryTree.cpp ├── minimumDepthOfBinaryTree_bfs.cpp └── minimumDepthOfBinaryTree_bfs.java ├── minimumDistanceBetweenBSTNodes └── minimumDistanceBetweenBSTNodes.cpp ├── minimumHeightTrees ├── minimumHeightTrees.cpp └── minimumHeightTrees.java ├── minimumIndexSumOfTwoLists └── minimunIndexSumOfTwoLists.cpp ├── minimumMovesToEqualArrayElementsII └── minimumMovesToEqualArrayElementsII.cpp ├── minimumNumberOfArrowsToBurstBalloons └── minimumNumberOfArrowsToBurstBalloons.cpp ├── minimumPathSum ├── minimumPathSum.cpp └── minimumPathSum_2.cpp ├── minimumRemoveToMakeValidParentheses └── minimumRemoveToMakeValidParentheses.java ├── minimumSizeSubarraySum └── minimumSizeSubarraySum.cpp ├── minimumTimeDifference └── minimumTimeDifference.cpp ├── minimumWindowSubsequence ├── minimumWindowSubsequence.cpp └── minimumWindowSubsequence_TLE.cpp ├── minimumWindowSubstring ├── minimumWindowSubstring.cpp ├── minimumWindowSubstring_easyunderstand.cpp └── minimumWindowSubstring_navie.cpp ├── mirrorRelection └── mirrorReflection.cpp ├── missingElementInSortedArray └── missingElementInSortedArray.cpp ├── missingNum ├── missingNum.cpp └── missingNum2.cpp ├── missingRanges └── missingRanges.cpp ├── monotoneIncreasingDigits └── monotoneIncreasingDigits.cpp ├── mostCommonWord └── mostCommonWord.cpp ├── mostFrequentSubtreeSum └── mostFrequentSubtreeSum.cpp ├── moveZeroes ├── moveZeros.cpp ├── moveZeros.java ├── moveZeros2.cpp └── moveZeros3.cpp ├── movingAverageFromDataStream └── movingAverageFromDataStream.cpp ├── multiplyStrings └── multiplyStrings.cpp ├── myCalendarI ├── myCalendarI.java ├── myCalendarI_1.cpp └── myCalendarI_2.cpp ├── myCalendarII └── myCalendarII.cpp ├── myCalendarIII └── myCalendarIII.cpp ├── nestListWeightSum └── nestListWeightSum.cpp ├── nestListWeightSumII └── nestListWeightSumII.cpp ├── nextClosestTime └── nextClosestTime.cpp ├── nextGreaterElementI └── nextGreaterElementI.cpp ├── nextGreaterElementII └── nextGreaterElementII.cpp ├── nextGreaterElementIII └── nextGreaterElementIII.cpp ├── nextPermutation └── nextPermutation.cpp ├── nimGame └── nimGame.cpp ├── nonDecreasingArray ├── nonDecreasingArray.cpp └── nonDecreasingArray1.cpp ├── notBoringMovies └── notBoringMovies ├── nthDigit └── nthDigit.cpp ├── nthHigestSalary └── nthHighestSalary ├── numberComplement └── numberComplement.cpp ├── numberOf1Bits └── numberOf1Bits.cpp ├── numberOfBoomerangs ├── numberOfBoomerangs.cpp ├── numberOfBoomerangs.java └── numberOfBoomerangs_2.cpp ├── numberOfConnectedComponentsInAnUndirectedGraph └── numberOfConnectedComponentsInAnUndirectedGraph.cpp ├── numberOfCornerRectangles └── numberOfCornerRectangles.cpp ├── numberOfDistinctIsland └── numberOfDistinctIsland.cpp ├── numberOfGoodPairs └── numberOfGoodPairs.java ├── numberOfIslands ├── numberOfIslands_bfs.cpp ├── numberOfIslands_bfs.java ├── numberOfIslands_bfs_visited.cpp ├── numberOfIslands_dfs.cpp └── numberOfIslands_dfs_stack.cpp ├── numberOfIslandsII ├── numberOfIslands.cpp └── numberOfIslands_2.cpp ├── numberOfLongestIncreasingSubsequence ├── numberOfLongestIncreasingSubsequence.cpp └── numberOfLongestIncreasingSubsequence.java ├── numberOfMatchingSubsequences ├── numberOfMatchingSubsequences.cpp └── numberOfMatchingSubsequences2.cpp ├── numberOfSegmentInAString └── numberOfSegmentsInAString.cpp ├── numberOfSubMatricesThatSumToTarget └── numberOfSubMatricesThatSumToTarget.cpp ├── oddEvenLinkedList └── oddEvenLinkedList.cpp ├── oneEditDistance └── oneEditDistance.cpp ├── onesAndZeroes ├── onesAndZeroes.cpp └── onesAndZeroes.java ├── optimalAccountBalancing └── optimalAccountBalancing.cpp ├── optimalDivision └── optimalDivision.cpp ├── outOfBoundaryPaths └── outOfBoundaryPaths.cpp ├── outputContestMatches └── outputContestMatches.cpp ├── pacificAtlanticWaterFlow ├── pacificAtlanticWaterFlow.cpp └── pacificAtlanticWaterFlow.java ├── paintFence └── paintFence.cpp ├── paintHouse └── paintHouse.cpp ├── paintHouseII └── paintHouseII.cpp ├── palindromeLinkedList └── palindromeLinkedList.cpp ├── palindromeNumber └── palindromeNumber.cpp ├── palindromePartitioning └── palindromePartitioning.cpp ├── palindromePermutation ├── palindromePermutation.cpp └── palindromePermutation.java ├── palindromePermutationII ├── PalindromePermutationII.java └── palindromePermutationII.cpp ├── palindromeSubstrings └── palindromeSubstrings.cpp ├── partitionEqualSubsetSum ├── partitionEqualSubsetSum.cpp ├── partitionEqualSubsetSum.java └── partitionEqualSubsetSum_dfs_mem.cpp ├── partitionLabels ├── partitionLabels.cpp └── partitionLabelsII.cpp ├── partitionList └── partitionList.cpp ├── partitionToKEqualSumSubsets ├── partitionToKEqualSumSubsets.cpp ├── partitionToKEqualSumSubsets.java └── partitionToKEqualSumSubsets_subsetPattern.cpp ├── pascalTriangle └── pascalTriangle.cpp ├── pascalTriangleII └── pascalTriangleII.cpp ├── patchingArray └── patchingArray.cpp ├── pathSum └── pathSum.cpp ├── pathSumII └── pathSumII.cpp ├── pathSumIII ├── pathSumIII.cpp ├── pathSumIII.java ├── pathSumIII_1.cpp └── pathSumIII_2.cpp ├── peakIndexInAmountainArray ├── peakIndexInAmountainArray.cpp └── peakIndexInAmountainArray_2.cpp ├── peaksInArray └── peaksInArray.java ├── peekingIterator └── peekingIterator.cpp ├── perfectNumber └── perfectNumber.cpp ├── perfectRectangle └── perfectRectangle.cpp ├── perfectSquares ├── perfectSquares.cpp ├── perfectSquares.java └── perfectSquares_BFS.cpp ├── permutationInString ├── permutationInString.cpp └── permutationInString_2.cpp ├── permutationSequence └── permutationSequence.cpp ├── permutations ├── permutations.cpp ├── permutations.java └── permutations2.cpp ├── permutationsII ├── permutationsII.cpp ├── permutationsII.java ├── permutationsII_set.cpp └── permutationsII_visited.cpp ├── plusOne └── plusOne.cpp ├── plusOneLinkedList └── plusOneLinkedList.cpp ├── poorPigs └── poorPigs.cpp ├── populatingNextRightPointsInEachNode ├── populatingNextRightPointersInEachNode.cpp ├── populatingNextRightPointersInEachNode.java └── populatingNextRightPointersInEachNode_2.cpp ├── populatingNextRightPointsInEachNodeII ├── populatingNextRightsInEachNodeII.cpp ├── populatingNextRightsInEachNodeII.java └── populatingNextRightsInEachNodeII2.cpp ├── possibleBipartition └── possibleBipartition.cpp ├── powXN ├── powXN.cpp ├── powXN.java └── powXN_2.java ├── powerOfFour └── powerOfFour.cpp ├── powerOfThree └── powerOfThree.cpp ├── powerOfTwo └── powerOfTwo.cpp ├── predictTheWinner ├── predictTheWinner.cpp ├── predictTheWinner.java └── predictTheWinner2.cpp ├── printBinaryTree ├── printBinaryTree.cpp └── printBinaryTree.java ├── productOfArrayExceptSelf ├── productOfArrayExceptSelf.cpp └── productOfArrayExceptSelf.java ├── pushDominoes ├── pushDominoes.cpp ├── pushDominoes.java └── pushDominoes_bfs.cpp ├── pyramidTransitionMatrix ├── pyramidTransitionMatrix.cpp └── pyramidTransitionMatrix.java ├── queueReconstructionByHeight ├── queueReconstructionByHeight.cpp └── queueReconstructionByHeight.java ├── randomPickIndex └── randomPickIndex.cpp ├── randomPickWithWeight ├── randomPickWithWeight.cpp ├── randomPickWithWeight.java ├── randomPickWithWeight_lowerbound.cpp └── randomPickWithWeight_lowerbound.java ├── rangeAddition └── rangeAddition.cpp ├── rangeAdditionII └── rangeAdditionII.cpp ├── rangeSumOfBST └── rangeSumOfBST.cpp ├── rangeSumQuery2D-Immutable └── rangeSumQuery2D-Immutable.cpp ├── rangeSumQuery2D_mutable └── rangeSumQuery2D_mutable.cpp ├── rangeSumQueryImmutable └── rangeSumQueryImmutable.cpp ├── rangeSumQueryMutable ├── rangeSumQueryMutable.cpp └── rangeSumQueryMutable_bit.cpp ├── rankScores └── rankScores ├── ransomNote └── ransomNote.cpp ├── reachingPoints └── reachingPoints.cpp ├── readNCharactersGivenRead4 └── readNCharactersGivenRead4.cpp ├── readNCharactersGivenRead4II └── readNCharactersGivenRead4II.cpp ├── rearrangeStringKDistanceApart └── rearrangeStringKDistanceApart.cpp ├── reconstructItinerary ├── reconstructItinerary.cpp ├── reconstructItinerary.java └── reconstructItinerary_stack.cpp ├── reconstructOriginalDigitsFromEnglish └── reconstructOriginalDigitsFromEnglish.cpp ├── rectangleArea └── rectangleArea.cpp ├── rectangleOverlap └── rectangleOverlap.cpp ├── redundantConnection └── redundantConnection.cpp ├── regularExpressionMatching ├── regularExpressionMatching.cpp └── regularExpressionMatching_2.cpp ├── relativeRanks └── relativeRanks.cpp ├── relativeSortArray └── relativeSortArray.cpp ├── removeAllAdjacentDuplicatesInString └── removeAllAdjacentDuplicatesInString.cpp ├── removeComments └── removeComments.cpp ├── removeDupFromSortedArray ├── removeDupFromSortedArray.cpp ├── removeDupFromSortedArray.java └── removeDupFromSortedArray2.cpp ├── removeDupFromSortedArrayII └── removeDupFromSortedArrayII.cpp ├── removeDupFromSortedList ├── removeDupFromSortedList.cpp └── removeDupFromSortedList2.cpp ├── removeDupFromSortedListII └── removeDupFromSortedListII.cpp ├── removeDuplicateLetters ├── removeDuplicateLetters.cpp └── removeDuplicateLetters_2.cpp ├── removeElement └── removeElement.cpp ├── removeInvalidParentheses ├── removeInvalidParentheses_bfs.cpp ├── removeInvalidParentheses_bfs_2.cpp └── removeInvalidParentheses_dfs.cpp ├── removeKDigits └── removeKDigits.cpp ├── removeLinkedListElements └── removeLinkedListElements.cpp ├── removeNthNodeFromEndOfList └── removeNthNodeFromEndofList.cpp ├── reorderDataInLogFiles ├── reorderDataInLogFiles.cpp └── reorderDataInLogFiles_1.cpp ├── reorderList └── reorderList.cpp ├── reorderLogFiles └── reorderLogFiles.cpp ├── reorganizeString └── reorganizeString.cpp ├── repeatedDNASequence └── repeatedDNASequences.cpp ├── repeatedStringMatch └── repeatedStringMatch.cpp ├── repeatedSubstringPattern └── repeatedSubstringPattern.cpp ├── replaceAllstoAvoidConsecutiveRepeatingCharacters ├── replaceAllstoAvoidConsecutiveRepeatingCharacters.java └── replaceAllstoAvoidConsecutiveRepeatingCharacters_bf.java ├── replaceElementsWithGreatestElementOnRightSide └── replaceElementsWithGreatestElementOnRightSide.cpp ├── replaceWords └── replaceWords.cpp ├── reshapeTheMatrix └── reshapeTheMatrix.cpp ├── restoreIpAddresses └── restoreIpAddresses.cpp ├── reverseBits └── reverseBits.cpp ├── reverseInteger ├── ReverseInteger.java ├── reverseInteger.cpp └── reverseInteger_2.cpp ├── reverseLinkedList ├── reverseLinkedList.cpp ├── reverseLinkedList2.cpp └── reverseLinkedList3.cpp ├── reverseLinkedListII ├── reverseLinkedListII.cpp ├── reverseLinkedListII_2.cpp └── reverseLinkedListII_headInsert.cpp ├── reverseNodesInkGroup └── reverseNodesInkGroup.cpp ├── reverseString ├── reverseString.cpp └── reverseString.java ├── reverseStringII └── reverseStringII.cpp ├── reverseVowelsOfASrting └── reverseVowelsOfAString.cpp ├── reverseWordsInAStringIII └── reverseWordsInAStringIII.cpp ├── reverseWordsInaString ├── reverseWordsInaString.cpp └── reverseWordsInaString_2.cpp ├── risingTemperature └── risingTemperature ├── robotBoundedInCircle └── robotBoundedInCircle.cpp ├── robotReturnToOrigin └── robotReturnToOrigin.java ├── robotRoomCleaner └── robotRoomCleaner.cpp ├── romanToInteger ├── romanToInteger.cpp └── romanToInteger.java ├── rotateArray ├── RotateArray.java ├── rotateArray.cpp └── rotateArray_1.cpp ├── rotateFunction └── rotateFunction.cpp ├── rotateImage ├── rotateImage.cpp └── rotateImage_1.cpp ├── rotateList └── rotateList.cpp ├── rotateString ├── rotateString.cpp └── rotateString_2.cpp ├── rotatedDigits └── rotatedDigits.cpp ├── rottingOranges └── rottingOrange.cpp ├── sameTree └── sameTree.cpp ├── scoreAfterFlippingMatrix └── scoreAfterFlippingMatrix.cpp ├── scoreOfParentheses ├── scoreOfParentheses.cpp └── scoreOfParentheses_1.cpp ├── searchA2DMatrix ├── searchA2DMatrix.cpp └── searchA2DMatrix.java ├── searchA2DMatrixII ├── searchA2DMatrixII.cpp └── searchA2DMatrixII.java ├── searchInASortedArrayOfUnknownSize └── searchInASortedArrayOfUnknownSize.cpp ├── searchInRotatedSortedArray ├── searchInRotatedSortedArray.cpp ├── searchInRotatedSortedArray.java └── searchInRotatedSortedArray2.cpp ├── searchInRotatedSortedArrayII ├── searchInRotatedArrayII.cpp └── searchInRotatedArrayII.java ├── searchInsertPosition ├── searchInsertPosition.cpp └── searchInsertPosition_2.cpp ├── secondHighestSalary └── secondHighestSalary ├── secondMinimumNodeInaBinaryTree └── secondMinimumNodeInaBinaryTree.cpp ├── selfDividingNumbers └── selfDividingNumbers.cpp ├── sentenceScreenFitting └── sentenceScreenFitting.cpp ├── sentenceSimilarity └── sentenceSimilarity.cpp ├── sentenceSimilarityII └── sentenceSimilarityII.cpp ├── sequenceReconstruction ├── sequenceReconstruction.cpp └── sequenceReconstruction2.cpp ├── serializeAndDeserializeBST ├── serializeAndDeserializeBST.cpp └── serializeAndDeserializeBST.java ├── serializeAndDeserializeBinaryTree ├── serializeAndDeserializeBinaryTree.cpp ├── serializeAndDeserializeBinaryTree.java ├── serializeAndDeserializeBinaryTree2.cpp └── serializeAndDeserializeBinaryTree3.cpp ├── serializeAndDeserializeN-aryTree └── serializeAndDeserializeN-aryTree.cpp ├── setMatrixZeroes └── setMatrixZeroes.cpp ├── setMismatch └── setMismatch.cpp ├── shoppingOffers ├── shoppingOffers.cpp └── shoppingOffers.java ├── shortestCompletingWord └── shortestCompletingWord.cpp ├── shortestDistanceFromAllBuildings └── shortestDistanceFromAllBuildings.cpp ├── shortestDistanceToACharacter └── shortestDistanceToACharacter.cpp ├── shortestPalindrome ├── shortestPalindrome.cpp └── shortestPalindrome2.cpp ├── shortestSubarrayWithSumAtLeastK └── shortestSubarrayWithSumAtLeastK.cpp ├── shortestUnsortedContSub ├── shortestUnsortedContSub.cpp └── shortestUnsortedContSub2.cpp ├── shortestWordDistance └── shortestWordDistance.cpp ├── shortestWordDistanceII └── shortestWordDistanceII.cpp ├── shortestWordDistanceIII └── shortestWordDistanceIII.cpp ├── shuffleAnArray └── shuffleAnArray.cpp ├── shuffleTheArray └── shuffleTheArray.java ├── similarRGBColor └── similarRGBColor.cpp ├── simplifyPath └── simplifyPath.cpp ├── singleElementInASortedArray ├── singleElementInASortedArray.cpp └── singleElementInASortedArray.java ├── singleNumber ├── singleNumber.cpp └── singleNumber_2.cpp ├── slidingWindowMaximum ├── slidingWindowMaximum.cpp └── slidingWindowMaximum.java ├── slidingWindowMedian ├── slidingWindowMedian.cpp └── slidingWindowMedian.java ├── smallestGoodBase └── smallestGoodBase.cpp ├── solveTheEquation ├── solveTheEquation.cpp ├── solveTheEquation.java └── solveTheEquation_split.cpp ├── sortArrayByParity └── sortArrayByParity.cpp ├── sortCharactersByFrequency └── sortCharactersByFrequency.cpp ├── sortColors ├── sortColors.cpp └── sortColors.java ├── sortList └── sortList.cpp ├── sortTransformedArray └── sortTransformedArray.cpp ├── soupServings ├── soupServings.cpp └── soupServings.java ├── sparseMatrixMultiplication └── sparseMatrixMultiplication.cpp ├── specialArrayII └── SpecialArrayII.java ├── spiralMatrix ├── spiralMatrix.cpp ├── spiralMatrix_bfs.cpp └── spiralMatrix_dfs.cpp ├── spiralMatrixII └── spiralMatrixII.cpp ├── splitArrayIntoConsecutiveSubsequences ├── splitArrayIntoConsecutiveSubsequences.cpp └── splitArrayIntoConsecutiveSubsequences2.cpp ├── splitArrayLargestSum ├── splitArrayLargestSum.cpp └── splitArrayLargestSum.java ├── splitBST └── splitBST.cpp ├── splitLinkedListInParts └── splitLinkedListInParts.cpp ├── sqrtX └── sqrtX.cpp ├── squaresOfSortedArray └── squaresOfSortedArray.cpp ├── stringToInteger └── stringToInteger.cpp ├── stringcompression ├── stringcompression.cpp ├── stringcompression.java └── stringcompression_2.cpp ├── strobogrammaticNumber └── strobogrammaticNumber.cpp ├── strobogrammaticNumberII ├── strobogrammaticNumberII.cpp ├── strobogrammaticNumberII_dfs.cpp └── strobogrammaticNumberII_dfs_overtime.cpp ├── studentAttendanceRecordI └── studentAttendanceRecordI.cpp ├── studentAttendanceRecordII └── studentAttendanceRecordII.cpp ├── subArraySumEqualsK ├── subArraySumEqualsK.cpp └── subArraySumEqualsK.java ├── subTreeOfAnotherTree ├── subTreeOfAnothertree.cpp └── subTreeOfAnothertree.java ├── subsets ├── subsets.cpp ├── subsets.java └── subsets_2.cpp ├── subsetsII ├── subsetsII.cpp ├── subsetsII.java └── subsetsII_2.cpp ├── substractTheProductAndSumOfDigitsOfAnInteger └── substractTheProductAndSumOfDigitsOfAnInteger.java ├── sudokuSolver └── sudokuSolver.cpp ├── sumOfDigitDifferencesOfAllPairs └── SumOfDigitDifferencesOfAllPairs.java ├── sumOfLeftLeaves └── sumOfLeftLeaves.cpp ├── sumOfSquareNumbers └── sumOfSquareNumbers.cpp ├── sumOfTwoIntegers └── sumOfTwoIntegers.cpp ├── sumRootToLeafNumbers └── sumRootToLeafNumbers.cpp ├── summaryRanges ├── summaryRanges.cpp └── summaryRanges_2.cpp ├── superPow └── superPow.cpp ├── superUglyNumber ├── superUglyNumber.cpp ├── superUglyNumber.java ├── superUglyNumber_pq.cpp └── superUglyNumber_pq_navie.cpp ├── superWashingMachines └── superWashingMachines.cpp ├── surroundedregions └── surroundedRegions.cpp ├── swapAdjacentInLRString └── swapAdjacentInLRString.cpp ├── swapNodesInPairs └── swapNodesInPairs.cpp ├── swapSalary └── swapSalary ├── symmetricTree ├── symmetricTree.cpp └── symmetricTree.java ├── targetSum ├── targetSum.cpp ├── targetSum.java ├── targetSum2.cpp └── targetSum_dfs.cpp ├── taskScheduler └── taskScheduler.cpp ├── teemoAttacking └── teemoAttacking.cpp ├── textJustification └── textJustification.cpp ├── theMaze └── theMaze.cpp ├── theMazeII └── theMazeII.cpp ├── theSkylineProblem ├── theSkylineProblem.cpp ├── theSkylineProblem.java └── theSkylineProblem_treeSet.java ├── thirdMaxNumber └── thirdMaxNumber.cpp ├── toLowerCase └── toLowerCase.java ├── toeplitzMatrix └── toeplitzMatrix.cpp ├── topKFrequentElements ├── topKFrequentElements.cpp └── topKFrequentElements_2.cpp ├── topKFrequentWords ├── topKFrequentWords.cpp ├── topKFrequentWords.java ├── topKFrequentWords_1.cpp └── topKFrequentWords_2.cpp ├── totalHammingDistance └── totalHammingDistance.cpp ├── trappingRainWater ├── trappingRainWater.cpp └── trappingRainWater.java ├── trappingRainWaterII └── trappingRainWaterII.cpp ├── triangle └── triangle.cpp ├── trimaBinarySearchTree └── trimaBinarySearchTree.cpp ├── twoSum ├── twoSum.cpp ├── twoSum.java ├── twoSum1.cpp └── twoSum_2.cpp ├── twoSumII └── twoSumII.cpp ├── twoSumIV_InputIsaBST ├── twoSumIV_InputIsaBST.cpp └── twoSumIV_InputIsaBST.java ├── uglyNumber └── uglyNumber.cpp ├── uglyNumberII ├── uglyNumberII.cpp ├── uglyNumberII.java └── uglyNumberII_2.cpp ├── uncrossedLines ├── uncrossedLines.cpp └── uncrossedLines.java ├── uniqueBST └── uniqueBST.cpp ├── uniqueBSTII └── uniqueBSTII.cpp ├── uniqueEmailAddresses ├── uniqueEmailAddresses.cpp └── uniqueEmailAddresses.java ├── uniqueMorseCodeWords └── uniqueMorseCodeWords.cpp ├── uniquePaths ├── uniquePaths.cpp └── uniquePaths_2.cpp ├── uniquePathsII ├── uniquePathsII.cpp └── uniquePathsII_2.cpp ├── uniqueSubstringInWraparoundString └── uniqueSubstringInWraparoundString.cpp ├── uniqueWordAbberviation └── uniqueWordAbberviation.cpp ├── utf8Validation └── utf8Validation.cpp ├── validAnagram └── validAnagram.cpp ├── validPalindrome ├── validParlindrome.cpp └── validParlindrome_1.cpp ├── validPalindromeII ├── validPalindromeII.cpp └── validPalindromeII.java ├── validParentheses ├── validParentheses.cpp └── validParentheses.java ├── validParenthesisString └── validParenthesisString.cpp ├── validPerfectSquare └── validPerfectSquare.cpp ├── validSquare └── validSquare.cpp ├── validSudoku ├── validSudoku.cpp └── validSudoku.java ├── validTriangleNumber └── validTriangleNumber.cpp ├── validWordAbbreviation └── validWordAbbreviation.cpp ├── validWordSquare └── validWordSquare.cpp ├── validateBinarySearchTree ├── validateBinarySearchTree.cpp ├── validateBinarySearchTree.java ├── validateBinarySearchTree_1.cpp ├── validateBinarySearchTree_2.cpp └── validateBinarySearchTree_3.cpp ├── validateIPAddress └── validateIPAddress.cpp ├── verifyPreorderSerializationOfBinaryTree └── verifyPreorderSerializationOfBinaryTree.cpp ├── wallsAndGates ├── wallsAndGates.cpp └── wallsAndGates2.cpp ├── waterAndJugProblem └── waterAndJugProblem.cpp ├── wiggleSort └── wiggleSort.cpp ├── wiggleSortII ├── wiggleSortII.cpp └── wiggleSortII_2.cpp ├── wiggleSubsequence └── wiggleSubsequence.cpp ├── wildcardMatching ├── wildcardMatching.cpp └── wildcardMatching.java ├── wordBreak ├── wordBreak.cpp ├── wordBreak.java └── wordBreak_2.java ├── wordBreakII └── wordBreakII.cpp ├── wordLadder ├── wordladder.java └── wordladder_2.cpp ├── wordLadderII ├── wordLadderII.cpp ├── wordLadderII_2.cpp └── wordLadderII_bruteforce.cpp ├── wordPattern ├── wordPattern.cpp └── wordPattern2.cpp ├── wordSearch ├── wordSearch.cpp ├── wordSearch.java └── wordSearch_2.cpp ├── wordSearchII ├── wordSearchII.cpp └── wordSearchII_2.cpp ├── wordSquares └── wordSquares.cpp ├── wordladder ├── wordladder.cpp └── wordladder_1.cpp ├── zigzagConversion ├── zigzagConversion.cpp └── zigzagConversion.java └── zigzagIterator └── zigzagIterator.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | *.*~ 2 | *.o 3 | *~ 4 | a.out 5 | .idea/ 6 | 7 | *.class 8 | -------------------------------------------------------------------------------- /1bitAnd2bitChar/1bitAnd2bitChar.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution 6 | { 7 | public: 8 | bool isOneBitCharacter(vector& bits) { 9 | int size = bits.size(); 10 | int i = 0; 11 | while (i < size - 1) { 12 | if (bits[i] == 1) 13 | i += 2; 14 | else 15 | i++; 16 | } 17 | return i == size - 1; 18 | } 19 | }; 20 | 21 | int main() 22 | { 23 | Solution s; 24 | vector ss1 = {1,0,0}; 25 | vector ss2 = {1,1,1,0}; 26 | vector ss3 = {0,0,1,1,0,0,1,1}; 27 | cout << s.isOneBitCharacter(ss1) << endl; 28 | cout << s.isOneBitCharacter(ss2) << endl; 29 | cout << s.isOneBitCharacter(ss3) << endl; 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /2KeysKeyboard/2Keyskeyboard.cpp: -------------------------------------------------------------------------------- 1 | // clang++ 2Keyskeyboard.cpp -std=c++11 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | int minSteps(int n) { 10 | if (n < 2) return 0; 11 | vector dp(n + 1, INT_MAX); 12 | dp[0] = 0; 13 | dp[1] = 0; 14 | dp[2] = 2; 15 | for (int i = 3; i <= n; i++) { 16 | for (int j = i / 2; j >= 1; j--) { 17 | if (i % j == 0) { 18 | dp[i] = min(dp[i], dp[j] + i / j); 19 | break; 20 | } 21 | } 22 | } 23 | return dp[n]; 24 | } 25 | }; 26 | 27 | int main() 28 | { 29 | Solution s; 30 | cout << s.minSteps(100) << endl; 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /2KeysKeyboard/2Keyskeyboard.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minSteps(int n) { 3 | if (n < 2) return 0; 4 | int[] dp = new int[n + 1]; 5 | for (int i = 0; i <= n; i++) dp[i] = Integer.MAX_VALUE; 6 | dp[0] = 0; 7 | dp[1] = 0; 8 | dp[2] = 2; 9 | for (int i = 3; i <= n; i++) { 10 | for (int j = i / 2; j >= 1; j--) { 11 | if (i % j == 0) { 12 | dp[i] = Math.min (dp[i], dp[j] + i / j); 13 | break; 14 | } 15 | } 16 | } 17 | return dp[n]; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /4keysKeyboard/4keysKeyboard.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | int maxA(int N) { 8 | vector dp(N + 1, 0); 9 | dp[0] = 0; 10 | dp[1] = 1; 11 | for (int k = 2; k <= N; k++) { 12 | dp[k] = k; 13 | for (int i = 1; i <= k - 3; i++) 14 | dp[k] = max (dp[k], dp[i] * (k - i - 1)); 15 | } 16 | return dp[N]; 17 | } 18 | }; 19 | 20 | int main() 21 | { 22 | Solution s; 23 | cout << s.maxA(8) << endl; 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /JewelsAndStones/JewelsAndStones.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int numJewelsInStones(string J, string S) { 8 | int res = 0; 9 | unordered_set s(J.begin(), J.end()); 10 | for (char c : S) { 11 | if (s.count(c)) 12 | res++; 13 | } 14 | return res; 15 | } 16 | }; 17 | 18 | int main() { 19 | Solution s; 20 | string J = "aA", S = "aAAbbb"; 21 | cout << s.numJewelsInStones(J, S) << endl; 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /JewelsAndStones/JewelsAndStones.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class JewelsAndStones { 3 | public int numJewelsInStones(String J, String S) { 4 | int res = 0; 5 | Set m = new HashSet(); 6 | for (char c : J.toCharArray()) { 7 | m.add(c); 8 | } 9 | for (char c : S.toCharArray()) { 10 | if (m.contains(c)) res++; 11 | } 12 | return res; 13 | } 14 | public static void main(String[] args) { 15 | String J = new String("aA"); 16 | String S = new String("aAAbbb"); 17 | JewelsAndStones s = new JewelsAndStones(); 18 | System.out.println(s.numJewelsInStones(J, S)); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | My solution to leetcode. Keep updating… -------------------------------------------------------------------------------- /addBinary/addBinary2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution{ 5 | public: 6 | string addBinary(string a, string b) { 7 | string res; 8 | int carry = 0; 9 | int i = a.length() - 1, j = b.length() - 1; 10 | while (i >= 0 || j >= 0 || carry != 0) { 11 | int sum = 0; 12 | if (i >= 0) 13 | sum += a[i] - '0'; 14 | if (j >= 0) 15 | sum += b[j] - '0'; 16 | sum += carry; 17 | res = to_string(sum % 2) + res; 18 | carry = sum / 2; 19 | i--; 20 | j--; 21 | } 22 | return res; 23 | } 24 | }; 25 | 26 | int main() 27 | { 28 | Solution s; 29 | string str1 = "11"; 30 | string str2 = "1"; 31 | cout << s.addBinary(str1, str2)<< endl; 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /addDigits/addDigits.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | int addDigits(int num) { 8 | /* int ans = 0; 9 | if (num < 10) 10 | return num; 11 | while (num > 0) { 12 | ans += num % 10; 13 | num = num / 10; 14 | } 15 | return addDigits(ans);*/ 16 | return 1 + (num - 1) % 9; 17 | } 18 | }; 19 | 20 | int main() 21 | { 22 | Solution s; 23 | cout << s.addDigits(38) << endl; 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /arithmeticSlices/arithmeticSlices.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | int numberOfArithmeticSlices(vector& A) { 8 | int size = A.size(); 9 | int res = 0, cur = 0; 10 | for (int i = 2; i < size; i++) { 11 | if (A[i] - A[i-1] == A[i-1] - A[i-2]) { 12 | cur++; 13 | res += cur; 14 | } else { 15 | cur = 0; 16 | } 17 | } 18 | return res; 19 | } 20 | }; 21 | 22 | int main() 23 | { 24 | Solution s; 25 | int a[4] = {1,2,3,4}; 26 | vector vec(a, a+4); 27 | cout << s.numberOfArithmeticSlices(vec) << endl; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /arrangingCoins/arrangingCoins.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | int arrangeCoins(int n) { 8 | /*int left = 0, right = n; 9 | while (left <= right) { 10 | long long mid = left + (right - left)/2; 11 | if(mid*(mid+1)*0.5 > n) 12 | right = mid - 1; 13 | else if(mid*(mid+1)*0.5 < n) 14 | left = mid + 1; 15 | else 16 | return mid; 17 | } 18 | return right;*/ 19 | //return int((-1 + sqrt(1 + 8 * (long)n))/2); 20 | return int(sqrt(0.25 + 2*(long)n) - 0.5); 21 | } 22 | }; 23 | 24 | int main() 25 | { 26 | Solution s; 27 | cout << s.arrangeCoins(17)<< endl; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /arrayPartitionI/arrayPartition1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution{ 7 | public: 8 | int arrayPairSum(vector& nums) { 9 | sort(nums.begin(), nums.end()); 10 | int size = nums.size(); 11 | int ans = 0; 12 | int i = 0; 13 | while (i < size) { 14 | ans += nums[i]; 15 | i += 2; 16 | } 17 | return ans; 18 | } 19 | }; 20 | 21 | int main() 22 | { 23 | Solution s; 24 | int a[10] = {1, 4, 3, 2}; 25 | vector vec(a, a+4); 26 | cout << s.arrayPairSum(vec) << endl; 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /assignCookies/assignCookies.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution{ 8 | public: 9 | int findContentChildren(vector& g, vector& s) { 10 | int ans = 0; 11 | sort(g.begin(), g.end()); 12 | sort(s.begin(), s.end()); 13 | int i = g.size()-1 , j = s.size()-1; 14 | while (i >= 0 && j >= 0) { 15 | if (g[i] <= s[j]) { 16 | ans++; 17 | i--; 18 | j--; 19 | } else { 20 | i--; 21 | } 22 | } 23 | return ans; 24 | } 25 | }; 26 | 27 | int main() 28 | { 29 | Solution s; 30 | int a[3] = {1,2}; 31 | int b[4] = {1,2,3}; 32 | vector vec1(a, a+2); 33 | vector vec2(b, b+3); 34 | cout << s.findContentChildren(vec1, vec2); 35 | cout << endl; 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /balancedBinaryTree/balancedBinaryTree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | class Solution { 11 | public boolean isBalanced(TreeNode root) { 12 | if (root == null) 13 | return true; 14 | res = true; 15 | getHeight(root); 16 | return res; 17 | } 18 | boolean res; 19 | public int getHeight(TreeNode root) { 20 | if (root == null) 21 | return 0; 22 | int left = getHeight(root.left); 23 | int right = getHeight(root.right); 24 | if (Math.abs(left - right) > 1) 25 | res = false; 26 | return Math.max(left, right) + 1; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /base7/base7.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | string convertToBase7(int num) { 8 | string ans; 9 | int sign = 1; 10 | if (num < 0) { 11 | sign = -1; 12 | num = -num; 13 | } 14 | if (num == 0) 15 | return "0"; 16 | while (num != 0) { 17 | ans += to_string(num % 7); 18 | num /= 7; 19 | } 20 | if (sign == -1) 21 | ans += "-"; 22 | reverse(ans.begin(), ans.end()); 23 | return ans; 24 | } 25 | }; 26 | 27 | int main() 28 | { 29 | Solution s; 30 | cout << s.convertToBase7(0); 31 | cout << endl; 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /beautifulArrangementII/beautifulArrangementII.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | vector constructArray(int n, int k) { 8 | vector res; 9 | int i = 1, j = n; 10 | while (i <= j) { 11 | if (k > 1) { 12 | if (--k % 2 == 0) 13 | res.push_back(i++); 14 | else 15 | res.push_back(j--); 16 | } else { 17 | res.push_back(i++); 18 | } 19 | } 20 | return res; 21 | } 22 | }; 23 | 24 | int main() { 25 | Solution s; 26 | for (int i : s.constructArray(3, 2)) { 27 | cout << i << " "; 28 | } 29 | cout << endl; 30 | return 0; 31 | } 32 | 33 | 34 | -------------------------------------------------------------------------------- /bestTimeToBuyAndSellStockIII/bestTimeToBuyAndSellStockIII.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int maxProfit(vector& prices) { 8 | if (prices.size() == 0) 9 | return 0; 10 | int hold1 = -prices[0]; 11 | int hold2 = INT_MIN; 12 | int sold1 = 0; 13 | int sold2 = 0; 14 | for (int p : prices) { 15 | hold1 = max (hold1, -p); 16 | sold1 = max (sold1, hold1 + p); 17 | hold2 = max (hold2, sold1 - p); 18 | sold2 = max (sold2, hold2 + p); 19 | } 20 | return sold2; 21 | } 22 | }; 23 | 24 | int main() { 25 | Solution s; 26 | vector prices = {4,3,2,6,2,9,1,2,3}; 27 | cout << s.maxProfit(prices) << endl; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /bestTimeToBuyAndSellStockWithTransactionFee/bestTimeToBuyAndSellStockWithTransactionFee.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxProfit(int[] prices, int fee) { 3 | int res = 0; 4 | int[] hold = new int[prices.length]; 5 | int[] sold = new int[prices.length]; 6 | hold[0] = -prices[0]; 7 | sold[0] = 0; 8 | for (int i = 1; i < prices.length; i++) { 9 | hold[i] = Math.max(hold[i - 1], sold[i - 1] - prices[i]); 10 | sold[i] = Math.max(sold[i - 1], hold[i - 1] + prices[i] - fee); 11 | } 12 | return sold[prices.length - 1]; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /bestTimeToBuyandSellStock/bestTimeToBuyAndSellStock.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int maxProfit(vector& prices) { 8 | int res = 0; 9 | int prevMin = INT_MAX; 10 | for (int p : prices) { 11 | if (p > prevMin) { 12 | res = max (res, p - prevMin); 13 | } else { 14 | prevMin = p; 15 | } 16 | } 17 | return res; 18 | } 19 | }; 20 | 21 | int main() 22 | { 23 | Solution s; 24 | int a[6] = {7, 1, 5, 3, 6, 4}; 25 | vector vec(a, a+6); 26 | cout << s.maxProfit(vec) << endl; 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /bestTimeToBuyandSellStock2/bestTimeToBuyandSellStock2_1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution{ 7 | public: 8 | int maxProfit(vector& prices) { 9 | int ans = 0; 10 | int size = prices.size(); 11 | if (size < 2) 12 | return ans; 13 | for (int i = 0; i < size - 1; i++) { 14 | if (prices[i+1] > prices[i]) 15 | ans += prices[i+1] - prices[i]; 16 | } 17 | return ans; 18 | } 19 | }; 20 | 21 | int main() 22 | { 23 | Solution s; 24 | int a[7] = {2,6,4,8,10,9,15}; 25 | vector vec(a, a+7); 26 | cout << s.maxProfit(vec) << endl; 27 | 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /bigCountries/bigCountries.cpp: -------------------------------------------------------------------------------- 1 | Select name, population, area 2 | from World 3 | where population > 25000000 or area > 3000000 4 | -------------------------------------------------------------------------------- /binaryGap/binaryGap.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int binaryGap(int N) { 4 | int res = 0; 5 | int rightOne = -1, i = 0; 6 | while (N) { 7 | i++; 8 | if (N % 2 == 1) { 9 | if (rightOne != -1) { 10 | res = max (res, i - rightOne); 11 | } 12 | rightOne = i; 13 | } 14 | N /= 2; 15 | } 16 | return res; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /binaryNumberWithAlternatingBits/binaryNumberWithAlternatingBits.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution 6 | { 7 | public: 8 | bool hasAlternatingBits(int n) { 9 | bool res = true; 10 | bool last = (n & 1) ? true : false; 11 | while (n) { 12 | n >>= 1; 13 | bool cur = (n & 1) ? true : false; 14 | if (last == cur) { 15 | res = false; 16 | break; 17 | } 18 | last = cur; 19 | //cout << n << endl; 20 | } 21 | return res; 22 | } 23 | }; 24 | 25 | int main() 26 | { 27 | Solution s; 28 | cout << s.hasAlternatingBits(5) << endl; 29 | cout << s.hasAlternatingBits(7) << endl; 30 | cout << s.hasAlternatingBits(11) << endl; 31 | cout << s.hasAlternatingBits(10) << endl; 32 | cout << s.hasAlternatingBits(21) << endl; 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /bulbSwitcher/bulbSwitcher.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | int bulbSwitch(int n) { 8 | return sqrt(n); 9 | } 10 | }; 11 | 12 | int main() 13 | { 14 | Solution s; 15 | cout << s.bulbSwitch(37) << endl; 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /bulbSwitcherII/bulbSwitcherII.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | int flipLights(int n, int m) { 8 | if (n == 0 || m == 0) return 1; 9 | if (n == 1) return 2; 10 | if (n == 2) return m == 1 ? 3 : 4; 11 | if (m == 1) return 4; 12 | return m == 2 ? 7 : 8; 13 | } 14 | }; 15 | 16 | int main() 17 | { 18 | Solution s; 19 | cout << s.flipLights(2, 1) << endl; 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /bulbSwitcherIII/bulbSwitcherIII.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numTimesAllBlue(int[] light) { 3 | int res = 0; 4 | int right = -1; 5 | for (int i = 0; i < light.length; i++) { 6 | right = Math.max(right, light[i]); 7 | if (i + 1 == right) { 8 | res++; 9 | } 10 | } 11 | return res; 12 | } 13 | } -------------------------------------------------------------------------------- /burstBalloons/burstBalloons.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxCoins(int[] nums) { 3 | int[][] dp = new int[nums.length][nums.length]; 4 | for (int[] arr : dp) { Arrays.fill(arr, -1); } 5 | return dfs(nums, dp, 0, nums.length - 1); 6 | } 7 | 8 | public int dfs(int[] nums, int[][] dp, int i, int j) { 9 | if (i > j) return 0; 10 | if (dp[i][j] != -1) return dp[i][j]; 11 | int res = 0; 12 | for (int k = i; k <= j; k++) { 13 | int boundLeft = i - 1 >= 0 ? nums[i - 1] : 1; 14 | int boundRight = j + 1 < nums.length ? nums[j + 1] : 1; 15 | res = Math.max(res, dfs(nums, dp, i, k - 1) + boundLeft * nums[k] * boundRight + dfs(nums, dp, k + 1, j)); 16 | } 17 | return dp[i][j] = res; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /canPlaceFlowers/canPlaceFlowers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | bool canPlaceFlowers(vector& flowerbed, int n) { 8 | int cnt = 0; 9 | for (int i = 0; i < flowerbed.size(); i++) { 10 | if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) 11 | && (i + 1 == flowerbed.size() || flowerbed[i + 1] == 0)) { 12 | flowerbed[i] = 1; 13 | cnt++; 14 | } 15 | } 16 | return cnt >= n; 17 | } 18 | }; 19 | 20 | int main() 21 | { 22 | Solution s; 23 | int a[8] = {0,1,0,1,0,1,0,0}; 24 | vector vec(a,a+8); 25 | cout << s.canPlaceFlowers(vec, 2) << endl; 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /classesMoreThan5Students/classesMoreThan5Students: -------------------------------------------------------------------------------- 1 | select class 2 | from courses 3 | group by class having count(distinct student) > 4; -------------------------------------------------------------------------------- /climbingStairs/climbingStairs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int climbStairs(int n) { 8 | if (n <= 2) return n; 9 | int dp1 = 1, dp2 = 2, dp3 = 0; 10 | for (int i = 3; i <= n; i++) { 11 | dp3 = dp1 + dp2; 12 | dp1 = dp2; 13 | dp2 = dp3; 14 | } 15 | return dp3; 16 | } 17 | }; 18 | 19 | int main() 20 | { 21 | Solution s; 22 | cout << s.climbStairs(10) << endl; 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /coinChange/coinChange.cpp: -------------------------------------------------------------------------------- 1 | // clang++ coinChange.cpp -std=c++11 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | int coinChange(vector& coins, int amount) { 10 | vector dp(amount + 1, INT_MAX); 11 | dp[0] = 0; 12 | for (int i = 1; i <= amount; i++) { 13 | for (int coin : coins) { 14 | if (i >= coin && dp[i - coin] != INT_MAX) { 15 | dp[i] = min (dp[i], dp[i - coin] + 1); 16 | } 17 | } 18 | } 19 | return dp[amount] == INT_MAX ? -1 : dp[amount]; 20 | } 21 | }; 22 | 23 | int main() 24 | { 25 | Solution s; 26 | vector coins = {1,2,5}; 27 | cout << s.coinChange(coins, 11) << endl;; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /coinChange/coinChange.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int coinChange(int[] coins, int amount) { 3 | int[] dp = new int[amount + 1]; 4 | dp[0] = 0; 5 | for (int i = 1; i <= amount; i++) { 6 | dp[i] = Integer.MAX_VALUE; 7 | for (int coin : coins) { 8 | if (i >= coin && dp[i - coin] != Integer.MAX_VALUE) { 9 | dp[i] = Math.min(dp[i], dp[i - coin] + 1); 10 | } 11 | } 12 | } 13 | if (dp[amount] == Integer.MAX_VALUE) return -1; 14 | else return dp[amount]; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /coinChangeII/coinChangeII.cpp: -------------------------------------------------------------------------------- 1 | // clang++ coinChangeII.cpp -std=c++11 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | int change(int amount, vector& coins) { 10 | vector dp(amount + 1, 0); 11 | dp[0] = 1; 12 | for (int coin : coins) { 13 | for (int j = 0; j <= amount; j++) { 14 | if (j >= coin) 15 | dp[j] += dp[j - coin]; 16 | } 17 | } 18 | return dp[amount]; 19 | } 20 | }; 21 | 22 | int main() 23 | { 24 | Solution s; 25 | vector coins = {1,2,5}; 26 | cout << s.change(11, coins) << endl;; 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /coinChangeII/coinChangeII.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int change(int amount, int[] coins) { 3 | int[][] dp = new int[coins.length + 1][amount + 1]; 4 | dp[0][0] = 1; 5 | for (int i = 1; i <= coins.length; i++) { 6 | for (int j = 0; j <= amount; j++) { 7 | dp[i][j] += dp[i - 1][j]; 8 | if (j >= coins[i - 1]) { 9 | dp[i][j] += dp[i][j - coins[i - 1]]; 10 | } 11 | } 12 | } 13 | return dp[coins.length][amount]; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /coinChangeII/coinChangeII_2.cpp: -------------------------------------------------------------------------------- 1 | // clang++ coinChangeII_2.cpp -std=c++11 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | int change(int amount, vector& coins) { 10 | vector > dp(coins.size() + 1, vector(amount + 1, 0)); 11 | dp[0][0] = 1; 12 | for (int i = 1; i <= coins.size(); i++) { 13 | for (int j = 0; j <= amount; j++) { 14 | dp[i][j] += dp[i - 1][j]; 15 | if (j >= coins[i - 1]) 16 | dp[i][j] += dp[i][j - coins[i - 1]]; 17 | } 18 | } 19 | return dp[coins.size()][amount]; 20 | } 21 | }; 22 | 23 | int main() 24 | { 25 | Solution s; 26 | vector coins = {1,2,5}; 27 | cout << s.change(11, coins) << endl;; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /combinationSumIV/combinationSumIV.cpp: -------------------------------------------------------------------------------- 1 | // clang++ combinationSumIV.cpp -std=c++11 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | int combinationSum4(vector& nums, int target) { 10 | vector dp(target + 1, 0); 11 | dp[0] = 1; 12 | for (int i = 1; i <= target; i++) { 13 | for (int num : nums) { 14 | if (i >= num) 15 | dp[i] += dp[i - num]; 16 | } 17 | } 18 | return dp[target]; 19 | } 20 | }; 21 | 22 | int main() 23 | { 24 | Solution s; 25 | vector nums = {1, 2, 3}; 26 | cout << s.combinationSum4(nums, 4) << endl; 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /combinationSumIV/combinationSumIV.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int combinationSum4(int[] nums, int target) { 3 | int[] dp = new int[target + 1]; 4 | dp[0] = 1; 5 | for (int i = 1; i <= target; i++) { 6 | for (int num : nums) { 7 | if (i >= num) dp[i] += dp[i - num]; 8 | } 9 | } 10 | return dp[target]; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /combineTwoTables/combineTwoTables: -------------------------------------------------------------------------------- 1 | select p.FirstName, p.LastName, a.City, a.State from Person p left join Address a on p.PersonId = a.PersonId; -------------------------------------------------------------------------------- /consecutiveNumbers/consecutiveNumbers: -------------------------------------------------------------------------------- 1 | Select DISTINCT l1.Num ConsecutiveNums from Logs l1, Logs l2, Logs l3 2 | where l1.Id=l2.Id-1 and l2.Id=l3.Id-1 3 | and l1.Num=l2.Num and l2.Num=l3.Num -------------------------------------------------------------------------------- /containerWithMostWater/containerWithMostWater.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution{ 7 | public: 8 | int maxArea(vector& height) { 9 | int left = 0, right = height.size() - 1; 10 | int maxArea = 0; 11 | while(left < right) { 12 | maxArea = max(maxArea, (right - left) * min(height[left], height[right])); 13 | if(height[left] > height[right]) 14 | right--; 15 | else 16 | left++; 17 | } 18 | return maxArea; 19 | } 20 | }; 21 | 22 | int main() 23 | { 24 | Solution s; 25 | int a[4] = {1,2,3,1}; 26 | vector vec(a, a + 4); 27 | cout << s.maxArea(vec) << endl; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /containsDuplicate/containsDup.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution{ 7 | public: 8 | bool contiansDuplicate(vector& nums) { 9 | int size = nums.size(); 10 | if (size < 2) 11 | return false; 12 | unordered_map map; 13 | map.insert(make_pair(nums[0], 0)); 14 | unordered_map::iterator it; 15 | for (int i = 1; i < size; i++) { 16 | it = map.find(nums[i]); 17 | if (it != map.end()) 18 | return true; 19 | else 20 | map.insert(make_pair(nums[i], i)); 21 | } 22 | return false; 23 | } 24 | }; 25 | 26 | int main() 27 | { 28 | Solution s; 29 | int a[8] = {4,3,2,7,8,4,5,1}; 30 | vector vec(a, a+8); 31 | cout << s.contiansDuplicate(vec) << endl; 32 | 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /contiguousArray/contiguousArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution{ 7 | public: 8 | int findMaxLength(vector& nums) { 9 | int res = 0; 10 | unordered_map m; 11 | m[0] = -1; 12 | int preSum = 0; 13 | for (int i = 0; i < nums.size(); i++) { 14 | int num = (nums[i] == 0 ? -1 : 1); 15 | preSum += num; 16 | if (m.count(preSum)) { 17 | res = max (res, i - m[preSum]); 18 | } else { 19 | m[preSum] = i; 20 | } 21 | } 22 | return res; 23 | } 24 | }; 25 | 26 | int main() 27 | { 28 | Solution s; 29 | int a[7] = {0, 0, 1, 0}; 30 | vector vec(a, a+4); 31 | cout << s.findMaxLength(vec); 32 | cout << endl; 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /convertBinaryNumberInLinkedListToInteger/convertBinaryNumberInLinkedListToInteger.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | int getDecimalValue(ListNode* head) { 12 | int res = 0; 13 | ListNode* cur = head; 14 | while (cur) { 15 | res *= 2; 16 | if (cur->val == 1) { 17 | res += cur->val; 18 | } 19 | cur = cur->next; 20 | } 21 | return res; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /convertaNumberToHexadecimal/convertANumberToHexadecimal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution{ 5 | public: 6 | string toHex(int num) { 7 | if (num == 0) 8 | return "0"; 9 | string ans; 10 | char hex[16] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; 11 | while (num != 0) { 12 | ans = hex[num & 0x0000000f] + ans; 13 | num >>= 4; 14 | if (ans.length() == 8) 15 | break; 16 | } 17 | return ans; 18 | } 19 | }; 20 | 21 | int main() 22 | { 23 | Solution s; 24 | cout << s.toHex(-1); 25 | cout << endl; 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /countAndSay/countAndSay.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | string countAndSay(int n) { 7 | string res = ""; 8 | if (n <= 0) 9 | return res; 10 | res = "1"; 11 | if (n == 1) 12 | return res; 13 | while (n > 1) { 14 | string temp; 15 | char c = res[0]; 16 | int count = 1; 17 | for (int i = 1; i < res.length(); i++) { 18 | if (res[i] == res[i - 1]) { 19 | count++; 20 | } else { 21 | temp += to_string(count) + c; 22 | c = res[i]; 23 | count = 1; 24 | } 25 | } 26 | temp += to_string(count) + c; 27 | res = temp; 28 | n--; 29 | } 30 | return res; 31 | } 32 | }; 33 | 34 | int main() 35 | { 36 | Solution s; 37 | cout << s.countAndSay(5) << endl; 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /countBinarySubstrings/countBinarySubstrings.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution 6 | { 7 | public: 8 | int countBinarySubstrings(string s) { 9 | int res = 0; 10 | int prevLength = 0; // length of pre sequence 0 or 1 11 | int curLength = 1; 12 | for (int i = 1; i < s.length(); i++) { 13 | if (s[i] == s[i - 1]) 14 | curLength++; 15 | else { 16 | prevLength = curLength; 17 | curLength = 1; 18 | } 19 | if (prevLength >= curLength) 20 | res++; 21 | } 22 | return res; 23 | } 24 | }; 25 | 26 | int main() 27 | { 28 | Solution s; 29 | string ss = "00110011"; 30 | cout << s.countBinarySubstrings(ss) << endl; 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /countNumbersWithUniqueDigits/countNumbersWithUniqueDigits.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution{ 7 | public: 8 | int countNumbersWithUniqueDigits(int n) { 9 | int ans = 10; 10 | if (n == 0) 11 | return 1; 12 | int uniqueDigitsNumInAFixedLen = 9; 13 | int availableDigitsNum = 9; 14 | while (n-- > 1 && availableDigitsNum > 0) { 15 | uniqueDigitsNumInAFixedLen = uniqueDigitsNumInAFixedLen * availableDigitsNum; 16 | ans += uniqueDigitsNumInAFixedLen; 17 | availableDigitsNum--; 18 | } 19 | return ans; 20 | } 21 | }; 22 | 23 | int main() 24 | { 25 | Solution s; 26 | cout << s.countNumbersWithUniqueDigits(3); 27 | cout << endl; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /countOfSmallerNumbersAfterSelf/countOfSmallerNumbersAfterSelf2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | vector countSmaller(vector& nums) { 8 | vector res(nums.size()); 9 | vector temp; 10 | for(int i = nums.size()-1; i >= 0; i--) 11 | { 12 | auto it = lower_bound(temp.begin(), temp.end(), nums[i]); 13 | res[i] = it - temp.begin(); 14 | temp.insert(it, nums[i]); 15 | } 16 | return res; 17 | } 18 | }; 19 | 20 | int main() { 21 | Solution s; 22 | vector nums = {5, 2, 6, 1}; 23 | for(int n : s.countSmaller(nums)) 24 | cout << n << " "; 25 | cout << endl; 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /countPairsThatFormACompleteDayI/countPairsThatFormACompleteDayI.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countCompleteDayPairs(int[] hours) { 3 | int res = 0; 4 | for (int i = 0; i < hours.length; i++) { 5 | for (int j = i - 1; j >= 0; j--) { 6 | if (((hours[i] % 24 + hours[j] % 24) % 24) == 0) res++; 7 | } 8 | } 9 | return res; 10 | } 11 | } -------------------------------------------------------------------------------- /countPrimes/countPrimes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | int countPrimes(int n) { 8 | int ans = 0; 9 | vector isPrime(n, true); 10 | for (int i = 2; i < n; i++) { 11 | if (isPrime[i]) { 12 | ans++; 13 | for (int j = 2; i*j < n; j++) { 14 | isPrime[i*j] = false; 15 | } 16 | } 17 | } 18 | return ans; 19 | } 20 | }; 21 | 22 | int main() 23 | { 24 | Solution s; 25 | cout << s.countPrimes(100); 26 | cout << endl; 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /countingBits/countingBits.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | vector countBits(int num) { 8 | vector ans(num+1, 0); 9 | for (int i = 1; i <= num; i++) { 10 | ans[i] = ans[i >> 1] + (i & 1); 11 | } 12 | return ans; 13 | } 14 | }; 15 | 16 | int main() 17 | { 18 | Solution s; 19 | vector res = s.countBits(5); 20 | for (int i : res) 21 | cout << i << " "; 22 | cout << endl; 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /customersWhoNeverOrder/customersWhoNeverOrder: -------------------------------------------------------------------------------- 1 | #method one 2 | select Customers.Name Customers from Customers 3 | where Customers.Id not in (select Customers.Id from Customers, Orders where Customers.Id = Orders.CustomerId); 4 | 5 | 6 | #method two 7 | select A.Name Customers from Customers A 8 | left join Orders B on a.Id = B.CustomerId 9 | where b.CustomerId is NULL; -------------------------------------------------------------------------------- /defangingAnIPAddress/defangingAnIPAddress.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string defangIPaddr(string address) { 4 | string res; 5 | for (char c : address) { 6 | if (c != '.') res += c; 7 | else res += "[.]"; 8 | } 9 | return res; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /deleteDupEmails/deleteDupEmails: -------------------------------------------------------------------------------- 1 | delete p1 from Person p1, Person p2 2 | where p1.Email = p2.Email and p1.Id > p2.Id; -------------------------------------------------------------------------------- /deleteOperationForTwoStrings/deleteOperationForTwoStrings.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minDistance(String word1, String word2) { 3 | int[][] dp = new int[word1.length() + 1][word2.length() + 1]; 4 | for (int i = 0; i <= word1.length(); i++) dp[i][0] = i; 5 | for (int j = 0; j <= word2.length(); j++) dp[0][j] = j; 6 | for (int i = 1; i <= word1.length(); i++) { 7 | for (int j = 1; j <= word2.length(); j++) { 8 | if (word1.charAt(i - 1) == word2.charAt(j - 1)) { 9 | dp[i][j] = dp[i - 1][j - 1]; 10 | } else { 11 | dp[i][j] = Math.min(dp[i - 1][j - 1] + 2, Math.min(dp[i - 1][j], dp[i][j - 1]) + 1); 12 | } 13 | } 14 | } 15 | return dp[word1.length()][word2.length()]; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /departmentHighestSalary/departmentHighestSalary: -------------------------------------------------------------------------------- 1 | #method one 2 | select Department.Name Department, Employee.Name Employee, Employee.Salary from Employee, Department 3 | where Employee.DepartmentId = Department.Id and Employee.Salary in (select max(Salary) from Employee e where e.DepartmentId = Department.Id); 4 | 5 | #method two 6 | select Department.Name Department, Employee.Name Employee, Employee.Salary from Employee, Department 7 | where Employee.DepartmentId = Department.Id and (DepartmentId, Employee.Salary) in (select DepartmentId, max(Salary) from Employee group by DepartmentId); -------------------------------------------------------------------------------- /distributeCandies/distributeCandies.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution{ 8 | public: 9 | int distributeCandies(vector& candies) { 10 | unordered_set kinds; 11 | for (int kind : candies) { 12 | kinds.insert(kind); 13 | } 14 | return min(kinds.size(), candies.size()/2); 15 | } 16 | }; 17 | 18 | int main() 19 | { 20 | Solution s; 21 | int a[6] = {1, 1, 2, 2, 3, 3}; 22 | vector vec(a,a+6); 23 | cout << s.distributeCandies(vec) << endl; 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /divideTwoIntegers/divideTwoIntegers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution{ 5 | public: 6 | int divide(int dividend, int divisor) { 7 | if (!divisor || (dividend == INT_MIN && divisor == -1)) 8 | return INT_MAX; 9 | int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1; 10 | long long dvd = labs(dividend); 11 | long long dvs = labs(divisor); 12 | int res = 0; 13 | while (dvd >= dvs) { 14 | long long temp = dvs, mutiple = 1; 15 | while (dvd >= (temp << 1)) { 16 | temp <<= 1; 17 | mutiple <<= 1; 18 | } 19 | dvd -= temp; 20 | res += mutiple; 21 | } 22 | return sign == 1 ? res : -res; 23 | } 24 | }; 25 | 26 | int main() 27 | { 28 | Solution s; 29 | cout << s.divide(35, 5) << endl; 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /dominoAndTrominoTiling/dominoAndTrominoTiling.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int numTilings(int N) { 8 | int kMod = 1000000007; 9 | vector > dp(N + 1, vector(2, 0)); 10 | dp[0][0] = dp[1][0] = 1; 11 | for (int i = 2; i <= N; i++) { 12 | dp[i][0] = (dp[i - 1][0] + dp[i - 2][0] + 2 * dp[i - 1][1]) % kMod; 13 | dp[i][1] = (dp[i - 2][0] + dp[i - 1][1]) % kMod; 14 | } 15 | return dp[N][0]; 16 | } 17 | }; 18 | 19 | int main() { 20 | Solution s; 21 | cout << s.numTilings(5) << endl; 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /dominoAndTrominoTiling/dominoAndTrominoTiling_2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int numTilings(int N) { 8 | const int kMod = 1000000007; 9 | vector dp1(N + 1, 0), dp2 = dp1, dp3 = dp1; 10 | dp1[0] = dp1[1] = dp2[1] = dp3[1] = 1; 11 | for (int i = 2; i <= N; i++) { 12 | dp1[i] = (dp1[i - 1] + dp1[i - 2] + dp2[i - 2] + dp3[i - 2]) % kMod; 13 | dp2[i] = (dp1[i - 1] + dp3[i - 1]) % kMod; 14 | dp3[i] = (dp1[i - 1] + dp2[i - 1]) % kMod; 15 | } 16 | return dp1[N]; 17 | } 18 | }; 19 | 20 | int main() { 21 | Solution s; 22 | cout << s.numTilings(5) << endl; 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /duplicateEmails/duplicateEmails: -------------------------------------------------------------------------------- 1 | 2 | #method one 3 | Select distinct p1.Email from Person p1 join Person p2 on p1.Email = p2.Email 4 | where p1.Id <> p2.Id; 5 | 6 | #method two 7 | select Email 8 | from Person 9 | group by Email 10 | having count(*) > 1 -------------------------------------------------------------------------------- /editDistance/editDistance.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minDistance(String word1, String word2) { 3 | int[][] dp = new int[word1.length() + 1][word2.length() + 1]; 4 | for (int i = 0; i <= word1.length(); i++) dp[i][0] = i; 5 | for (int j = 0; j <= word2.length(); j++) dp[0][j] = j; 6 | for (int i = 1; i <= word1.length(); i++) { 7 | for (int j = 1; j <= word2.length(); j++) { 8 | if (word1.charAt(i - 1) == word2.charAt(j - 1)) { 9 | dp[i][j] = dp[i - 1][j - 1]; 10 | } else { 11 | dp[i][j] = Math.min(dp[i - 1][j], Math.min(dp[i - 1][j - 1], dp[i][j - 1])) + 1; 12 | } 13 | } 14 | } 15 | return dp[word1.length()][word2.length()]; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /employeesEarningMoreThanTheirManagers/employeesEarnMoreThanTheirManagers: -------------------------------------------------------------------------------- 1 | select E1.Name Employee 2 | from Employee as E1, Employee as E2 3 | where E1.ManagerId = E2.Id and E1.Salary > E2.Salary -------------------------------------------------------------------------------- /escapeTheGhosts/escapeTheGhosts.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | bool escapeGhosts(vector>& ghosts, vector& target) { 8 | long dis = abs(target[0]) + abs(target[1]); 9 | for (vector& p : ghosts) { 10 | long dx = abs (target[0] - p[0]); 11 | long dy = abs (target[1] - p[1]); 12 | if (dx + dy <= dis) 13 | return false; 14 | } 15 | return true; 16 | } 17 | }; 18 | 19 | int main() { 20 | Solution s; 21 | vector> ghosts = {{1, 0}}; 22 | vector target = {2, 0}; 23 | cout << s.escapeGhosts(ghosts, target) << endl; 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /excelSheetColumnNumber/excelSheetColumnNumber.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | int titleToNumber(string s) { 8 | int ans = 0; 9 | int i = s.length() - 1; 10 | int base = 1; 11 | while (i >= 0) { 12 | ans += (s[i] - 'A' + 1) * base; 13 | base *= 26; 14 | i--; 15 | } 16 | return ans; 17 | } 18 | }; 19 | 20 | int main() 21 | { 22 | Solution s; 23 | string str = "A"; 24 | cout << s.titleToNumber(str)<< endl; 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /excelSheetColumnTitle/excelSheetColumnTitle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | string convertToTitle(int n) { 8 | string ans = ""; 9 | convert(n, ans); 10 | return ans; 11 | } 12 | void convert(int n, string& ans) { 13 | if (n <= 26) { 14 | ans += 'A' + n - 1; 15 | } 16 | else { 17 | convert((n-1)/26, ans); 18 | ans += 'A' + (n-1)%26; 19 | // cout << ans << "---" << endl; 20 | } 21 | } 22 | }; 23 | 24 | int main() 25 | { 26 | Solution s; 27 | cout << s.convertToTitle(10000)<< endl; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /factorialTrailingZeroes/factorialTrailingZeroes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution{ 5 | public: 6 | int trailingZeroes(int n) { 7 | return n == 0 ? 0 : n/5 + trailingZeroes(n/5); 8 | } 9 | }; 10 | 11 | int main() 12 | { 13 | Solution s; 14 | cout << s.trailingZeroes(30)<< endl; 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /fibonacciNumber/fibonacciNumber.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int fib(int N) { 4 | if (N <= 1) return N; 5 | int f0 = 0, f1 = 1; 6 | while (N-- > 1) { 7 | int sum = f0 + f1; 8 | f0 = f1; 9 | f1 = sum; 10 | } 11 | return f1; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /findAllDuplicatesInAnArray/findAllDuplicatesInAnArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution{ 7 | public: 8 | vector findDuplicates(vector& nums) { 9 | vector ans; 10 | for (int i = 0; i < nums.size(); i++) { 11 | int index = abs(nums[i]) - 1; 12 | if (nums[index] < 0) 13 | ans.push_back(index+1); 14 | else 15 | nums[index] = -nums[index]; 16 | } 17 | return ans; 18 | } 19 | }; 20 | 21 | int main() 22 | { 23 | Solution s; 24 | int a[8] = {4,3,2,7,8,2,3,1}; 25 | vector vec(a, a+8); 26 | vector res = s.findDuplicates(vec); 27 | for (int i : res) 28 | cout << i << " "; 29 | cout << endl; 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /findMinimumInRotatedSortedArray/findMinimumInRotatedSortedArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | int findMin(vector& nums) { 8 | int left = 0, right = nums.size() - 1; 9 | while (left + 1 < right) { 10 | int mid = left + (right - left) / 2; 11 | if (nums[mid] > nums[right]) 12 | left = mid; 13 | else 14 | right = mid; 15 | } 16 | return min (nums[left], nums[right]); 17 | } 18 | }; 19 | 20 | int main() 21 | { 22 | Solution s; 23 | int a[7] = {3,1,2,7,0,1,2}; 24 | vector vec(a, a+3); 25 | cout << s.findMin(vec); 26 | cout << endl; 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /findMinimumInRotatedSortedArray/findMinimumInRotatedSortedArray.java: -------------------------------------------------------------------------------- 1 | // 153, all nums are unique 2 | 3 | class Solution { 4 | public int findMin(int[] nums) { 5 | int left = 0, right = nums.length - 1; 6 | while (left + 1 < right) { 7 | int mid = left + (right - left) / 2; 8 | if (nums[mid] > nums[right]) { // mid must be in left part 9 | left = mid; 10 | } else { // mid must be in right part 11 | right = mid; 12 | } 13 | } 14 | if (nums[left] < nums[right]) return nums[left]; 15 | else return nums[right]; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /findMinimumInRotatedSortedArray/findMinimumInRotatedSortedArray2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | int findMin(vector& nums) { 8 | int left = 0, right = nums.size()-1; 9 | while (left < right) { 10 | int mid = left + (right-left)/2; 11 | if (nums[mid] <= nums[right]) { 12 | right = mid; 13 | } else { 14 | left = mid + 1; 15 | } 16 | } 17 | return nums[left]; 18 | } 19 | }; 20 | 21 | int main() 22 | { 23 | Solution s; 24 | int a[7] = {3,1,2,7,0,1,2}; 25 | vector vec(a, a+3); 26 | cout << s.findMin(vec); 27 | cout << endl; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /findMinimumInRotatedSortedArrayII/findMinimumInRotatedSortedArrayII.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findMin(int[] nums) { 3 | int left = 0, right = nums.length - 1; 4 | while (left + 1 < right) { 5 | int mid = left + (right - left) / 2; 6 | if (nums[mid] > nums[right]) { // mid must be in left part 7 | left = mid; 8 | } else if (nums[mid] < nums[right]) { // mid must be in right part 9 | right = mid; 10 | } else { 11 | right--; // not matter mid in left or right(we don't know), min should be in the left side of mid 12 | } 13 | } 14 | if (nums[left] < nums[right]) return nums[left]; 15 | else return nums[right]; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /findPeakElement/findPeakElement.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findPeakElement(int[] nums) { 3 | int len = nums.length; 4 | if (len == 1) return 0; 5 | if (nums[0] > nums[1]) return 0; 6 | if (nums[len - 1] > nums[len - 2]) return len - 1; 7 | int left = 1, right = nums.length - 2; 8 | while (left + 1 < right) { 9 | int mid = left + (right - left) / 2; 10 | if (nums[mid] > nums[mid - 1] && nums[mid] > nums[mid + 1]) { 11 | return mid; 12 | } else if (nums[mid] > nums[mid - 1]) { 13 | left = mid; 14 | } else { 15 | right = mid; 16 | } 17 | } 18 | if (nums[left] < nums[right]) return right; 19 | else return left; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /findSmallestLetterGreaterThanTarget/findSmallestLetterGreaterThanTarget.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public char nextGreatestLetter(char[] letters, char target) { 3 | int n = letters.length; 4 | int left = 0, right = n - 1; 5 | while (left + 1 < right) { 6 | int mid = left + (right - left) / 2; 7 | if (letters[mid] > target) { 8 | right = mid; 9 | } else { 10 | left = mid; 11 | } 12 | } 13 | if (letters[left] > target) return letters[left]; 14 | else if (letters[right] > target) return letters[right]; 15 | else return letters[0]; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /findTheCelebrity/findTheCelebrity.cpp: -------------------------------------------------------------------------------- 1 | // Forward declaration of the knows API. 2 | bool knows(int a, int b); 3 | 4 | class Solution { 5 | public: 6 | int findCelebrity(int n) { 7 | int candidate = 0; 8 | for (int i = 1; i < n; i++) { 9 | if (knows(candidate, i)) 10 | candidate = i; 11 | } 12 | for (int i = 0; i < n; i++) { 13 | if (i != candidate) { 14 | if (knows(candidate, i) || !knows(i, candidate)) 15 | return -1; 16 | } 17 | } 18 | return candidate; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /findTheChildWhoHasTheBallAfterKSeconds/findTheChildWhoHasTheBallAfterKSeconds.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numberOfChild(int n, int k) { 3 | int remain = k % (2 * n - 2); 4 | if (remain < n - 1) return remain; 5 | else return 2 * (n - 1) - remain; 6 | } 7 | } -------------------------------------------------------------------------------- /findTheDifference/findTheDifference.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | char findTheDifference(string s, string t) { 8 | char ans; 9 | if (s.empty()) 10 | return t[0]; 11 | int hash[26] = {0}; 12 | int size = s.length(); 13 | for (int i = 0; i < size; i++) { 14 | hash[s[i] - 'a']++; 15 | } 16 | for (int j = 0; j < size + 1; j++) { 17 | --hash[t[j] - 'a']; 18 | } 19 | for (int k = 0; k < 26; k++) { 20 | if (hash[k] != 0) 21 | ans = char('a' + k); 22 | } 23 | return ans; 24 | } 25 | }; 26 | 27 | int main() 28 | { 29 | Solution s; 30 | string ss = "abcd"; 31 | string p = "abcde"; 32 | cout << s.findTheDifference(ss, p); 33 | cout << endl; 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /findTheDifference/findTheDifference2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | char findTheDifference(string s, string t) { 8 | char c = t.back(); 9 | for (int i = 0; i < s.length(); i++) { 10 | c ^= s[i]; 11 | c ^= t[i]; 12 | } 13 | return c; 14 | } 15 | }; 16 | 17 | int main() 18 | { 19 | Solution s; 20 | string ss = "abcd"; 21 | string p = "abcde"; 22 | cout << s.findTheDifference(ss, p); 23 | cout << endl; 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /findTheDistanceValueBetweenTwoArrays/findTheDistanceValueBetweenTwoArrays.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findTheDistanceValue(vector& arr1, vector& arr2, int d) { 4 | int res = 0; 5 | for (int i = 0; i < arr1.size(); i++) { 6 | bool flag = true; 7 | for (int j = 0; j < arr2.size(); j++) { 8 | if (abs(arr1[i] - arr2[j]) <= d) { 9 | flag = false; 10 | break; 11 | } 12 | } 13 | if (flag) res++; 14 | } 15 | return res; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /findTheDistanceValueBetweenTwoArrays/findTheDistanceValueBetweenTwoArrays_binarySearch.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findTheDistanceValue(vector& arr1, vector& arr2, int d) { 4 | int res = 0; 5 | sort(arr2.begin(), arr2.end()); 6 | for (int i = 0; i < arr1.size(); i++) { 7 | auto it1 = lower_bound(arr2.begin(), arr2.end(), arr1[i] - d); 8 | auto it2 = upper_bound(arr2.begin(), arr2.end(), arr1[i] + d); 9 | if (it1 == it2) res++; 10 | } 11 | return res; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /findTheDuplicateNumber/findTheDuplicateNumber.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int findDuplicate(vector& nums) { 8 | int slow = nums[0], fast = nums[0]; 9 | while (1) { 10 | slow = nums[slow]; 11 | fast = nums[nums[fast]]; 12 | if (slow == fast) 13 | break; 14 | } 15 | fast = nums[0]; 16 | while (slow != fast) { 17 | slow = nums[slow]; 18 | fast = nums[fast]; 19 | } 20 | return slow; 21 | } 22 | }; 23 | 24 | int main() 25 | { 26 | Solution s; 27 | int a[4] = {1,2,3,1}; 28 | vector vec(a, a+2); 29 | cout << s.findDuplicate(vec); 30 | cout << endl; 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /findTheMaximumLengthOfValidSubsequenceII/findTheMaximumLengthOfValidSubsequenceII.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maximumLength(int[] nums, int k) { 3 | int res = 0; 4 | int[][] dp = new int[k][k]; 5 | for (int i = 0; i < nums.length; i++) { 6 | for (int j = 0; j < k; j++) { 7 | dp[nums[i] % k][j] = dp[j][nums[i] % k] + 1; 8 | res = Math.max(res, dp[nums[i] % k][j]); 9 | } 10 | } 11 | return res; 12 | } 13 | } -------------------------------------------------------------------------------- /findTheMinimumAreaToCoverAllOnesI/findTheMinimumAreaToCoverAllOnesI.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minimumArea(int[][] grid) { 3 | int topI = grid.length; 4 | int downI = 0; 5 | int leftJ = grid[0].length; 6 | int rightJ = 0; 7 | for (int i = 0; i < grid.length; i++) { 8 | for (int j = 0; j < grid[0].length; j++) { 9 | if (grid[i][j] == 1) { 10 | topI = Math.min(topI, i); 11 | downI = Math.max(downI, i); 12 | leftJ = Math.min(leftJ, j); 13 | rightJ = Math.max(rightJ, j); 14 | } 15 | } 16 | } 17 | return (rightJ - leftJ + 1) * (downI - topI + 1); 18 | } 19 | } -------------------------------------------------------------------------------- /findTheNthValueAfterKSeconds/findTheNthValueAfterKSeconds.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int valueAfterKSeconds(int n, int k) { 3 | int[] arr = new int[n]; 4 | for (int i = 0; i < n; i++) arr[i] = 1; 5 | for (int i = 0; i < k; i++) { 6 | for (int j = 0; j < n; j++) { 7 | if (j > 0) { 8 | arr[j] += arr[j - 1]; 9 | arr[j] %= 1000000007; 10 | } 11 | } 12 | } 13 | return (int) (arr[n - 1] % 1000000007); 14 | } 15 | } -------------------------------------------------------------------------------- /firstBadVersion/firstBadVersion.java: -------------------------------------------------------------------------------- 1 | /* The isBadVersion API is defined in the parent class VersionControl. 2 | boolean isBadVersion(int version); */ 3 | 4 | public class Solution extends VersionControl { 5 | public int firstBadVersion(int n) { 6 | if (n == 1 && isBadVersion(1)) return 1; 7 | int left = 1, right = n; 8 | while (left + 1 < right) { 9 | int mid = left + (right - left) / 2; 10 | if (isBadVersion(mid)) { 11 | right = mid; 12 | } else { 13 | left = mid; 14 | } 15 | } 16 | if (isBadVersion(left)) return left; 17 | if (isBadVersion(right)) return right; 18 | return -1; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /firstUniqueCharacterInaString/firstUniqueCharacterInaString.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | int firstUniqChar(string s) { 8 | int hash[26] = {0}; 9 | int size = s.length(); 10 | for (int i = 0; i < size; i++) { 11 | hash[s[i] - 'a']++; 12 | } 13 | for (int i = 0; i < size; i++) { 14 | if (hash[s[i] - 'a'] == 1) 15 | return i; 16 | } 17 | return -1; 18 | } 19 | }; 20 | 21 | int main() 22 | { 23 | Solution s; 24 | string str = "loveleetcode"; 25 | cout << s.firstUniqChar(str); 26 | cout << endl; 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /fizzBuzz/fizzBuzz.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | vector fizzBuzz(int n) { 8 | vector res(n, ""); 9 | for (int i = 1; i <= n; i++) { 10 | int mod_3 = i % 3, mod_5 = i % 5; 11 | if (mod_3 && mod_5) { 12 | res[i - 1] = to_string(i); 13 | } else { 14 | if (mod_3 == 0) 15 | res[i - 1] += "Fizz"; 16 | if (mod_5 == 0) 17 | res[i - 1] += "Buzz"; 18 | } 19 | } 20 | return res; 21 | } 22 | }; 23 | 24 | int main() 25 | { 26 | Solution s; 27 | vector vec = s.fizzBuzz(20); 28 | for (string str : vec) 29 | cout << str << endl; 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /flatten2DVector/flatten2DVector.cpp: -------------------------------------------------------------------------------- 1 | class Vector2D { 2 | public: 3 | Vector2D(vector>& vec2d) { 4 | cur = vec2d.begin(); 5 | end = vec2d.end(); 6 | i = 0; 7 | } 8 | 9 | int next() { 10 | int res = -1; 11 | if (hasNext()) { 12 | res = (*cur)[i]; 13 | i++; 14 | } 15 | return res; 16 | } 17 | 18 | bool hasNext() { 19 | while (cur != end && i == cur->size()) { 20 | cur++; 21 | i = 0; 22 | } 23 | return cur != end; 24 | } 25 | vector >::iterator cur, end; 26 | int i; 27 | }; 28 | -------------------------------------------------------------------------------- /flipGame/flipGame.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | vector generatePossibleNextMoves(string s) { 8 | vector res; 9 | if (s.length() < 2) 10 | return res; 11 | for (int i = 1; i < s.length(); i++) { 12 | if (s[i] == '+' && s[i] == s[i - 1]) { 13 | string temp = s; 14 | temp[i - 1] = temp[i] = '-'; 15 | res.push_back(temp); 16 | } 17 | } 18 | return res; 19 | } 20 | }; 21 | 22 | int main() { 23 | Solution s; 24 | for(string& ss : s.generatePossibleNextMoves("++++")) { 25 | cout << ss << endl; 26 | } 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /flippingAnImage/flippingAnImage.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | vector> flipAndInvertImage(vector>& A) { 8 | for (auto& row : A) 9 | reverse(row.begin(), row.end()); 10 | for (auto& row : A) 11 | for (int& b : row) 12 | b ^= 1; 13 | return A; 14 | } 15 | }; 16 | 17 | int main() { 18 | Solution s; 19 | vector > A = {{1,1,0},{1,0,1},{0,0,0}}; 20 | for (auto& row : s.flipAndInvertImage(A)) { 21 | for (int b : row) 22 | cout << b << " "; 23 | cout << endl; 24 | } 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /frogJump/frogJump.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canCross(int[] stones) { 3 | Map> dp = new HashMap<>(); 4 | for (int stone : stones) { 5 | dp.put(stone, new HashSet<>()); 6 | } 7 | dp.get(0).add(0); 8 | 9 | for (int s : stones) { 10 | for (int k : dp.get(s)) { 11 | if (k - 1 > 0 && dp.containsKey(s + k - 1)) 12 | dp.get(s + k - 1).add(k - 1); 13 | if (dp.containsKey(s + k)) 14 | dp.get(s + k).add(k); 15 | if (dp.containsKey(s + k + 1)) 16 | dp.get(s + k + 1).add(k + 1); 17 | } 18 | } 19 | 20 | return !dp.get(stones[stones.length - 1]).isEmpty(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /gasStation/gasStation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int canCompleteCircuit(vector& gas, vector& cost) { 4 | if (gas.size() == 0 || cost.size() == 0) return -1; 5 | int tank = 0; 6 | int res = 0; 7 | int total = 0; 8 | for (int i = 0; i < cost.size(); i++) { 9 | tank += gas[i] - cost[i]; 10 | if (tank < 0) { 11 | res = i + 1; 12 | tank = 0; 13 | } 14 | total += gas[i] - cost[i]; 15 | } 16 | return total >= 0 ? res : -1; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /grayCode/grayCode.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | vector grayCode(int n) { 8 | vector ans; 9 | for (int i = 0; i < (1 << n); i++) 10 | ans.push_back(i ^ i>>1); 11 | return ans; 12 | } 13 | unsigned int binaryToGray(unsigned int num) { 14 | return (num >> 1)^num; 15 | } 16 | unsigned int grayToBinary(unsigned int num) { 17 | for (unsigned int mask = num >> 1; mask != 0; mask = mask >> 1) { 18 | num = num ^ mask; 19 | } 20 | return num; 21 | } 22 | }; 23 | 24 | int main() 25 | { 26 | Solution s; 27 | vector res = s.grayCode(3); 28 | for (int i : res) 29 | cout << i << " "; 30 | cout << endl; 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /guessNumberHigherOrLower/guessNumberHigerOrLower.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int guess(int num) { 7 | if (num < 6) 8 | return 1; 9 | else if (num > 6) 10 | return -1; 11 | else 12 | return 0; 13 | } 14 | 15 | class Solution{ 16 | public: 17 | int guessNumber(int n) { 18 | int low = 1, high = n; 19 | while (low <= high) { 20 | int mid = low + (high-low)/2; 21 | if (guess(mid) == -1) 22 | high = mid - 1; 23 | else if (guess(mid) == 1) 24 | low = mid + 1; 25 | else 26 | return mid; 27 | } 28 | return -1; 29 | } 30 | }; 31 | 32 | int main() 33 | { 34 | Solution s; 35 | cout << s.guessNumber(10) << endl; 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /hIndex/hIndex.cpp: -------------------------------------------------------------------------------- 1 | // clang++ hIndex.cpp -std=c++11 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution{ 8 | public: 9 | int hIndex(vector& citations) { 10 | int ans = 0; 11 | int size = citations.size(); 12 | vector hash(size+1, 0); 13 | for (int i = 0; i < size; i++) { 14 | if (citations[i] > size) 15 | hash[size]++; 16 | else 17 | hash[citations[i]]++; 18 | } 19 | int sum = 0; 20 | for (int i = size; i >= 0; i--) { 21 | sum += hash[i]; 22 | if (sum >= i) { 23 | ans = i; 24 | break; 25 | } 26 | } 27 | return ans; 28 | } 29 | }; 30 | 31 | int main() 32 | { 33 | Solution s; 34 | vector vec = {3,0,6,1,5}; 35 | cout << s.hIndex(vec); 36 | cout << endl; 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /hIndex/hIndex2.cpp: -------------------------------------------------------------------------------- 1 | // clang++ hIndex2.cpp -std=c++11 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution{ 8 | public: 9 | int hIndex(vector& citations) { 10 | int res = 0; 11 | sort(citations.begin(), citations.end(), greater()); 12 | for (int i = 0; i < citations.size(); i++) { 13 | if (citations[i] > i) 14 | res++; 15 | } 16 | return res; 17 | } 18 | }; 19 | 20 | int main() 21 | { 22 | Solution s; 23 | vector vec = {3,0,6,1,5}; 24 | cout << s.hIndex(vec); 25 | cout << endl; 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /hIndexII/hIndexII.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int hIndex(int[] citations) { 3 | int len = citations.length; 4 | if (len == 1) { 5 | if (citations[0] >= 1) return 1; 6 | else return 0; 7 | } 8 | int left = 0, right = len - 1; 9 | while (left + 1 < right) { 10 | int mid = left + (right - left) / 2; 11 | if (citations[mid] >= len - mid) { 12 | right = mid; 13 | } else { 14 | left = mid; 15 | } 16 | } 17 | if (citations[left] >= len - left) return len - left; 18 | else if (citations[right] >= len - right) return len - right; 19 | else return 0; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /hammingDistance/hanmmingDistance.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution{ 5 | public: 6 | int hammingDistance(int x, int y) { 7 | uint32_t ans = 0; 8 | int n = x^y; 9 | for (int i = 0; i < 32; i++) { 10 | if ((n&1) == 1) 11 | ans++; 12 | n >>= 1; 13 | } 14 | return ans; 15 | } 16 | }; 17 | 18 | int main() 19 | { 20 | Solution s; 21 | cout << s.hammingDistance(1, 4); 22 | cout << endl; 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /happyNumber/happyNumber.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution{ 7 | public: 8 | bool isHappy(int n) { 9 | unordered_set set; 10 | int squareSum = 0; 11 | int oldN = 0; 12 | while (set.find(n) == set.end()) { 13 | squareSum = 0; 14 | oldN = n; 15 | while (n > 0) { 16 | squareSum += (n%10) * (n%10); 17 | n /= 10; 18 | } 19 | if (squareSum == 1) { 20 | return true; 21 | } 22 | else { 23 | set.insert(oldN); 24 | n = squareSum; 25 | } 26 | } 27 | return false; 28 | } 29 | }; 30 | 31 | int main() 32 | { 33 | Solution s; 34 | cout << s.isHappy(19); 35 | cout << endl; 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /houseRobber/houseRobber.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int rob(vector& nums) { 8 | if (nums.size() == 0) return 0; 9 | vector dp(nums.size(), 0); 10 | for (int i = 0; i < dp.size(); i++) { 11 | int prev1 = i - 1 >= 0 ? dp[i - 1] : 0; 12 | int prev2 = i - 2 >= 0 ? dp[i - 2] : 0; 13 | dp[i] = max (prev2 + nums[i], prev1); 14 | } 15 | return dp.back(); 16 | } 17 | }; 18 | 19 | int main() 20 | { 21 | int a[6] = {0, 0, 3, 0, 2, 0}; 22 | vector vec(a, a+6); 23 | Solution s; 24 | cout << s.rob(vec) << endl; 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /houseRobber/houseRobber.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int rob(int[] nums) { 3 | if (nums.length < 2) return nums[0]; 4 | int[] dp = new int[nums.length]; 5 | dp[0] = nums[0]; 6 | dp[1] = nums[1]; 7 | if (nums.length == 2) return Math.max(dp[0], dp[1]); 8 | dp[2] = nums[0] + nums[2]; 9 | int res = Math.max(dp[1], dp[2]); 10 | for (int i = 3; i < dp.length; i++) { 11 | dp[i] = Math.max(dp[i - 2], dp[i - 3]) + nums[i]; 12 | res = Math.max(res, dp[i]); 13 | } 14 | return res; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /houseRobber/houseRobber3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int rob(vector& nums) { 8 | int res = 0; 9 | if (nums.size() == 0) return res; 10 | vector dp(nums.size(), 0); 11 | for (int i = 0; i < dp.size(); i++) { 12 | int prev1 = i - 2 >= 0 ? dp[i - 2] : 0; 13 | int prev2 = i - 3 >= 0 ? dp[i - 3] : 0; 14 | dp[i] = max (prev1, prev2) + nums[i]; 15 | res = max (res, dp[i]); 16 | } 17 | return res; 18 | } 19 | }; 20 | 21 | int main() 22 | { 23 | int a[6] = {0, 0, 3, 0, 2, 0}; 24 | vector vec(a, a+6); 25 | Solution s; 26 | cout << s.rob(vec) << endl; 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /houseRobber/houseRobber_2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int rob(vector& nums) { 8 | int n = nums.size(); 9 | if (n == 0) 10 | return 0; 11 | if (n == 1) 12 | return nums[0]; 13 | vector dp(3, INT_MIN); 14 | dp[0] = nums[0]; 15 | dp[1] = max (nums[0], nums[1]); 16 | for (int i = 2; i < n; i++) { 17 | dp[i % 3] = max (dp[(i - 2) % 3] + nums[i], dp[(i - 1) % 3]); 18 | } 19 | return dp[(n - 1) % 3]; 20 | } 21 | }; 22 | 23 | int main() 24 | { 25 | int a[6] = {0, 0, 3, 0, 2, 0}; 26 | vector vec(a, a+6); 27 | Solution s; 28 | cout << s.rob(vec) << endl; 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /houseRobber/houseRobber_2.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int rob(int[] nums) { 3 | if (nums.length < 2) return nums[0]; 4 | int[] g = new int[nums.length]; // must rob 5 | int[] h = new int[nums.length]; // must not rob 6 | g[0] = nums[0]; 7 | h[0] = 0; 8 | for (int i = 1; i < nums.length; i++) { 9 | g[i] = nums[i] + h[i - 1]; 10 | h[i] = Math.max(g[i - 1], h[i - 1]); 11 | } 12 | return Math.max(g[nums.length - 1], h[nums.length - 1]); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /howManyNumberAreSmallerThanTheCurrentNumber/howManyNumberAreSmallerThanTheCurrentNumber_arrHash.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] smallerNumbersThanCurrent(int[] nums) { 3 | int[] res = new int[nums.length]; 4 | int[] count = new int[101]; 5 | for (int n : nums) count[n]++; 6 | int[] smaller = new int[101]; 7 | smaller[0] = 0; 8 | for (int i = 1; i < smaller.length; i++) { 9 | smaller[i] = smaller[i - 1] + count[i - 1]; 10 | } 11 | for (int i = 0; i < res.length; i++) { 12 | res[i] = smaller[nums[i]]; 13 | } 14 | return res; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /howManyNumberAreSmallerThanTheCurrentNumber/howManyNumberAreSmallerThanTheCurrentNumber_lowerbound.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] smallerNumbersThanCurrent(int[] nums) { 3 | int[] res = new int[nums.length]; 4 | int[] sortNums = nums.clone(); 5 | Arrays.sort(sortNums); 6 | for (int i = 0; i < nums.length; i++ ) { 7 | res[i] = lowerBound(sortNums, nums[i]); 8 | } 9 | return res; 10 | } 11 | 12 | int lowerBound(int a[], int x) { // x is the target value or key 13 | int l = -1, r = a.length; 14 | while (l + 1 < r) { 15 | int m = l + (r - l) / 2; 16 | if (a[m] >= x) r = m; 17 | else l = m; 18 | } 19 | return r; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /implementStrStr/implementStrStr2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int strStr(string haystack, string needle) { 8 | if (haystack == needle) return 0; 9 | for (int i = 0; i <= (int)haystack.size() - (int)needle.size(); i++) { 10 | if (haystack.substr(i, needle.size()) == needle) return i; 11 | } 12 | return -1; 13 | } 14 | }; 15 | 16 | int main() 17 | { 18 | Solution s; 19 | string haystack = "babcabceabcabcabcaaa"; 20 | string needle = "abcabcaaa"; 21 | cout << s.strStr(haystack, needle) << endl; 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /increasingTripletSubsequence/increasingTripletSubsequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | bool increasingTriplet(vector& nums) { 8 | if (nums.size() < 3) 9 | return false; 10 | int minV = INT_MAX, secondMinV = INT_MAX; 11 | for (int i = 0; i < nums.size(); i++) { 12 | if (nums[i] <= minV) 13 | minV = nums[i]; 14 | else if (nums[i] <= secondMinV) 15 | secondMinV = nums[i]; 16 | else 17 | return true; 18 | } 19 | return false; 20 | } 21 | }; 22 | 23 | int main() 24 | { 25 | Solution s; 26 | int a[6] = {6, 5, 6, 0, 1, 7}; 27 | vector vec(a, a+6); 28 | cout << s.increasingTriplet(vec); 29 | cout << endl; 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /integerBreak/integerBreak.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | int integerBreak(int n) { 8 | if (n == 2) 9 | return 1; 10 | if (n == 3) 11 | return 2; 12 | if (n == 4) 13 | return 4; 14 | int product = 1; 15 | while (n > 4) { 16 | product *= 3; 17 | n -= 3; 18 | } 19 | product *= n; 20 | return product; 21 | } 22 | }; 23 | 24 | int main() 25 | { 26 | Solution s; 27 | cout << s.integerBreak(10); 28 | cout << endl; 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /integerReplacement/integerReplacement.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int integerReplacement(int n) { 7 | if (n == 1) 8 | return 0; 9 | long m = n; 10 | if (m % 2 == 0) 11 | return integerReplacement(m / 2) + 1; 12 | else 13 | return min (integerReplacement((m + 1) / 2), integerReplacement((m - 1) / 2) ) + 2; 14 | } 15 | }; 16 | 17 | int main() 18 | { 19 | Solution s; 20 | cout << s.integerReplacement(8) << endl; 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /isSubsequence/isSubsequence.cpp: -------------------------------------------------------------------------------- 1 | // clang++ isSubsequence.cpp -std=c++11 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | bool isSubsequence(string s, string t) { 10 | int len_s = s.length(), len_t = t.length(); 11 | int p_s = 0, p_t = 0; 12 | while (p_t < len_t) { 13 | if (s[p_s] == t[p_t]) { 14 | p_s++; p_t++; 15 | } else { 16 | p_t++; 17 | } 18 | } 19 | return p_s == len_s; 20 | } 21 | }; 22 | 23 | int main() 24 | { 25 | Solution s; 26 | string s1 = "abc"; 27 | string s2 = "ahbgdc"; 28 | cout << s.isSubsequence(s1, s2) << endl; 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /isomorphicStrings/isomorphicStrings.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | bool isIsomorphic(string s, string t) { 8 | int sSize = s.length(); 9 | int tSize = t.length(); 10 | if (sSize != tSize) 11 | return false; 12 | unordered_map m1; 13 | unordered_map m2; 14 | for (int i = 0; i < sSize; i++) { 15 | if (m1[s[i]] != m2[t[i]]) 16 | return false; 17 | m1[s[i]] = i + 1; // defalut is 0,plus one to differ from defalut 18 | m2[t[i]] = i + 1; 19 | } 20 | return true; 21 | } 22 | }; 23 | 24 | int main() 25 | { 26 | Solution s; 27 | string str1 = "aba"; 28 | string str2 = "baa"; 29 | cout << s.isIsomorphic(str1, str2); 30 | cout << endl; 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /judgeRouteCircle/judgeRouteCircle.cpp: -------------------------------------------------------------------------------- 1 | //clang++ judgeRouteCircle.cpp -std=c++11 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | class Solution { 7 | public: 8 | bool judgeCircle(string moves) { 9 | int v = 0, h = 0; 10 | for (char ch : moves) { 11 | switch(ch) { 12 | case 'U' : v++; break; 13 | case 'D' : v--; break; 14 | case 'R' : h++; break; 15 | case 'L' : h--; break; 16 | } 17 | } 18 | return v == 0 && h == 0; 19 | } 20 | }; 21 | int main(void) 22 | { 23 | Solution s; 24 | string moves = "UDLLRRU"; 25 | cout << s.judgeCircle(moves) << endl; 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /jumpGame/jumpGame_2.cpp: -------------------------------------------------------------------------------- 1 | // clang++ jumpGame_2.cpp -std=c++11 2 | 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | 9 | class Solution{ 10 | public: 11 | bool canJump(vector& nums) { 12 | int size = nums.size(); 13 | int reach = 0; 14 | int i; 15 | for (i = 0; i < size && i <= reach; i++) 16 | reach = max(i + nums[i], reach); 17 | return i == size; 18 | } 19 | }; 20 | 21 | int main() 22 | { 23 | Solution s; 24 | vector nums = {2,3,1,1,4}; 25 | vector nums2 = {3,2,1,0,4}; 26 | vector nums3 = {0,1}; 27 | vector nums4 = {0}; 28 | cout << s.canJump(nums) << endl; 29 | cout << s.canJump(nums2) << endl; 30 | cout << s.canJump(nums3) << endl; 31 | cout << s.canJump(nums4) << endl; 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /kdiffPairsInArray/kdiffPairsInArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int findPairs(vector& nums, int k) { 9 | if (k < 0) return 0; 10 | int res = 0; 11 | unordered_map m; 12 | for (int n : nums) m[n]++; 13 | for (auto& p : m) { 14 | if (k == 0) { 15 | if (p.second > 1) res++; 16 | } else { 17 | if (m.count(p.first + k)) res++; 18 | } 19 | } 20 | return res; 21 | } 22 | }; 23 | 24 | int main() 25 | { 26 | Solution s; 27 | int a[5] = {1,3,1,5,4}; 28 | vector vec(a, a+5); 29 | cout << s.findPairs(vec, 0); 30 | cout << endl; 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /kdiffPairsInArray/kdiffPairsInArray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findPairs(int[] nums, int k) { 3 | int res = 0; 4 | Map m = new HashMap<>(); 5 | for (int n : nums) { 6 | if (!m.containsKey(n)) { 7 | m.put(n, 0); 8 | } 9 | m.put(n, m.get(n) + 1); 10 | } 11 | for (Map.Entry entry : m.entrySet()) { 12 | if (k == 0) { 13 | if (entry.getValue() > 1) res++; 14 | } else { 15 | if (m.containsKey(entry.getKey() + k)) res++; 16 | } 17 | } 18 | return res; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /kthLargestElementInAnArray/kthLargestElementInAnArray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findKthLargest(int[] nums, int k) { 3 | Queue pq = new PriorityQueue<>(); 4 | for (int i = 0; i < nums.length; i++) { 5 | pq.add(nums[i]); 6 | if (pq.size() > k) { 7 | pq.poll(); 8 | } 9 | } 10 | return pq.peek(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /kthLargestElementInAnArray/kthLargestElementInAnArray_2.cpp: -------------------------------------------------------------------------------- 1 | // clang++ kthLargestElementInAnArray_2.cpp -std=c++11 2 | 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | 9 | class Solution { 10 | public: 11 | int findKthLargest(vector& nums, int k) { 12 | priority_queue, greater > pq; 13 | for (int n : nums) { 14 | pq.push(n); 15 | if (pq.size() > k) 16 | pq.pop(); 17 | } 18 | return pq.top(); 19 | } 20 | }; 21 | 22 | int main() 23 | { 24 | Solution s; 25 | vector vec = {3,2,1,5,6,4}; 26 | cout << s.findKthLargest(vec, 2); 27 | cout << endl; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /kthSmallestElementInASortedMatrix/kthSmallestElementInASortedMatrix_pq.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int kthSmallest(int[][] matrix, int k) { 3 | int m = matrix.length, n = matrix[0].length; 4 | PriorityQueue pq = new PriorityQueue<>((t1, t2) -> t1.val - t2.val); 5 | for (int i = 0; i < m; i++) { 6 | pq.offer(new Tuple(i, 0, matrix[i][0])); 7 | } 8 | for (int i = 1; i < k; i++) { 9 | Tuple t = pq.poll(); 10 | if (t.j + 1 >= n) continue; 11 | pq.offer(new Tuple(t.i, t.j + 1, matrix[t.i][t.j + 1])); 12 | } 13 | return pq.poll().val; 14 | } 15 | } 16 | 17 | class Tuple { 18 | public int i, j, val; 19 | public Tuple(int i, int j, int val) { 20 | this.i = i; 21 | this.j = j; 22 | this.val = val; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /kthSymbolInGrammar/kthSymbolInGrammar.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int kthGrammar(int N, int K) { 7 | if (N == 1 && K == 1) 8 | return 0; 9 | if (K % 2 == 0) 10 | return kthGrammar(N - 1, K / 2) == 0 ? 1 : 0; 11 | else 12 | return kthGrammar(N - 1, (K + 1) / 2) == 0 ? 0 : 1; 13 | } 14 | }; 15 | 16 | int main() { 17 | Solution s; 18 | cout << s.kthGrammar(5, 10) << endl; 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /kthSymbolInGrammar/kthSymbolInGrammar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int kthGrammar(int n, int k) { 3 | if (n == 1 && k == 1) return 0; 4 | if (k % 2 != 0) { 5 | return kthGrammar(n - 1, (k - 1) / 2 + 1); 6 | } else { 7 | if (kthGrammar(n - 1, (k - 1) / 2 + 1) == 1) return 0; 8 | else return 1; 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /largestNumber/largestNumber.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution{ 7 | public: 8 | string largestNumber(vector& nums) { 9 | string ans; 10 | if (nums.size() == 0) 11 | return ans; 12 | vector vec; 13 | for (int num : nums) 14 | vec.push_back(to_string(num)); 15 | sort(vec.begin(), vec.end(), [](string &s1, string &s2) {return s1+s2 > s2+s1;}); 16 | for (string &s : vec) { 17 | ans += s; 18 | } 19 | while (ans.length() > 1 && ans[0] == '0') { 20 | ans.erase(0,1); 21 | } 22 | return ans; 23 | } 24 | }; 25 | 26 | int main() 27 | { 28 | Solution s; 29 | int a[5] = {3,30,34,5,9}; 30 | vector nums(a, a+5); 31 | cout << s.largestNumber(nums) << endl; 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /largestSumOfAverages/largestSumOfAverages.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public double largestSumOfAverages(int[] nums, int k) { 3 | double[][] dp = new double[nums.length + 1][k + 1]; 4 | dp[0][0] = 0.0; 5 | double sum0I = 0.0; 6 | for (int i = 1; i <= nums.length; i++) { 7 | sum0I += nums[i - 1]; 8 | dp[i][1] = sum0I / i; 9 | } 10 | for (int j = 2; j <= k; j++) { 11 | for (int i = 1; i <= nums.length; i++) { 12 | double sumXI = 0.0; 13 | for (int x = i - 1; x >= 0; x--) { 14 | sumXI += nums[x]; 15 | dp[i][j] = Math.max(dp[i][j], dp[x][j - 1] + sumXI / (i - x)); 16 | } 17 | } 18 | } 19 | return dp[nums.length][k]; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /lengthOfLastWord/lengthOfLastWord.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | int lengthOfLastWord(string s) { 8 | int ans = 0; 9 | int i = s.length() - 1; 10 | while (s[i] == ' ') 11 | i--; 12 | for (i; i >= 0; i--) { 13 | if (isalpha(s[i])) 14 | ans++; 15 | else 16 | break; 17 | } 18 | return ans; 19 | } 20 | }; 21 | 22 | int main() 23 | { 24 | Solution s; 25 | string str = "hello world"; 26 | cout << s.lengthOfLastWord(str) << endl; 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /longestContinuousIncreasingSubsequence/longestContinuousIncreasingSubsequence.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findLengthOfLCIS(int[] nums) { 3 | int res = 1; 4 | int dp = 1; 5 | for (int i = 1; i < nums.length; i++) { 6 | if (nums[i] > nums[i - 1]) dp++; 7 | else dp = 1; 8 | res = Math.max(res, dp); 9 | } 10 | return res; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /longestIncreasingSubsequence/longestIncreasingSubsequence.cpp: -------------------------------------------------------------------------------- 1 | // clang++ longestIncreasingSubsequence.cpp -std=c++11 2 | 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | class Solution{ 9 | public: 10 | int lengthOfLIS(vector& nums) { 11 | int res = 1; 12 | int len = nums.size(); 13 | if (len == 0) 14 | return 0; 15 | vector m(len, 1); 16 | for (int i = 1; i < len; i++) { 17 | for (int j = 0; j < i; j++) { 18 | if (nums[j] < nums[i] && m[j] + 1 > m[i]) { 19 | m[i] = m[j] + 1; 20 | } 21 | } 22 | res = max(res, m[i]); 23 | }//for 24 | return res; 25 | } 26 | }; 27 | 28 | int main() 29 | { 30 | Solution s; 31 | vector nums = {10,9,2,5,3,7,101,18}; 32 | cout << s.lengthOfLIS(nums) << endl; 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /longestPalindromicSubsequence/longestPalindromicSubsequence.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int longestPalindromeSubseq(String s) { 3 | int res = 0; 4 | int[][] dp = new int[s.length()][s.length()]; 5 | for (int i = s.length() - 1; i >= 0; i--) { 6 | for (int j = i; j < s.length(); j++) { 7 | if (i == j) { 8 | dp[i][j] = 1; 9 | } else { 10 | if (s.charAt(i) == s.charAt(j)) { 11 | dp[i][j] = dp[i + 1][j - 1] + 2; 12 | } else { 13 | dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]); 14 | } 15 | } 16 | } 17 | } 18 | return dp[0][s.length() - 1]; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /longestSubstringWithoutRepeatingCharacters/longestSubstringWithoutRepeatingCharacters.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int lengthOfLongestSubstring(String s) { 3 | int res = 0; 4 | Map map = new HashMap<>(); 5 | int left = 0, right = 0; 6 | while (right < s.length()) { 7 | char c = s.charAt(right); 8 | if (map.containsKey(c)) { 9 | left = Math.max(left, map.get(c) + 1); 10 | } 11 | res = Math.max(res, right - left + 1); 12 | map.put(c, right); 13 | right++; 14 | } 15 | return res; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /longestUncommonSubsequenceI/longestUncommonSubsequenceI.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution{ 7 | public: 8 | int findLUSlength(string a, string b) { 9 | return (a == b) ? -1 : max(a.length(), b.length()); 10 | } 11 | }; 12 | 13 | int main() 14 | { 15 | Solution s; 16 | string str1 = "aba"; 17 | string str2 = "cdc"; 18 | cout << s.findLUSlength(str1, str2) << endl; 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /lowestCommonAncestorOfABinarySearchTree/lowestCommonAncestorOfABinarySearchTree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | 11 | class Solution { 12 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 13 | if (root.val > p.val && root.val > q.val) { 14 | return lowestCommonAncestor(root.left, p, q); 15 | } else if (root.val < p.val && root.val < q.val) { 16 | return lowestCommonAncestor(root.right, p, q); 17 | } else { 18 | return root; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /lowestCommonAncestorOfaBinaryTree/lowestCommonAncestorOfaBinaryTree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | class Solution { 11 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 12 | if (root == null || root.val == p.val || root.val == q.val) return root; 13 | TreeNode leftRes = lowestCommonAncestor(root.left, p, q); 14 | TreeNode rightRes = lowestCommonAncestor(root.right, p, q); 15 | if (leftRes == null) return rightRes; 16 | else if (rightRes == null) return leftRes; 17 | else return root; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /magicalString/magicalString.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int magicalString(int n) { 7 | if (n == 0) 8 | return 0; 9 | int res = 1; 10 | string s = "122"; 11 | int p = 2; 12 | while (s.length() < n) { 13 | char temp = s.back() == '1' ? '2' : '1'; 14 | s += string(s[p] - '0', temp); 15 | if (temp == '1') 16 | res += s[p] - '0'; 17 | p++; 18 | } 19 | if (s.length() > n && s.back() == '1') 20 | res--; 21 | return res; 22 | } 23 | }; 24 | 25 | int main() { 26 | Solution s; 27 | cout << s.magicalString(4) << endl; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /majorityElement/majorityElement_2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int majorityElement(vector& nums) { 8 | int cnt = 1, res = nums[0]; 9 | for (int i = 1; i < nums.size(); i++) { 10 | if (cnt == 0) { 11 | res = nums[i]; 12 | cnt++; 13 | } else if (cnt > 0) { 14 | if (nums[i] != res) cnt--; 15 | else cnt++; 16 | } 17 | } 18 | return res; 19 | } 20 | }; 21 | 22 | int main() 23 | { 24 | Solution s; 25 | int a[7] = {2,6,4,8,10,9,15}; 26 | vector vec(a, a+7); 27 | cout << s.majorityElement(vec) << endl; 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /makeTwoArraysEqualByReversingSubarrays/makeTwoArraysEqualByReversingSubarrays.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canBeEqual(int[] target, int[] arr) { 3 | Map m = new HashMap(); 4 | for (int t : target) { 5 | m.put(t, m.getOrDefault(t, 0) + 1); 6 | } 7 | for (int a : arr) { 8 | int n = m.getOrDefault(a, 0); 9 | if (n <= 0) return false; 10 | m.put(a, n - 1); 11 | } 12 | for (Integer i : m.values()) { 13 | if (i != 0) return false; 14 | } 15 | return true; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /maxChunksToMakeSorted/maxChunksToMakeSorted.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int maxChunksToSorted(vector& arr) { 8 | int res = 0; 9 | int maxV = 0; 10 | for (int i = 0; i < arr.size(); i++) { 11 | maxV = max (maxV, arr[i]); 12 | if (maxV == i) 13 | res++; 14 | } 15 | return res; 16 | } 17 | }; 18 | 19 | int main() { 20 | Solution s; 21 | vector arr = {1,0,2,3,4}; 22 | cout << s.maxChunksToSorted(arr) << endl; 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /maxConsecutiveOnes/maxConsecutiveOnes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | int findMaxConsecutiveOnes(vector& nums) { 8 | int ans = 0; 9 | int size = nums.size(); 10 | if (size < 0) 11 | return ans; 12 | int temp = 0; 13 | for (int i = 0; i < size; i++) { 14 | if (nums[i] == 1) { 15 | if (++temp > ans) 16 | ans = temp; 17 | } 18 | else if (nums[i] == 0) { 19 | temp = 0; 20 | } 21 | 22 | } 23 | return ans; 24 | } 25 | }; 26 | 27 | int main() 28 | { 29 | Solution s; 30 | int a[8] = {1,1,0,1,1,1,0,1}; 31 | vector vec(a, a+8); 32 | cout << s.findMaxConsecutiveOnes(vec) << endl; 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /maxConsecutiveOnesII/maxConsecutiveOnesII.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int findMaxConsecutiveOnes(vector& nums) { 8 | int res = 0; 9 | int left = 0, right = 0, k = 1; 10 | int zero = 0; 11 | while (right < nums.size()) { 12 | if (nums[right++] == 0) 13 | zero++; 14 | while (zero > k) { 15 | if(nums[left++] == 0) 16 | zero--; 17 | } 18 | res = max (res, right - left); 19 | } 20 | return res; 21 | } 22 | }; 23 | 24 | int main() { 25 | Solution s; 26 | vector nums = {1,1,0,1,1,1,0,0,1,1,1,1}; 27 | cout << s.findMaxConsecutiveOnes(nums) << endl; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /maximizeTotalCostOfAlternatingSubarrays/maximizeTotalCostOfAlternatingSubarrays.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long maximumTotalCost(int[] nums) { 3 | long[] dp_pos = new long[nums.length]; // dp must end with nums i && nums i must end with '+' 4 | long[] dp_neg = new long[nums.length]; // dp must end with nums i && nums i must end with '-' 5 | dp_pos[0] = nums[0]; 6 | dp_neg[0] = Long.MIN_VALUE; 7 | for (int i = 1; i < nums.length; i++) { 8 | dp_pos[i] = Math.max(dp_pos[i - 1], dp_neg[i - 1]) + nums[i]; // nums i be one subarry or not 9 | dp_neg[i] = dp_pos[i - 1] - nums[i]; // nums i can not be one subarry under '-' case 10 | } 11 | return Math.max(dp_pos[nums.length - 1], dp_neg[nums.length - 1]); 12 | } 13 | } -------------------------------------------------------------------------------- /maximumPointsAfterEnemyBattles/maximumPointsAfterEnemyBattles.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long maximumPoints(int[] enemyEnergies, int currentEnergy) { 3 | int minEnemyEnergy = enemyEnergies[0]; 4 | long totalEnergies = 0; 5 | for (int i = 0; i < enemyEnergies.length; i++) { 6 | totalEnergies += enemyEnergies[i]; 7 | minEnemyEnergy = Math.min(minEnemyEnergy, enemyEnergies[i]); 8 | } 9 | if (currentEnergy >= minEnemyEnergy) 10 | return (totalEnergies - minEnemyEnergy + currentEnergy) / minEnemyEnergy; 11 | else return 0; 12 | } 13 | } -------------------------------------------------------------------------------- /maximumProductOfThreeNumbers/maximumProductOfThreeNumbers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | int maximumProduct(vector& nums) { 8 | int size = nums.size(); 9 | sort(nums.begin(), nums.end()); 10 | int a = nums[0] * nums[1] * nums[size-1]; 11 | int ans = max(a, nums[size-3]*nums[size-2]*nums[size-1]); 12 | return ans; 13 | } 14 | }; 15 | 16 | int main() 17 | { 18 | Solution s; 19 | int a[4] = {1,2,3,4}; 20 | vector vec(a, a+4); 21 | cout << s.maximumProduct(vec); 22 | cout << endl; 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /maximumProductSubarray/maximumProductSubarray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxProduct(int[] nums) { 3 | int res = nums[0]; 4 | int[] g = new int[nums.length]; // max prod 5 | int[] h = new int[nums.length]; // min prod 6 | g[0] = h[0] = nums[0]; 7 | for (int i = 1; i < nums.length; i++) { 8 | int c1 = g[i - 1] * nums[i]; 9 | int c2 = h[i - 1] * nums[i]; 10 | g[i] = Math.max(Math.max(c1, c2), nums[i]); 11 | h[i] = Math.min(Math.min(c1, c2), nums[i]); 12 | res = Math.max(res, g[i]); 13 | } 14 | return res; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /maximumSizeSubarraySumEqualsK/maximumSizeSubarraySumEqualsK.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution{ 7 | public: 8 | int maxSubArrayLen(vector& nums, int k) { 9 | int res = 0; 10 | unordered_map m; 11 | int preSum = 0; 12 | m[0] = -1; 13 | for (int i = 0; i < nums.size(); i++) { 14 | preSum += nums[i]; 15 | if (m.count(preSum - k)) { 16 | res = max (res, i - m[preSum - k]); 17 | } 18 | if (!m.count(preSum)){ 19 | m[preSum] = i; 20 | } 21 | } 22 | return res; 23 | } 24 | }; 25 | 26 | int main() 27 | { 28 | Solution s; 29 | int a[5] = {1,-1,5,-2,3}; 30 | vector vec(a, a+5); 31 | cout << s.maxSubArrayLen(vec, 3); 32 | cout << endl; 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /maximumSubarray/maxSubArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int maxSubArray(vector& nums) { 8 | vector dp = nums; 9 | int res = nums[0]; 10 | for (int i = 1; i < dp.size(); i++) { 11 | dp[i] = max (dp[i - 1] + nums[i], nums[i]); 12 | res = max(res, dp[i]); 13 | } 14 | return res; 15 | } 16 | }; 17 | 18 | int main() 19 | { 20 | Solution s; 21 | int a[9] = {-2,1,-3,4,-1,2,1,-5,4}; 22 | vector vec(a, a+9); 23 | cout << s.maxSubArray(vec) << endl; 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /maximumSubarray/maxSubArray.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class MaxSubArray { 4 | public int maxSubArray(int[] nums) { 5 | if (nums.length == 0) 6 | return 0; 7 | int local = nums[0]; 8 | int global = nums[0]; 9 | for (int i = 1; i < nums.length; i++) { 10 | local = Math.max(local + nums[i], nums[i]); 11 | global = Math.max (local, global); 12 | } 13 | return global; 14 | } 15 | public static void main(String[] args) { 16 | MaxSubArray s = new MaxSubArray(); 17 | int[] nums = {-2,1,-3,4,-1,2,1,-5,4}; 18 | System.out.println(s.maxSubArray(nums)); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /maximumSubarray/maxSubArray_2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int maxSubArray(vector& nums) { 8 | int n = nums.size(); 9 | if (n == 0) 10 | return -1; 11 | int64_t global = nums[0], local = nums[0]; 12 | for (int i = 1; i < n; i++) { 13 | local = max (local + nums[i], (int64_t)nums[i]); 14 | global = max (global, local); 15 | } 16 | return global; 17 | } 18 | }; 19 | 20 | int main() 21 | { 22 | Solution s; 23 | int a[9] = {-2,1,-3,4,-1,2,1,-5,4}; 24 | vector vec(a, a+9); 25 | cout << s.maxSubArray(vec) << endl; 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /maximumSubarray/maxSubArray_2.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxSubArray(int[] nums) { 3 | int[] dp = new int[nums.length]; 4 | dp[0] = nums[0]; 5 | int res = nums[0]; 6 | for (int i = 1; i < nums.length; i++) { 7 | if (dp[i - 1] > 0) { 8 | dp[i] = dp[i - 1] + nums[i]; 9 | } else { 10 | dp[i] = nums[i]; 11 | } 12 | res = Math.max(res, dp[i]); 13 | } 14 | return res; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /maximumSubarray/maxSubArray_3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int maxSubArray(vector& nums) { 8 | int n = nums.size(); 9 | vector preSum(n + 1, 0); 10 | int64_t minV = 0, res = INT64_MIN; 11 | for (int i = 1; i <= n; i++) { 12 | preSum[i] = preSum[i - 1] + nums[i - 1]; 13 | res = max (res, preSum[i] - minV); 14 | minV = min (minV, preSum[i]); 15 | } 16 | return res; 17 | } 18 | }; 19 | 20 | int main() 21 | { 22 | Solution s; 23 | int a[9] = {-2,1,-3,4,-1,2,1,-5,4}; 24 | vector vec(a, a+9); 25 | cout << s.maxSubArray(vec) << endl; 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /maximumSubarray/maxSubArray_4.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int maxSubArray(vector& nums) { 8 | int preSum = 0; 9 | int res = INT_MIN; 10 | int prevMin = 0; 11 | for (int i = 0; i < nums.size(); i++) { 12 | preSum += nums[i]; 13 | res = max (res, preSum - prevMin); 14 | prevMin = min (prevMin, preSum); 15 | } 16 | return res; 17 | } 18 | }; 19 | 20 | int main() 21 | { 22 | Solution s; 23 | int a[9] = {-2,1,-3,4,-1,2,1,-5,4}; 24 | vector vec(a, a+9); 25 | cout << s.maxSubArray(vec) << endl; 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /maximumSwap/maximumSwap2.cpp: -------------------------------------------------------------------------------- 1 | // clang++ maximumSwap2.cpp -std=c++11 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | 8 | class Solution{ 9 | public: 10 | int maximumSwap(int num) { 11 | string str = to_string(num); 12 | vector hash(10, 0); 13 | for (int i = 0; i < str.length(); i++) { 14 | hash[str[i] - '0'] = i; 15 | } 16 | for (int i = 0; i < str.length(); i++) { 17 | for (int j = 9; j > str[i] - '0'; j--) { 18 | if (hash[j] > i) { 19 | swap (str[hash[j]], str[i]); 20 | return stoi(str); 21 | } 22 | } 23 | } 24 | return stoi(str); 25 | } 26 | }; 27 | 28 | int main() 29 | { 30 | Solution s; 31 | cout << s.maximumSwap(98368) << endl; 32 | cout << s.maximumSwap(9973) << endl; 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /maximumTotalRewardUsingOperationsI/maximumTotalRewardUsingOperationsI.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxTotalReward(int[] rewardValues) { 3 | Arrays.sort(rewardValues); 4 | int res = 0; 5 | boolean[] dp = new boolean[2000 * 2000 + 1]; 6 | dp[rewardValues[0]] = true; 7 | res = rewardValues[0]; 8 | for (int k = 1; k < rewardValues.length; k++) { 9 | for (int i = 0; i < rewardValues[k]; i++) { 10 | dp[rewardValues[k]] = true; 11 | res = Math.max(res, rewardValues[k]); 12 | if (dp[i]) { 13 | dp[rewardValues[k] + i] = true; 14 | res = Math.max(res, rewardValues[k] + i); 15 | } 16 | } 17 | } 18 | return res; 19 | } 20 | } -------------------------------------------------------------------------------- /maximumXORofTwoNumbersInAnArray/maximumXORofTwoNumbersInAnArray.cpp: -------------------------------------------------------------------------------- 1 | //clang++ maximumXORofTwoNumbersInAnArray.cpp -std=c++11 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | class Solution { 7 | public: 8 | int findMaximumXOR(vector& nums) { 9 | int res = 0, mask = 0; 10 | for (int i = 31; i >= 0; i--) { 11 | mask |= (1 << i); 12 | unordered_set s; 13 | for (int num : nums) 14 | s.insert(num & mask); 15 | int t = res | (1 << i); 16 | for (int prefix : s) { 17 | if (s.count(t ^ prefix)) { 18 | res = t; 19 | break; 20 | } 21 | } 22 | }//for 23 | return res; 24 | } 25 | }; 26 | int main(void) 27 | { 28 | Solution s; 29 | vector nums = {3,10,5,25,2,8}; 30 | cout << s.findMaximumXOR(nums) << endl; 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /meetingScheduler/meetingScheduler.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector minAvailableDuration(vector>& slots1, vector>& slots2, int duration) { 4 | sort(slots1.begin(), slots1.end()); 5 | sort(slots2.begin(), slots2.end()); 6 | int p1 = 0, p2 = 0; 7 | while (p1 < slots1.size() && p2 < slots2.size()) { 8 | int left = max (slots1[p1][0], slots2[p2][0]); 9 | int right = min (slots1[p1][1], slots2[p2][1]); 10 | if (right - left >= duration) { 11 | return {left, left + duration}; 12 | } else if (slots1[p1][1] < slots2[p2][1]) { 13 | p1++; 14 | } else { 15 | p2++; 16 | } 17 | } 18 | return {}; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /minMoveToEqualArrayElements/minMoveToEqualArrayElements.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution{ 7 | public: 8 | int minMoves(vector& nums) { 9 | int sum = 0, minE = INT_MAX; 10 | for (int i = 0; i < nums.size(); i++) { 11 | sum += nums[i]; 12 | minE = min(minE, nums[i]); 13 | } 14 | return sum - nums.size() * minE; 15 | } 16 | }; 17 | 18 | int main() 19 | { 20 | Solution s; 21 | int a[3] = {1,2,3}; 22 | vector vec(a, a+3); 23 | cout << s.minMoves(vec) << endl; 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /minimumMovesToEqualArrayElementsII/minimumMovesToEqualArrayElementsII.cpp: -------------------------------------------------------------------------------- 1 | // clang++ minimumMovesToEqualArrayElementsII.cpp -std=c++11 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | 10 | class Solution{ 11 | public: 12 | int minMoves2(vector& nums) { 13 | sort(nums.begin(), nums.end()); 14 | int i = 0, j = nums.size() - 1; 15 | int ans = 0; 16 | while (i < j) { 17 | ans += nums[j] - nums[i]; 18 | i++; 19 | j--; 20 | } 21 | return ans; 22 | } 23 | }; 24 | 25 | int main() 26 | { 27 | Solution s; 28 | vector nums = {1,2,99}; 29 | cout << s.minMoves2(nums); 30 | cout << endl; 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /mirrorRelection/mirrorReflection.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int mirrorReflection(int p, int q) { 7 | if (q == 0) 8 | return 0; 9 | int lcm = p * q / gcd(p, q); 10 | int v = lcm / p; // vertical bar number = vertical total len / p 11 | if (v % 2 == 0) // even 12 | return 0; 13 | int len_x = p * lcm / q; 14 | int h = len_x / p; 15 | if (h % 2) 16 | return 1; 17 | else 18 | return 2; 19 | } 20 | int gcd (int p, int q) { 21 | if (q == 0) 22 | return p; 23 | return gcd(q, p % q); 24 | } 25 | }; 26 | 27 | int main() { 28 | Solution s; 29 | cout << s.mirrorReflection(2, 1) << endl; 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /missingElementInSortedArray/missingElementInSortedArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int missingElement(vector& nums, int k) { 4 | int i = 0; 5 | while (i < nums.size()) { 6 | if (i + 1 < nums.size() && nums[i + 1] == nums[i]) { 7 | i++; 8 | continue; 9 | } else { 10 | if (i + 1 == nums.size()) { 11 | return nums.back() + k; 12 | } else { 13 | int delta = nums[i + 1] - nums[i] - 1; 14 | if (delta < k) 15 | k -= delta; 16 | else 17 | return nums[i] + k; 18 | } 19 | i++; 20 | } 21 | } 22 | return -1; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /missingNum/missingNum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution{ 7 | public: 8 | int missingNumber(vector& nums) { 9 | int size = nums.size(); 10 | int sum = size * (size + 1) / 2; 11 | for (const int& num : nums) 12 | sum -= num; 13 | return sum; 14 | } 15 | }; 16 | 17 | int main() 18 | { 19 | Solution s; 20 | int a[8] = {1,2,3,4,5,6,7,8}; 21 | vector vec(a, a+3); 22 | cout << s.missingNumber(vec) << endl; 23 | 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /missingNum/missingNum2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution{ 7 | public: 8 | int missingNumber(vector& nums) { 9 | int res = nums.size(); 10 | if (nums.size() == 0) 11 | return 0; 12 | for (int i = 0; i < nums.size(); i++) { 13 | res = res ^ i; 14 | res = res ^ nums[i]; 15 | } 16 | return res; 17 | } 18 | }; 19 | 20 | int main() 21 | { 22 | Solution s; 23 | int a[8] = {1,2,3,4,5,6,7,8}; 24 | vector vec(a, a+3); 25 | cout << s.missingNumber(vec) << endl; 26 | 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /monotoneIncreasingDigits/monotoneIncreasingDigits.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution{ 5 | public: 6 | int monotoneIncreasingDigits(int N) { 7 | string number = to_string(N); 8 | int k = number.size(); 9 | for (int i = number.size() - 1; i > 0; i--) { 10 | if (number[i] < number[i - 1]) { 11 | k = i; 12 | number[i - 1] = number[i - 1] - 1; 13 | } 14 | } 15 | for (int i = k; i < number.size(); i++) 16 | number[i] = '9'; 17 | return stoi(number); 18 | } 19 | }; 20 | 21 | int main() 22 | { 23 | Solution s; 24 | int N = 1444367; 25 | int N2 = 0000; 26 | cout << s.monotoneIncreasingDigits(N) << endl; 27 | cout << s.monotoneIncreasingDigits(N2) << endl; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /moveZeroes/moveZeros.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | void moveZeros(vector& nums) { 8 | int numOfZero = 0; 9 | int size = nums.size(); 10 | for (int i = 0; i < size; i++) { 11 | if (0 == nums[i]) { 12 | numOfZero++; 13 | } 14 | else 15 | swap(nums[i], nums[i-numOfZero]); 16 | } 17 | } 18 | }; 19 | 20 | int main() 21 | { 22 | Solution s; 23 | int a[5] = {0,1,0,3,12}; 24 | vector vec(a, a+5); 25 | s.moveZeros(vec); 26 | vector::iterator it = vec.begin(); 27 | while (it != vec.end()) { 28 | cout << *it << " "; 29 | ++it; 30 | } 31 | cout << endl; 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /moveZeroes/moveZeros.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void moveZeroes(int[] nums) { 3 | int last = 0; 4 | for (int i = 0; i < nums.length; i++) { 5 | if (nums[i] != 0) { 6 | int temp = nums[last]; 7 | nums[last++] = nums[i]; 8 | nums[i] = temp; 9 | } 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /moveZeroes/moveZeros2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | void moveZeroes(vector& nums) { 8 | if (nums.size() == 0) 9 | return; 10 | int left = 0, right = 0; 11 | while (right < nums.size()) { 12 | if (nums[right] != 0) 13 | swap(nums[left++], nums[right++]); 14 | else 15 | right++; 16 | } 17 | } 18 | }; 19 | 20 | int main() 21 | { 22 | Solution s; 23 | int a[5] = {0,1,0,3,12}; 24 | vector vec(a, a+5); 25 | s.moveZeroes(vec); 26 | vector::iterator it = vec.begin(); 27 | while (it != vec.end()) { 28 | cout << *it << " "; 29 | ++it; 30 | } 31 | cout << endl; 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /moveZeroes/moveZeros3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | void moveZeroes(vector& nums) { 8 | int left = 0; 9 | for (int i = 0; i < nums.size(); i++) { 10 | if (nums[i] != 0) { 11 | swap (nums[left++], nums[i]); 12 | } 13 | } 14 | } 15 | }; 16 | 17 | int main() 18 | { 19 | Solution s; 20 | int a[5] = {0,1,0,3,12}; 21 | vector vec(a, a+5); 22 | s.moveZeroes(vec); 23 | vector::iterator it = vec.begin(); 24 | while (it != vec.end()) { 25 | cout << *it << " "; 26 | ++it; 27 | } 28 | cout << endl; 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /movingAverageFromDataStream/movingAverageFromDataStream.cpp: -------------------------------------------------------------------------------- 1 | class MovingAverage { 2 | public: 3 | /** Initialize your data structure here. */ 4 | MovingAverage(int size) { 5 | len = size; 6 | sum = 0; 7 | } 8 | 9 | double next(int val) { 10 | q.push(val); 11 | sum += val; 12 | if (q.size() > len) { 13 | sum -= q.front(); 14 | q.pop(); 15 | } 16 | return sum * 1.0 / q.size(); 17 | } 18 | queue q; 19 | int sum; 20 | int len; 21 | }; 22 | 23 | /** 24 | * Your MovingAverage object will be instantiated and called as such: 25 | * MovingAverage obj = new MovingAverage(size); 26 | * double param_1 = obj.next(val); 27 | */ 28 | -------------------------------------------------------------------------------- /myCalendarI/myCalendarI.java: -------------------------------------------------------------------------------- 1 | class MyCalendar { 2 | 3 | public MyCalendar() { 4 | books = new TreeMap<>(); 5 | } 6 | 7 | TreeMap books; 8 | 9 | public boolean book(int start, int end) { 10 | java.util.Map.Entry floor = books.floorEntry(start), ceiling = books.ceilingEntry(start); 11 | if (floor != null && start < floor.getValue()) return false; // (s, e) start within floor 12 | if (ceiling != null && ceiling.getKey() < end) return false; // ceiling start within (s, e) 13 | books.put(start, end); 14 | return true; 15 | } 16 | } 17 | 18 | /** 19 | * Your MyCalendar object will be instantiated and called as such: 20 | * MyCalendar obj = new MyCalendar(); 21 | * boolean param_1 = obj.book(start,end); 22 | */ 23 | -------------------------------------------------------------------------------- /myCalendarI/myCalendarI_1.cpp: -------------------------------------------------------------------------------- 1 | class MyCalendar { 2 | public: 3 | MyCalendar() { 4 | 5 | } 6 | 7 | bool book(int start, int end) { 8 | for (auto& e : events) { 9 | bool flag1 = end <= e.first; 10 | bool flag2 = start >= e.second; 11 | if (!flag1 && !flag2) 12 | return false; 13 | } 14 | events.push_back(make_pair(start, end)); 15 | return true; 16 | } 17 | vector > events; 18 | }; 19 | 20 | /** 21 | * Your MyCalendar object will be instantiated and called as such: 22 | * MyCalendar obj = new MyCalendar(); 23 | * bool param_1 = obj.book(start,end); 24 | */ 25 | -------------------------------------------------------------------------------- /myCalendarI/myCalendarI_2.cpp: -------------------------------------------------------------------------------- 1 | class MyCalendar { 2 | public: 3 | MyCalendar() { 4 | 5 | } 6 | 7 | bool book(int start, int end) { 8 | auto next = events.lower_bound({start, end}); 9 | if (next != events.end() && end > next->first) 10 | return false; 11 | if (next != events.begin() && start < (--next)->second) 12 | return false; 13 | events.insert(make_pair(start, end)); 14 | return true; 15 | } 16 | set > events; 17 | }; 18 | 19 | /** 20 | * Your MyCalendar object will be instantiated and called as such: 21 | * MyCalendar obj = new MyCalendar(); 22 | * bool param_1 = obj.book(start,end); 23 | */ 24 | -------------------------------------------------------------------------------- /myCalendarIII/myCalendarIII.cpp: -------------------------------------------------------------------------------- 1 | class MyCalendarThree { 2 | public: 3 | MyCalendarThree() { 4 | 5 | } 6 | 7 | int book(int start, int end) { 8 | timeline[start]++; 9 | timeline[end]--; 10 | int ongoing = 0, res = 0; 11 | for (auto& p : timeline) { 12 | res = max (res, ongoing += p.second); 13 | } 14 | return res; 15 | } 16 | map timeline; 17 | }; 18 | 19 | /** 20 | * Your MyCalendarThree object will be instantiated and called as such: 21 | * MyCalendarThree obj = new MyCalendarThree(); 22 | * int param_1 = obj.book(start,end); 23 | */ 24 | -------------------------------------------------------------------------------- /nestListWeightSum/nestListWeightSum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int depthSum(vector& nestedList) { 4 | int res = 0; 5 | return dfs(nestedList, 1); 6 | } 7 | int dfs(vector& nestedList, int depth) { 8 | int res = 0; 9 | for (NestedInteger ni : nestedList) { 10 | if (ni.isInteger()) res += depth * ni.getInteger(); 11 | else res += dfs(ni.getList(), depth + 1); 12 | } 13 | return res; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /nestListWeightSumII/nestListWeightSumII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int depthSumInverse(vector& nestedList) { 4 | vector level; 5 | level.push_back(0); 6 | int res = 0; 7 | dfs(nestedList, level, 1); 8 | for (int i = 1; i < level.size(); i++) { 9 | res += level[i] * (level.size() - i); 10 | } 11 | return res; 12 | } 13 | void dfs(vector& nestedList, vector& level, int depth) { 14 | for (NestedInteger& ni : nestedList) { 15 | if (depth == level.size()) level.push_back(0); 16 | if (ni.isInteger()) level[depth] += ni.getInteger(); 17 | else dfs(ni.getList(), level, depth + 1); 18 | } 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /nextGreaterElementIII/nextGreaterElementIII.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | int nextGreaterElements(int n) { 8 | string s = to_string(n); 9 | int size = s.length(); 10 | int i = size - 1; 11 | while (i >= 1 && s[i-1] >= s[i]) { 12 | i--; 13 | } 14 | if (i == 0) 15 | return -1; 16 | int p1 = i - 1; 17 | while (i < size) { 18 | if (s[++i] <= s[p1]) { 19 | swap(s[i-1], s[p1]); 20 | reverse(s.begin() + p1 + 1, s.end()); 21 | break; 22 | } 23 | } 24 | long ans = stol(s); 25 | return ans > INT_MAX ? -1 : ans; 26 | } 27 | }; 28 | 29 | int main() 30 | { 31 | Solution s; 32 | cout << s.nextGreaterElements(1999999999); 33 | cout << endl; 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /nimGame/nimGame.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | bool canWinNim(int n) { 8 | /* vector m(n+1, false); 9 | m[1] = true; 10 | m[2] = true; 11 | m[3] = true; 12 | for (int i = 3; i <= n; i++) 13 | m[i] = !m[i-1] || !m[i-2] || !m[i-3]; 14 | return m[n];*/ 15 | return n % 4 != 0; 16 | } 17 | }; 18 | 19 | int main() 20 | { 21 | Solution s; 22 | cout << s.canWinNim(100); 23 | cout << endl; 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /notBoringMovies/notBoringMovies: -------------------------------------------------------------------------------- 1 | Select * from cinema 2 | where id % 2 <> 0 and description <> "boring" 3 | order by rating desc -------------------------------------------------------------------------------- /nthDigit/nthDigit.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution{ 5 | public: 6 | int findNthDigit(int n) { 7 | long long base = 9, bits = 1, start = 1; 8 | while (n > base * bits) { 9 | n -= base * bits; 10 | bits++; 11 | base *= 10; 12 | start *= 10; 13 | } 14 | string s = to_string(start + (n-1)/bits); 15 | return s[(n-1)%bits] - '0'; 16 | } 17 | }; 18 | 19 | int main() 20 | { 21 | Solution s; 22 | cout << s.findNthDigit(150)<< endl; 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /nthHigestSalary/nthHighestSalary: -------------------------------------------------------------------------------- 1 | CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT 2 | BEGIN 3 | DECLARE M INT; 4 | SET M=N-1; 5 | RETURN ( 6 | # Write your MySQL query statement below. 7 | select distinct Salary from Employee order by Salary desc limit M, 1 8 | ); 9 | END -------------------------------------------------------------------------------- /numberComplement/numberComplement.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution{ 5 | public: 6 | int findComplement(int num) { 7 | unsigned mask = ~0; 8 | while (num & mask) 9 | mask <<= 1; 10 | return ~mask & ~num; 11 | } 12 | }; 13 | 14 | int main() 15 | { 16 | Solution s; 17 | cout << s.findComplement(5); 18 | cout << endl; 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /numberOf1Bits/numberOf1Bits.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | int hammingWeight(uint32_t n) { 8 | int res = 0; 9 | while (n) { 10 | if ((n & 1) == 1) 11 | res++; 12 | n = n >> 1; 13 | } 14 | return res; 15 | } 16 | }; 17 | 18 | int main() 19 | { 20 | Solution s; 21 | cout << s.hammingWeight(11); 22 | cout << endl; 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /numberOfGoodPairs/numberOfGoodPairs.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numIdenticalPairs(int[] nums) { 3 | int res = 0; 4 | Map m = new HashMap(); 5 | for (int n : nums) { 6 | m.put(n, m.getOrDefault(n, 0) + 1); 7 | } 8 | for (Integer i : m.values()) { 9 | if (i > 1) res += i * (i - 1) / 2; 10 | } 11 | return res; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /numberOfSegmentInAString/numberOfSegmentsInAString.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution{ 5 | public: 6 | int countSegments(string s) { 7 | int ans = 0; 8 | int i = 0; 9 | int size = s.length(); 10 | if (size < 1) 11 | return 0; 12 | while (i < size && s[i] == ' ') 13 | i++; 14 | if (i < size && s[i] != ' ') 15 | ans += 1; 16 | for(i; i < s.length(); i++) { 17 | if (s[i] == ' ') { 18 | while (i < size && s[i] == ' ') 19 | i++; 20 | if (i < size && s[i] != ' ') 21 | ans += 1; 22 | } 23 | } 24 | return ans; 25 | } 26 | }; 27 | 28 | int main() 29 | { 30 | Solution s; 31 | string str = " "; 32 | cout << s.countSegments(str) << endl; 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /optimalDivision/optimalDivision.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | string optimalDivision(vector& nums) { 8 | string ans; 9 | int size = nums.size(); 10 | if (size == 0) 11 | return ans; 12 | ans = to_string(nums[0]); 13 | if (size == 1) 14 | return ans; 15 | if (size == 2) 16 | return ans + "/" + to_string(nums[1]); 17 | ans += "/(" + to_string(nums[1]); 18 | for (int i = 2; i < nums.size(); i++) 19 | ans += "/" + to_string(nums[i]); 20 | ans += ")"; 21 | return ans; 22 | } 23 | }; 24 | 25 | int main() 26 | { 27 | Solution s; 28 | int a[4] = {1000, 100, 10, 2}; 29 | vector vec(a, a+4); 30 | cout << s.optimalDivision(vec); 31 | cout << endl; 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /outputContestMatches/outputContestMatches.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | string findContestMatch(int n) { 8 | vector vec(n, ""); 9 | for (int i = 1; i <= n; i++) { 10 | vec[i - 1] = to_string(i); 11 | } 12 | while (n > 1) { 13 | for (int i = 0; i < n; i++) { 14 | vec[i] = "(" + vec[i] + "," + vec[n - i - 1] + ")"; 15 | } 16 | n /= 2; 17 | } 18 | return vec[0]; 19 | } 20 | }; 21 | 22 | int main() { 23 | Solution s; 24 | cout << s.findContestMatch(8) << endl; 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /paintFence/paintFence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int numWays(int n, int k) { 7 | if (n == 0 || k == 0) 8 | return 0; 9 | if (n == 1) 10 | return k; 11 | if (n == 2) 12 | return k * k; 13 | int dp = 0; 14 | int dp1 = k * k; 15 | int dp2 = k; 16 | for (int i = 2; i < n; i++) { 17 | dp = (dp1 + dp2) * (k - 1); 18 | dp2 = dp1; 19 | dp1 = dp; 20 | } 21 | return dp; 22 | } 23 | }; 24 | 25 | int main() { 26 | Solution s; 27 | cout << s.numWays(4, 6) << endl; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /palindromeNumber/palindromeNumber.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | bool isPalindrome(int x) { 7 | if (x < 0) return false; 8 | int64_t res = 0; 9 | int64_t num = x; 10 | while (num) { 11 | res = res * 10 + num % 10; 12 | num = num / 10; 13 | } 14 | return x == res; 15 | } 16 | }; 17 | 18 | int main() 19 | { 20 | Solution s; 21 | cout << s.isPalindrome(10) << endl; 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /palindromePermutation/palindromePermutation.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class PalindromePermutation { 4 | public boolean canPermutePalindrome(String s) { 5 | Set charSet = new HashSet(); 6 | for (char c : s.toCharArray()) { 7 | if (!charSet.contains(c)) 8 | charSet.add(c); 9 | else 10 | charSet.remove(c); 11 | } 12 | return charSet.size() <= 1; 13 | } 14 | public static void main(String[] args) { 15 | PalindromePermutation s = new PalindromePermutation(); 16 | String str = "code"; 17 | System.out.println(s.canPermutePalindrome(str)); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /partitionEqualSubsetSum/partitionEqualSubsetSum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canPartition(int[] nums) { 3 | int sum = 0; 4 | for (int num : nums) sum += num; 5 | if (sum % 2 != 0) return false; 6 | int target = sum / 2; 7 | boolean dp[][] = new boolean[nums.length + 1][target + 1]; 8 | dp[0][0] = true; 9 | for (int i = 1; i <= nums.length; i++) { 10 | for (int j = 0; j <= target; j++) { 11 | if (dp[i - 1][j]) { 12 | dp[i][j] = true; 13 | } else if (j - nums[i - 1] >= 0) { 14 | dp[i][j] = dp[i - 1][j - nums[i - 1]]; 15 | } 16 | } 17 | } 18 | return dp[nums.length][target]; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /pascalTriangleII/pascalTriangleII.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | vector getRow(int rowIndex) { 8 | vector ans(rowIndex+1, 1); 9 | for (int i = 2; i <= rowIndex; i++) { 10 | for (int j = i-1; j >= 1; j--) { 11 | ans[j] = ans[j-1] + ans[j]; 12 | } 13 | } 14 | return ans; 15 | } 16 | }; 17 | 18 | int main() 19 | { 20 | Solution s; 21 | vector vec = s.getRow(4); 22 | vector::iterator it = vec.begin(); 23 | while (it != vec.end()) { 24 | cout << *it << " "; 25 | ++it; 26 | } 27 | cout << endl; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /patchingArray/patchingArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int minPatches(vector& nums, int n) { 8 | long miss = 1, res = 0, i = 0; 9 | while (miss <= n) { 10 | if (i < nums.size() && nums[i] <= miss) { 11 | miss += nums[i++]; 12 | } else { 13 | miss += miss; 14 | res++; 15 | } 16 | } 17 | return res; 18 | } 19 | }; 20 | 21 | int main() { 22 | Solution s; 23 | vector nums = {1,5,10}; 24 | int n = 20; 25 | cout << s.minPatches(nums, n); 26 | cout << endl; 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /peakIndexInAmountainArray/peakIndexInAmountainArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int peakIndexInMountainArray(vector& A) { 8 | int left = 0, right = A.size() - 1; 9 | while (left + 1 < right) { 10 | int mid = left + (right - left) / 2; 11 | if (A[mid] < A[mid + 1]) 12 | left = mid; 13 | else 14 | right = mid; 15 | } 16 | return right; 17 | } 18 | }; 19 | 20 | int main() { 21 | Solution s; 22 | vector A = {0,2,1,0}; 23 | cout << s.peakIndexInMountainArray(A) << endl; 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /peakIndexInAmountainArray/peakIndexInAmountainArray_2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int peakIndexInMountainArray(vector& A) { 8 | for (int i = 1; i < A.size() - 1; i++) { 9 | if (A[i] > A[i - 1] && A[i] > A[i + 1]) 10 | return i; 11 | } 12 | return -1; 13 | } 14 | }; 15 | 16 | int main() { 17 | Solution s; 18 | vector A = {0,2,1,0}; 19 | cout << s.peakIndexInMountainArray(A) << endl; 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /perfectNumber/perfectNumber.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution{ 5 | public: 6 | bool checkPerfectNumber(int num) { 7 | int ans = 0; 8 | if (num == 1) 9 | return false; 10 | for(int i = 2; i*i <= num; i++) { 11 | if (num % i == 0) 12 | ans += i + num / i; 13 | } 14 | ans++; // consider the divisor 1 15 | return ans == num; 16 | } 17 | }; 18 | 19 | int main() 20 | { 21 | Solution s; 22 | cout << s.checkPerfectNumber(28) << endl; 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /perfectSquares/perfectSquares.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int numSquares(int n) { 8 | vector dp(n + 1, INT_MAX); 9 | dp[0] = 0; 10 | dp[1] = 1; 11 | for (int i = 1; i <= n; i++) { 12 | for (int j = 1; j * j <= i; j++) { 13 | dp[i] = min (dp[i], dp[i - j * j] + 1); 14 | } 15 | } 16 | return dp[n]; 17 | } 18 | }; 19 | 20 | int main() 21 | { 22 | Solution s; 23 | cout << s.numSquares(12) << endl; 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /perfectSquares/perfectSquares.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numSquares(int n) { 3 | int[] dp = new int[n + 1]; 4 | Arrays.fill(dp, Integer.MAX_VALUE); 5 | dp[0] = 0; 6 | dp[1] = 1; 7 | for (int i = 1; i <= n; i++) { 8 | for (int j = 1; j * j <= i; j++) { 9 | dp[i] = Math.min(dp[i], dp[i - j * j] + 1); 10 | } 11 | } 12 | return dp[n]; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /permutationSequence/permutationSequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution{ 7 | public: 8 | string getPermutation(int n, int k) { 9 | string ans; 10 | string numbers; 11 | vector factorial(n+1, 1); 12 | int cumprod = 1; 13 | for (int i = 1; i <= n; i++) { 14 | cumprod *= i; 15 | factorial[i] = cumprod; 16 | numbers.push_back(i + '0'); 17 | } 18 | k--; 19 | for (int i = 1; i <= n; i++) { 20 | int index = k/factorial[n-i]; 21 | ans += numbers[index]; 22 | numbers.erase(numbers.begin() + index); 23 | k -= index * factorial[n-i]; 24 | } 25 | return ans; 26 | } 27 | }; 28 | 29 | int main() 30 | { 31 | Solution s; 32 | cout << s.getPermutation(3, 3); 33 | cout << endl; 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /poorPigs/poorPigs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | int poorPigs(int buckets, int minutesToDie, int minutesToTest) { 8 | int pigs = 0; 9 | while (pow(minutesToTest/minutesToDie + 1, pigs) < buckets) 10 | pigs++; 11 | return pigs; 12 | } 13 | }; 14 | 15 | int main() 16 | { 17 | Solution s; 18 | cout << s.poorPigs(1000, 15, 60); 19 | cout << endl; 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /powXN/powXN.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution{ 5 | public: 6 | double myPow(double x, int n) { 7 | long long N = n; 8 | if (N == 0) 9 | return 1; 10 | if (N < 0) { 11 | N = -N; 12 | x = 1/x; 13 | } 14 | return (N % 2 == 0) ? myPow(x * x, N / 2) : x * myPow (x * x, N / 2); 15 | } 16 | }; 17 | 18 | int main() 19 | { 20 | Solution s; 21 | cout << s.myPow(2, 5) << endl; 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /powXN/powXN.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public double myPow(double x, int n) { 3 | long N = n; 4 | if (N == 0) return 1; 5 | if (N < 0) { 6 | N = -N; 7 | x = 1 / x; 8 | } 9 | double sub = myPow(x, (int)(N / 2)); 10 | if (N % 2 == 0) { 11 | return sub * sub; 12 | } else { 13 | return sub * sub * x; 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /powXN/powXN_2.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public double myPow(double x, int n) { 3 | if (n == 0) return 1; 4 | long N = n; 5 | if (N < 0) { 6 | N = -N; 7 | x = 1 / x; 8 | } 9 | double sub = myPow(x, (int) (N / 2)); 10 | if (N % 2 == 0) { 11 | return sub * sub; 12 | } else { 13 | return sub * sub * x; 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /powerOfFour/powerOfFour.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution{ 5 | public: 6 | bool isPowerOfFour(int num) { 7 | return num > 0 && (num&(num-1)) == 0 && (num & 0x55555555) != 0; 8 | } 9 | }; 10 | 11 | int main() 12 | { 13 | Solution s; 14 | cout << s.isPowerOfFour(12); 15 | cout << endl; 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /powerOfThree/powerOfThree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution{ 5 | public: 6 | bool isPowerOfThree(int n) { 7 | /* if (n == 1) 8 | return true; 9 | if (n == 0 || n%3 != 0) 10 | return false; 11 | else 12 | return isPowerOfThree(n/3);*/ 13 | 14 | // 1162261467 is 3^19, 3^20 is bigger than int 15 | return ( n>0 && 1162261467%n == 0); 16 | } 17 | }; 18 | 19 | int main() 20 | { 21 | Solution s; 22 | cout << s.isPowerOfThree(3)<< endl; 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /powerOfTwo/powerOfTwo.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution{ 5 | public: 6 | bool isPowerOfTwo(int n) { 7 | return n > 0 && (n & (n - 1)) == 0; 8 | } 9 | }; 10 | 11 | int main() 12 | { 13 | Solution s; 14 | cout << s.isPowerOfTwo(8)<< endl; 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /predictTheWinner/predictTheWinner.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean PredictTheWinner(int[] nums) { 3 | int[][] dp = new int[nums.length][nums.length]; 4 | for (int[] row : dp) Arrays.fill(row, -1); 5 | long sum = 0; 6 | for (int num : nums) sum += num; 7 | return dfs(dp, nums, 0, nums.length - 1) * 2 >= sum; 8 | } 9 | 10 | public int dfs(int[][] dp, int[] nums, int i, int j) { 11 | if (i > j) return 0; 12 | else if (i == j) return nums[i]; 13 | if (dp[i][j] != -1) return dp[i][j]; 14 | int start = nums[i] + Math.min(dfs(dp, nums, i + 2, j), dfs(dp, nums, i + 1, j - 1)); 15 | int end = nums[j] + Math.min(dfs(dp, nums, i + 1, j - 1), dfs(dp, nums, i, j - 2)); 16 | return dp[i][j] = Math.max(start, end); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /productOfArrayExceptSelf/productOfArrayExceptSelf.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] productExceptSelf(int[] nums) { 3 | if (nums == null || nums.length < 2) 4 | return nums; 5 | int[] res = new int[nums.length]; 6 | res[0] = 1; 7 | for (int i = 1; i < nums.length; i++) { 8 | res[i] = res[i - 1] * nums[i - 1]; 9 | } 10 | int right = 1; 11 | for (int i = nums.length - 2; i >= 0; i--) { 12 | right = right * nums[i + 1]; 13 | res[i] *= right; 14 | } 15 | return res; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /queueReconstructionByHeight/queueReconstructionByHeight.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[][] reconstructQueue(int[][] people) { 3 | Arrays.sort(people, (a, b) -> a[0] != b[0] ? a[0] - b[0] : b[1] - a[1]); 4 | for (int i = people.length - 2; i >= 0; i--) { 5 | int h = people[i][0]; 6 | int k = people[i][1]; 7 | int j = i; 8 | while (j != i + k) { 9 | people[j][0] = people[j + 1][0]; 10 | people[j][1] = people[j + 1][1]; 11 | j++; 12 | } 13 | people[i + k][0] = h; 14 | people[i + k][1] = k; 15 | } 16 | return people; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /randomPickIndex/randomPickIndex.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | Solution(vector nums) { 4 | nums_ = nums; 5 | srand(time(0)); 6 | } 7 | 8 | int pick(int target) { 9 | int res = -1, count = 0; 10 | for (int i = 0; i < nums_.size(); i++) { 11 | if (nums_[i] == target) { 12 | count++; 13 | if (rand() % count == 0) 14 | res = i; 15 | } 16 | } 17 | return res; 18 | } 19 | vector nums_; 20 | }; 21 | 22 | /** 23 | * Your Solution object will be instantiated and called as such: 24 | * Solution obj = new Solution(nums); 25 | * int param_1 = obj.pick(target); 26 | */ 27 | -------------------------------------------------------------------------------- /rangeAddition/rangeAddition.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | vector getModifiedArray(int length, vector>& updates) { 8 | vector res(length, 0); 9 | for (auto& update : updates) { 10 | res[update[0]] += update[2]; 11 | if (update[1] + 1 < length) 12 | res[update[1] + 1] -= update[2]; 13 | } 14 | for (int i = 1; i < length; i++) 15 | res[i] += res[i - 1]; 16 | return res; 17 | } 18 | }; 19 | 20 | int main() { 21 | Solution s; 22 | vector > updates = { {1,3,2}, {2,4,3}, {0,2,-2}}; 23 | for (int i : s.getModifiedArray(5, updates)) 24 | cout << i << " "; 25 | cout << endl; 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /rangeAdditionII/rangeAdditionII.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution{ 7 | public: 8 | int maxCount(int m, int n, vector >& ops) { 9 | //vector > matrix(m, vector(n, 0)); 10 | int row = m, col = n; 11 | for (vector op : ops) { 12 | row = min(row, op[0]); 13 | col = min(col, op[1]); 14 | } 15 | return row*col; 16 | } 17 | }; 18 | 19 | int main() 20 | { 21 | Solution s; 22 | int a[2] = {2,2}; 23 | int b[2] = {3,3}; 24 | vector vec1(a, a+2); 25 | vector vec2(b, b+2); 26 | vector > ops; 27 | ops.push_back(vec1); 28 | ops.push_back(vec2); 29 | cout << s.maxCount(3, 3, ops) << endl; 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /rangeSumOfBST/rangeSumOfBST.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | int rangeSumBST(TreeNode* root, int L, int R) { 13 | if (!root) return 0; 14 | if (root->val < L) 15 | return rangeSumBST(root->right, L, R); 16 | else if (root->val > R) 17 | return rangeSumBST(root->left, L, R); 18 | else 19 | return root->val + rangeSumBST(root->left, L, R) + rangeSumBST(root->right, L, R); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /rangeSumQueryImmutable/rangeSumQueryImmutable.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class NumArray{ 6 | public: 7 | NumArray(vector nums) { 8 | int sum = 0; 9 | for (int i : nums) { 10 | sum += i; 11 | p.push_back(sum); 12 | } 13 | } 14 | 15 | int sumRange(int i, int j) { 16 | if (i > j) 17 | return 0; 18 | if (i < 0) 19 | i = 0; 20 | if (j > p.size() - 1) 21 | j = p.size() - 1; 22 | if (i == 0) 23 | return p[j]; 24 | else 25 | return p[j] - p[i-1]; 26 | } 27 | 28 | vector p; 29 | }; 30 | 31 | int main() 32 | { 33 | int a[6] = {-2, 0, 3, -5, 2, -1}; 34 | vector vec(a, a+6); 35 | NumArray na(vec); 36 | cout << na.sumRange(2, 5) << endl; 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /rankScores/rankScores: -------------------------------------------------------------------------------- 1 | select Score, (select count(*) from (select distinct Score s from Scores) tmp where s >= Score) Rank 2 | from Scores 3 | order by Score desc -------------------------------------------------------------------------------- /ransomNote/ransomNote.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | bool canConstruct(string ransomNote, string magazine) { 8 | unordered_map m; 9 | for(int i = 0; i < magazine.size(); i++) { 10 | m[magazine[i]]++; 11 | } 12 | for(int i = 0; i < ransomNote.size(); i++) { 13 | if (--m[ransomNote[i]] < 0) 14 | return false; 15 | } 16 | return true; 17 | } 18 | }; 19 | 20 | int main() 21 | { 22 | Solution s; 23 | string str1 = "aa"; 24 | string str2 = "ab"; 25 | cout << s.canConstruct(str1, str2) << endl; 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /rectangleArea/rectangleArea.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution{ 5 | public: 6 | double computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { 7 | int areaRect1 = (C-A) * (D-B); 8 | int areaRect2 = (G-E) * (H-F); 9 | int left = max(A, E); 10 | int right = min(G, C); 11 | int bottom = max(B, F); 12 | int top = min(D, H); 13 | int overlap = 0; 14 | if (right > left && top > bottom) 15 | overlap = (right - left) * (top - bottom); 16 | return areaRect1 + areaRect2 - overlap; 17 | } 18 | }; 19 | 20 | int main() 21 | { 22 | Solution s; 23 | cout << s.computeArea(-3,0,3,4,0,-1,9,2) << endl; 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /rectangleOverlap/rectangleOverlap.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | bool isRectangleOverlap(vector& rec1, vector& rec2) { 8 | return max (rec1[0], rec2[0]) < min (rec1[2], rec2[2]) && max (rec1[1], rec2[1]) < min (rec1[3], rec2[3]); 9 | } 10 | }; 11 | 12 | int main() { 13 | Solution s; 14 | vector rec1 = {0,0,2,2}, rec2 = {1,1,3,3}; 15 | cout << s.isRectangleOverlap(rec1, rec2) << endl; 16 | return 0; 17 | } 18 | 19 | -------------------------------------------------------------------------------- /relativeSortArray/relativeSortArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector relativeSortArray(vector& arr1, vector& arr2) { 4 | vector res; 5 | unordered_map m; 6 | for (int n : arr2) m[n] = 0; 7 | for (int n : arr1) { 8 | if (m.count(n)) 9 | m[n]++; 10 | } 11 | for (int n : arr2) { 12 | for (int i= 0; i < m[n]; i++) res.push_back(n); 13 | } 14 | vector remain; 15 | for (int n : arr1) { 16 | if (!m.count(n)) remain.push_back(n); 17 | } 18 | sort(remain.begin(), remain.end()); 19 | res.insert(res.end(), remain.begin(), remain.end()); 20 | return res; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /removeAllAdjacentDuplicatesInString/removeAllAdjacentDuplicatesInString.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string removeDuplicates(string S) { 4 | string res; 5 | for (char c : S) { 6 | if (res.back() == c) { 7 | res.pop_back(); 8 | } else { 9 | res.push_back(c); 10 | } 11 | } 12 | return res; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /removeDupFromSortedArray/removeDupFromSortedArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int removeDuplicates(vector& nums) { 8 | int res = 0; 9 | for (int i = 0; i < nums.size(); i++) { 10 | if (i == 0 || nums[i] != nums[i - 1]) { 11 | nums[res++] = nums[i]; 12 | } 13 | } 14 | return res; 15 | } 16 | }; 17 | 18 | int main() 19 | { 20 | Solution s; 21 | int a[5] = {1,1,2,4,5}; 22 | vector vec(a, a+5); 23 | int size = s.removeDuplicates(vec); 24 | for (int i = 0; i < size; i++) 25 | cout << vec[i] << " "; 26 | cout << endl; 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /removeDupFromSortedArray/removeDupFromSortedArray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int removeDuplicates(int[] nums) { 3 | if (nums == null || nums.length == 0) 4 | return 0; 5 | int res = 1; 6 | for (int i = 1; i < nums.length; i++) { 7 | if (nums[i] != nums[i - 1]) 8 | nums[res++] = nums[i]; 9 | } 10 | return res; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /removeDupFromSortedArrayII/removeDupFromSortedArrayII.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | int removeDuplicates(vector& nums) { 8 | if (nums.size() == 0) 9 | return nums.size(); 10 | int left = 0, right = 1; 11 | int count = 0; 12 | while (left < nums.size() && right < nums.size()) { 13 | if (nums[right] == nums[left]) { 14 | count++; 15 | if (count < 2) { 16 | nums[++left] = nums[right]; 17 | } 18 | } else { 19 | nums[++left] = nums[right]; 20 | count = 0; 21 | } 22 | right++; 23 | } 24 | return left + 1; 25 | } 26 | }; 27 | 28 | int main() 29 | { 30 | Solution s; 31 | int a[6] = {1,1,1,1,2,3}; 32 | vector vec(a, a+6); 33 | cout << s.removeDuplicates(vec); 34 | cout << endl; 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /reorderDataInLogFiles/reorderDataInLogFiles.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | static bool cmp (string s1, string s2) { 4 | int p1 = s1.find(' '), p2 = s2.find(' '); 5 | if (!isdigit(s1[p1 + 1]) && !isdigit(s2[p2 + 1])) { 6 | if (s1.substr(p1 + 1) == s2.substr(p2 + 1)) return s1.substr(0, p1 + 1) < s2.substr(0, p2 + 1); 7 | else return s1.substr(p1 + 1) < s2.substr(p2 + 1); 8 | } else { 9 | if (!isdigit(s1[p1 + 1])) return true; 10 | else return false; 11 | } 12 | } 13 | vector reorderLogFiles(vector& logs) { 14 | vector res = logs; 15 | stable_sort(res.begin(), res.end(), cmp); 16 | return res; 17 | } 18 | 19 | }; 20 | -------------------------------------------------------------------------------- /repeatedStringMatch/repeatedStringMatch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int repeatedStringMatch(string A, string B) { 8 | int res = 1; 9 | string A_ = A; 10 | while (A.length() < B.length()) { 11 | A += A_; 12 | res++; 13 | } 14 | if (A.find(B) != string::npos) 15 | return res; 16 | A += A_; 17 | res++; 18 | if (A.find(B) != string::npos) 19 | return res; 20 | return -1; 21 | } 22 | }; 23 | 24 | int main() 25 | { 26 | Solution s; 27 | string A = "abcd"; 28 | string B = "cdabcdab"; 29 | cout << s.repeatedStringMatch(A, B) << endl; 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /replaceAllstoAvoidConsecutiveRepeatingCharacters/replaceAllstoAvoidConsecutiveRepeatingCharacters.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String modifyString(String s) { 3 | char[] ss = s.toCharArray(); 4 | for (int i = 0; i < ss.length; i++) { 5 | if (ss[i] == '?') { 6 | for (char c = 'a'; c <= 'z'; c++) { 7 | if ( (i - 1 < 0 || c != ss[i - 1]) && (i + 1 >= ss.length || c != ss[i + 1]) ) { 8 | ss[i] = c; 9 | } 10 | } 11 | } 12 | } 13 | return new String(ss); 14 | } 15 | } -------------------------------------------------------------------------------- /replaceElementsWithGreatestElementOnRightSide/replaceElementsWithGreatestElementOnRightSide.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector replaceElements(vector& arr) { 4 | vector res(arr.size(), -1); 5 | int curM = arr.back(); 6 | for (int i = arr.size() - 2; i >= 0; i--) { 7 | res[i] = curM; 8 | curM = max(curM, arr[i]); 9 | } 10 | return res; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /reverseBits/reverseBits.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | uint32_t reverseBits(uint32_t n) { 8 | /* n = (n >> 16) | (n << 16); 9 | n = ((n&0xff00ff00) >> 8) | ((n&0x00ff00ff) << 8); 10 | n = ((n&0xf0f0f0f0) >> 4) | ((n&0x0f0f0f0f) << 4); 11 | n = ((n&0xcccccccc) >> 2) | ((n&0x33333333) << 2); 12 | n = ((n&0xaaaaaaaa) >> 1) | ((n&0x55555555) << 1); 13 | return n;*/ 14 | uint32_t ans = 0; 15 | for (int i = 0; i < 32; i++) 16 | ans = ((n>>i)&1) | (ans<<1); 17 | return ans; 18 | } 19 | }; 20 | 21 | int main() 22 | { 23 | Solution s; 24 | cout << s.reverseBits(43261596); 25 | cout << endl; 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /reverseInteger/ReverseInteger.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class ReverseInteger { 4 | public int reverse(int x) { 5 | int flag = 1; 6 | long n = x; 7 | if (n < 0) { 8 | flag = -1; 9 | n = -n; 10 | } 11 | long res = 0; 12 | while (n != 0) { 13 | res = res * 10 + n % 10; 14 | n /= 10; 15 | } 16 | res *= flag; 17 | return res > Integer.MAX_VALUE || res < Integer.MIN_VALUE ? 0 : (int) res; 18 | } 19 | public static void main(String[] args) { 20 | ReverseInteger s = new ReverseInteger(); 21 | int x = -123; 22 | System.out.println(x + "\n" + s.reverse(x)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /reverseInteger/reverseInteger.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int reverse(int x) { 8 | int64_t num = x; 9 | int sign = 1; 10 | if (x < 0) { 11 | sign = -1; 12 | num = -num; 13 | } 14 | int64_t res = 0; 15 | while (num) { 16 | res = 10 * res + num % 10; 17 | num /= 10; 18 | if (res > INT_MAX) 19 | return 0; 20 | } 21 | return res * sign; 22 | } 23 | }; 24 | 25 | int main() 26 | { 27 | Solution s; 28 | int a = -2143857412; 29 | cout << s.reverse(a) << endl; 30 | cout << INT_MAX << endl; 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /reverseInteger/reverseInteger_2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int reverse(int x) { 8 | int64_t res = 0; 9 | while (x) { 10 | res = 10 * res + x % 10; 11 | x /= 10; 12 | } 13 | return (res > INT_MAX || res < INT_MIN) ? 0 : res; 14 | } 15 | }; 16 | 17 | int main() 18 | { 19 | Solution s; 20 | int a = -2143857412; 21 | cout << s.reverse(a) << endl; 22 | cout << INT_MAX << endl; 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /reverseString/reverseString.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | string reverseString(string s) { 8 | int i = 0; 9 | int j = s.length() - 1; 10 | while (i < j) { 11 | swap(s[i++], s[j--]); 12 | } 13 | return s; 14 | } 15 | void swap(char& a, char& b) { 16 | char temp = a; 17 | a = b; 18 | b = temp; 19 | } 20 | }; 21 | 22 | int main() 23 | { 24 | Solution s; 25 | string str = "hello"; 26 | cout << s.reverseString(str) << endl; 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /reverseString/reverseString.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String reverseString(String s) { 3 | char[] ss = s.toCharArray(); 4 | int left = 0, right = ss.length - 1; 5 | while (left < right) { 6 | char temp = ss[left]; 7 | ss[left] = ss[right]; 8 | ss[right] = temp; 9 | left++; 10 | right--; 11 | } 12 | return new String(ss); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /risingTemperature/risingTemperature: -------------------------------------------------------------------------------- 1 | Select w2.Id from Weather w1, Weather w2 2 | where to_days(w2.DATE) - to_days(w1.DATE) = 1 and w1.Temperature < w2.Temperature; -------------------------------------------------------------------------------- /robotBoundedInCircle/robotBoundedInCircle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isRobotBounded(string instructions) { 4 | int x = 0, y = 0, d = 0; 5 | vector > dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; 6 | for (char c : instructions) { 7 | if (c == 'R') { 8 | d = (d + 1) % 4; 9 | } else if (c == 'L') { 10 | d = (d + 3) % 4; 11 | } else { 12 | x += dirs[d][0]; y += dirs[d][1]; 13 | } 14 | } 15 | return (x == 0 && y == 0) || d; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /robotReturnToOrigin/robotReturnToOrigin.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean judgeCircle(String moves) { 3 | Map m = new HashMap<>(); 4 | for (char c : moves.toCharArray()) { 5 | m.put(c, m.getOrDefault(c, 0) + 1); 6 | } 7 | return m.getOrDefault('R', 0).equals(m.getOrDefault('L', 0)) 8 | && m.getOrDefault('D', 0).equals(m.getOrDefault('U', 0)); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /romanToInteger/romanToInteger.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | int romanToInt(string s) { 8 | int ans = 0; 9 | unordered_map m; 10 | m['M'] = 1000; 11 | m['D'] = 500; 12 | m['C'] = 100; 13 | m['L'] = 50; 14 | m['X'] = 10; 15 | m['V'] = 5; 16 | m['I'] = 1; 17 | for(int i = 0; i < s.length(); i++){ 18 | ans += m[s[i]]; 19 | if(i>0 && m[s[i]] > m[s[i-1]]) 20 | ans -= 2*m[s[i-1]]; 21 | //cout << ans << endl; 22 | } 23 | 24 | return ans; 25 | } 26 | }; 27 | 28 | int main() 29 | { 30 | Solution s; 31 | cout << s.romanToInt("MCDLXXVI") << endl; 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /rotateArray/rotateArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | void rotate(vector& nums, int k) { 8 | int size = nums.size(); 9 | if (k == 0) return; 10 | int step = size - k % size; 11 | reverse(nums.begin(), nums.begin() + step); 12 | reverse(nums.begin() + step, nums.end()); 13 | reverse(nums.begin(), nums.end()); 14 | } 15 | }; 16 | 17 | int main() 18 | { 19 | Solution s; 20 | int a[9] = {0, 1, 2, 3, 4, 5, 6, 7, 8}; 21 | vector vec(a,a+4); 22 | s.rotate(vec, 2); 23 | vector::iterator it = vec.begin(); 24 | while (it != vec.end()) { 25 | cout << *it << " "; 26 | ++it; 27 | } 28 | cout << endl; 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /rotateFunction/rotateFunction.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int maxRotateFunction(vector& A) { 8 | int sum = 0; 9 | int len = A.size(); 10 | int F = 0; 11 | for (int i = 0; i < len; i++) { 12 | F += i * A[i]; 13 | sum += A[i]; 14 | } 15 | int res = F; 16 | for (int i = len - 1; i >= 1; i--) { 17 | F = F + sum - len * A[i]; 18 | res = max(F, res); 19 | } 20 | return res; 21 | } 22 | }; 23 | 24 | int main() 25 | { 26 | Solution s; 27 | vector A = {4,3,2,6}; 28 | cout << s.maxRotateFunction(A); 29 | cout << endl; 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /rotateString/rotateString.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool rotateString(string A, string B) { 4 | return A.size() == B.size() && (A + A).find(B) != string::npos; 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /rotateString/rotateString_2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool rotateString(string A, string B) { 4 | if (A == B) return true; 5 | int len_A = A.length(), len_B = B.length(); 6 | if (len_A != len_B) return false; 7 | for (int i = 0; i < len_B; i++) { 8 | if (B[i] == A[0] && checkHelper(A, B, 0, i)) return true; 9 | } 10 | return false; 11 | } 12 | bool checkHelper(string& A, string& B, int pA, int pB) { 13 | int len = A.length(); 14 | for (int i = 0; i < len; i++) { 15 | if (pB >= len) pB = pB % len; 16 | if (A[pA] != B[pB]) return false; 17 | pA++; pB++; 18 | } 19 | return true; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /scoreOfParentheses/scoreOfParentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int scoreOfParentheses(string S) { 4 | stack stk; 5 | int cur = 0; 6 | for (char c : S) { 7 | if (c == '(') { 8 | stk.push(cur); 9 | cur = 0; 10 | } else { 11 | cur = max(cur * 2, 1) + stk.top(); 12 | stk.pop(); 13 | } 14 | } 15 | return cur; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /scoreOfParentheses/scoreOfParentheses_1.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int scoreOfParentheses(string S) { 4 | int res = 0, level = 0; 5 | for (int i = 0; i < S.length(); i++) { 6 | if (S[i] == '(') level++; 7 | else level--; 8 | if (S[i] == ')' && S[i - 1] == '(') 9 | res += 1 << level; 10 | } 11 | return res; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /searchA2DMatrix/searchA2DMatrix.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean searchMatrix(int[][] matrix, int target) { 3 | int m = matrix.length, n = matrix[0].length; 4 | int left = 0, right = m * n - 1; 5 | while (left + 1 < right) { 6 | int mid = left + (right - left) / 2; 7 | int i = mid / n; 8 | int j = mid % n; 9 | if (matrix[i][j] < target) { 10 | left = mid; 11 | } else if (matrix[i][j] > target) { 12 | right = mid; 13 | } else { 14 | return true; 15 | } 16 | } 17 | if (matrix[left / n][left % n] == target || matrix[right / n][right % n] == target) return true; 18 | else return false; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /searchA2DMatrixII/searchA2DMatrixII.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean searchMatrix(int[][] matrix, int target) { 3 | int m = matrix.length, n = matrix[0].length; 4 | int i = 0, j = n - 1; 5 | while (i < m && j >= 0) { 6 | if (target > matrix[i][j]) { 7 | i++; 8 | } else if (target < matrix[i][j]) { 9 | j--; 10 | } else { 11 | return true; 12 | } 13 | } 14 | return false; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /searchInASortedArrayOfUnknownSize/searchInASortedArrayOfUnknownSize.cpp: -------------------------------------------------------------------------------- 1 | // Forward declaration of ArrayReader class. 2 | class ArrayReader; 3 | 4 | class Solution { 5 | public: 6 | int search(const ArrayReader& reader, int target) { 7 | int left = 0, right = 10000; 8 | while (left + 1 < right) { 9 | int mid = left + (right - left) / 2; 10 | int val = reader.get(mid); 11 | if (val > target) { 12 | right = mid; 13 | } else if (val < target) { 14 | left = mid; 15 | } else { 16 | return mid; 17 | } 18 | } 19 | if (reader.get(left) == target) return left; 20 | if (reader.get(right) == target) return right; 21 | return -1; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /searchInsertPosition/searchInsertPosition.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | int searchInsert(vector& nums, int target) { 8 | int low = 0, high = nums.size() - 1; 9 | while (low <= high) { 10 | int mid = low + (high - low)/2; 11 | if (nums[mid] < target) 12 | low = mid + 1; 13 | else if (nums[mid] > target) 14 | high = mid - 1; 15 | else 16 | return mid; 17 | } 18 | return low; 19 | } 20 | }; 21 | 22 | int main() 23 | { 24 | Solution s; 25 | int a[8] = {1,3,5,6,7,8,9,10}; 26 | vector vec(a, a+8); 27 | cout << s.searchInsert(vec, 5) << endl; 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /secondHighestSalary/secondHighestSalary: -------------------------------------------------------------------------------- 1 | select max(Salary) SecondHighestSalary from Employee 2 | where Salary < (select max(Salary )from Employee) -------------------------------------------------------------------------------- /selfDividingNumbers/selfDividingNumbers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution 6 | { 7 | public: 8 | vector selfDividingNumbers(int left, int right) { 9 | vector res; 10 | int i = left; 11 | while (i <= right) { 12 | int n = i; 13 | bool isSelfDividing = true; 14 | while (n) { 15 | int r = n % 10; 16 | n /= 10; 17 | if ( r == 0 || (i % r != 0) ) { 18 | isSelfDividing = false; 19 | break; 20 | } 21 | } 22 | if (isSelfDividing) 23 | res.push_back(i); 24 | i++; 25 | }//while 26 | return res; 27 | } 28 | }; 29 | 30 | int main() 31 | { 32 | Solution s; 33 | vector res = s.selfDividingNumbers(1, 22); 34 | for (int i : res) 35 | cout << i << " "; 36 | cout << endl; 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /setMismatch/setMismatch.cpp: -------------------------------------------------------------------------------- 1 | // clang++ setMismatch.cpp -std=c++11 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution{ 8 | public: 9 | vector findErrorNums(vector& nums) { 10 | vector ans; 11 | int size = nums.size(); 12 | vector hash(size+1, 0); 13 | for (int i = 0; i < size; i++) { 14 | if (++hash[nums[i]] == 2) 15 | ans.push_back(nums[i]); 16 | } 17 | for (int i = 1; i < size+1; i++) { 18 | if (hash[i] == 0) 19 | ans.push_back(i); 20 | } 21 | return ans; 22 | } 23 | }; 24 | 25 | int main() 26 | { 27 | Solution s; 28 | vector vec = {1,2,2,4}; 29 | vector res = s.findErrorNums(vec); 30 | for (int i : res) 31 | cout << i << " "; 32 | cout << endl; 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /shortestPalindrome/shortestPalindrome.cpp: -------------------------------------------------------------------------------- 1 | // clang++ shortestPalindrome.cpp -std=c++11 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | string shortestPalindrome(string s) { 10 | string res; 11 | string rs(s.rbegin(), s.rend()); 12 | int n = s.length(); 13 | for (int i = 0; i < n; i++) { 14 | if (s.substr(0, n - i) == rs.substr(i)) { 15 | return rs.substr(0, i) + s; 16 | } 17 | } 18 | return res; 19 | } 20 | }; 21 | 22 | int main() 23 | { 24 | Solution s; 25 | string ss = "aacecaaa"; 26 | cout << s.shortestPalindrome(ss) << endl; 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /shortestPalindrome/shortestPalindrome2.cpp: -------------------------------------------------------------------------------- 1 | // clang++ shortestPalindrome.cpp -std=c++11 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | string shortestPalindrome(string s) { 10 | int n = s.size(); 11 | int i = 0; 12 | for (int j = n - 1; j >= 0; j--) { 13 | if (s[i] == s[j]) 14 | i++; 15 | } 16 | if (i == n) 17 | return s; 18 | string remain_rev = s.substr(i, n); 19 | reverse(remain_rev.begin(), remain_rev.end()); 20 | return remain_rev + shortestPalindrome(s.substr(0, i)) + s.substr(i); 21 | } 22 | }; 23 | 24 | int main() 25 | { 26 | Solution s; 27 | string ss = "aacecaaa"; 28 | cout << s.shortestPalindrome(ss) << endl; 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /shuffleTheArray/shuffleTheArray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] shuffle(int[] nums, int n) { 3 | int[] res = new int[nums.length]; 4 | int index = 0; 5 | for (int i = 0; i < n; i++) { 6 | res[index++] = nums[i]; 7 | res[index++] = nums[i + n]; 8 | } 9 | return res; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /similarRGBColor/similarRGBColor.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Solution { 4 | public: 5 | string similarRGB(string color) { 6 | return "#" + helper(color.substr(1, 2)) + helper(color.substr(3, 2)) + helper(color.substr(5, 2)); 7 | } 8 | string helper(string str) { 9 | string dec_to_hex = "0123456789abcdef"; 10 | string res = ""; 11 | int dec_num = stoi(str, nullptr, 16); 12 | int c0 = dec_num / 17; 13 | int c1 = dec_num % 17; 14 | if (c1 > 8) 15 | c0 = c0 + 1; 16 | res = res + dec_to_hex[c0] + dec_to_hex[c0]; 17 | return res; 18 | } 19 | }; 20 | 21 | int main() { 22 | Solution s; 23 | cout << s.similarRGB("#09f166") << endl; 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /simplifyPath/simplifyPath.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution{ 7 | public: 8 | string simplifyPath(string path) { 9 | string ans; 10 | int size = path.length(); 11 | istringstream iss(path); 12 | string temp; 13 | vector vec; 14 | while (getline(iss, temp, '/')) { 15 | if (temp == "" || temp == ".") { 16 | continue; 17 | } else if (temp == "..") { 18 | if (!vec.empty()) 19 | vec.pop_back(); 20 | } else { 21 | vec.push_back(temp); 22 | } 23 | } 24 | for (string ss : vec) 25 | ans += "/" + ss; 26 | return ans == "" ? "/" : ans; 27 | } 28 | }; 29 | 30 | int main() 31 | { 32 | Solution s; 33 | string path = "/.."; 34 | cout << s.simplifyPath(path); 35 | cout << endl; 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /singleNumber/singleNumber.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | int singleNumber(vector& nums) { 8 | int ans = 0; 9 | int size = nums.size(); 10 | for (int i = 0; i < size; i++) { 11 | ans ^= nums[i]; 12 | } 13 | return ans; 14 | } 15 | }; 16 | 17 | int main() 18 | { 19 | Solution s; 20 | int a[7] = {1,3,2,2,5,3,5}; 21 | vector vec(a, a+7); 22 | cout << s.singleNumber(vec); 23 | cout << endl; 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /singleNumber/singleNumber_2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int singleNumber(vector& nums) { 8 | int res = 1; 9 | for (int n : nums) 10 | res ^= n; 11 | return res ^ 1; 12 | } 13 | }; 14 | 15 | int main() 16 | { 17 | Solution s; 18 | int a[7] = {1,3,2,2,5,3,5}; 19 | vector vec(a, a+7); 20 | cout << s.singleNumber(vec); 21 | cout << endl; 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /slidingWindowMaximum/slidingWindowMaximum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] maxSlidingWindow(int[] nums, int k) { 3 | if (nums == null || k <= 0) 4 | return new int[0]; 5 | int[] res = new int[nums.length - k + 1]; 6 | int index = 0; 7 | Deque dq = new ArrayDeque<>(); 8 | for (int i = 0; i < nums.length; i++) { 9 | while (!dq.isEmpty() && dq.peek() < i - k + 1) 10 | dq.poll(); 11 | while (!dq.isEmpty() && nums[dq.peekLast()] < nums[i]) 12 | dq.pollLast(); 13 | dq.offer(i); 14 | if (i >= k - 1) { 15 | res[index++] = nums[dq.peek()]; 16 | } 17 | } 18 | return res; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /sortArrayByParity/sortArrayByParity.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector sortArrayByParity(vector& A) { 4 | vector res = A; 5 | int lastOdd = 0; 6 | for (int i = 0; i < A.size(); i++) { 7 | if (A[i] % 2 == 0) { 8 | swap(res[lastOdd++], res[i]); 9 | } 10 | } 11 | return res; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /sortCharactersByFrequency/sortCharactersByFrequency.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | string frequencySort(string s) { 9 | string res; 10 | unordered_map m; 11 | for (char c : s) 12 | m[c]++; 13 | vector bucket(s.length() + 1, ""); 14 | for (auto& p : m) { 15 | bucket[p.second] += string(p.second, p.first); 16 | } 17 | for (int i = bucket.size() - 1; i > 0; i--) 18 | res += bucket[i]; 19 | return res; 20 | } 21 | }; 22 | 23 | int main() 24 | { 25 | Solution s; 26 | string ss = "tree"; 27 | cout << s.frequencySort(ss); 28 | cout << endl; 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /sortColors/sortColors.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void sortColors(int[] nums) { 3 | int left = 0, right = nums.length - 1; 4 | int i = 0; 5 | while (i <= right) { 6 | if (nums[i] == 0) { 7 | swap(nums, left++, i); 8 | } else if (nums[i] == 2) { 9 | swap(nums, i, right--); 10 | i--; 11 | } 12 | i++; 13 | } 14 | } 15 | 16 | private void swap(int[] nums, int left, int right) { 17 | int tmp = nums[left]; 18 | nums[left] = nums[right]; 19 | nums[right] = tmp; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /soupServings/soupServings.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public double soupServings(int n) { 3 | if (n > 4800) return 1.0; 4 | n = (n + 24) / 25; 5 | double[][] dp = new double[n + 1][n + 1]; 6 | dp[0][0] = 0.5; 7 | for (int j = 1; j <= n; j++) dp[0][j] = 1; 8 | int[][] serve = {{4, 0}, {3, 1}, {2, 2}, {1, 3}}; 9 | for (int i = 1; i <= n; i++) { 10 | for (int j = 1; j <= n; j++) { 11 | for (int[] s : serve) { 12 | int prevI = i >= s[0] ? i - s[0] : 0; 13 | int prevJ = j >= s[1] ? j - s[1] : 0; 14 | dp[i][j] += 0.25 * dp[prevI][prevJ]; 15 | } 16 | } 17 | } 18 | return dp[n][n]; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /sqrtX/sqrtX.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution{ 5 | public: 6 | int mySqrt(int x) { 7 | if (x == 0) 8 | return 0; 9 | long long left = 1, right = x; 10 | while (left <= right) { 11 | long long mid = left + (right-left)/2; 12 | if (mid * mid > x) 13 | right = mid - 1; 14 | else if (mid * mid < x) 15 | left = mid + 1; 16 | else 17 | return mid; 18 | } 19 | return left - 1; 20 | } 21 | }; 22 | 23 | int main() 24 | { 25 | Solution s; 26 | cout << s.mySqrt(35) << endl; 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /squaresOfSortedArray/squaresOfSortedArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector sortedSquares(vector& A) { 4 | vector res(A.size(), 0); 5 | int i = A.size() - 1; 6 | int left = 0, right = A.size() - 1; 7 | while (left <= right) { 8 | if (abs(A[left]) < abs(A[right])) { 9 | res[i--] = A[right] * A[right]; 10 | right--; 11 | } else { 12 | res[i--] = A[left] * A[left]; 13 | left++; 14 | } 15 | } 16 | return res; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /studentAttendanceRecordI/studentAttendanceRecordI.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | bool checkRecord(string s) { 8 | int countA = 0, countL = 0; 9 | for(int i = 0; i < s.length(); i++) { 10 | if (s[i] == 'A') 11 | countA++; 12 | if (s[i] == 'L') { 13 | countL++; 14 | if (countL > 2) 15 | return false; 16 | } else { 17 | countL = 0; 18 | } 19 | } 20 | return countA < 2; 21 | } 22 | }; 23 | 24 | int main() 25 | { 26 | Solution s; 27 | string str = "PPALLL"; 28 | cout << s.checkRecord(str) << endl; 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /studentAttendanceRecordII/studentAttendanceRecordII.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int checkRecord(int n) { 8 | vector dp( (n <= 3 ? 4 : n + 1) , 0); 9 | dp[0] = 1; 10 | dp[1] = 2; 11 | dp[2] = 4; 12 | dp[3] = 7; // 2 ^ 3 - LLL 13 | for (int i = 4; i <= n; i++) 14 | dp[i] = ((2 * dp[i - 1]) % M + (M - dp[i - 4])) % M; 15 | long sum = dp[n]; 16 | for (int i = 1; i <= n; i++) { 17 | sum += (dp[i - 1] * dp[n - i]) % M; 18 | } 19 | return (int)(sum % M); 20 | } 21 | long M = 1000000007; 22 | }; 23 | 24 | int main() 25 | { 26 | Solution s; 27 | int n = 2; 28 | cout << s.checkRecord(n) << endl; 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /subArraySumEqualsK/subArraySumEqualsK.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int subarraySum(int[] nums, int k) { 3 | int res = 0; 4 | if (nums == null || nums.length == 0) 5 | return res; 6 | int[] preSum = new int[nums.length + 1]; 7 | preSum[0] = 0; 8 | for (int i = 0; i < nums.length; i++) 9 | preSum[i + 1] = preSum[i] + nums[i]; 10 | Map m = new HashMap<>(); 11 | for (int i = 0; i < preSum.length; i++) { 12 | if (m.containsKey(preSum[i] - k)) 13 | res += m.get(preSum[i] - k); 14 | if (!m.containsKey(preSum[i])) 15 | m.put(preSum[i], 1); 16 | else 17 | m.put(preSum[i], m.get(preSum[i]) + 1); 18 | } 19 | return res; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /subsets/subsets.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> subsets(int[] nums) { 3 | List> res = new ArrayList<>(); 4 | List path = new ArrayList<>(); 5 | dfs(res, path, nums, 0); 6 | return res; 7 | } 8 | 9 | void dfs(List> res, List path, int[] nums, int index) { 10 | res.add(new ArrayList<>(path)); 11 | for (int i = index; i < nums.length; i++) { 12 | path.add(nums[i]); 13 | dfs(res, path, nums, i + 1); 14 | path.remove(path.size() - 1); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /subsetsII/subsetsII.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> subsetsWithDup(int[] nums) { 3 | List> res = new ArrayList<>(); 4 | if (nums == null || nums.length == 0) { 5 | return res; 6 | } 7 | Arrays.sort(nums); 8 | List path = new ArrayList(); 9 | dfs(nums, res, path, 0); 10 | return res; 11 | } 12 | 13 | private void dfs(int[] nums, List> res, List path, int index) { 14 | res.add(new ArrayList<>(path)); 15 | for (int i = index; i < nums.length; i++) { 16 | if (i > index && nums[i] == nums[i - 1]) continue; 17 | path.add(nums[i]); 18 | dfs(nums, res, path, i + 1); 19 | path.remove(path.size() - 1); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /substractTheProductAndSumOfDigitsOfAnInteger/substractTheProductAndSumOfDigitsOfAnInteger.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int subtractProductAndSum(int n) { 3 | int product = 1; 4 | int sum = 0; 5 | while (n != 0) { 6 | int m = n % 10; 7 | product *= m; 8 | sum += m; 9 | n = n / 10; 10 | } 11 | return product - sum; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /sumOfSquareNumbers/sumOfSquareNumbers.cpp: -------------------------------------------------------------------------------- 1 | // clang++ sumOfSquareNumbers.cpp 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | 8 | class Solution{ 9 | public: 10 | bool judgeSquareSum(int c) { 11 | /*long left = 0, right = (int)sqrt(c); 12 | while (left <= right) { 13 | long sum = left * left + right * right; 14 | if (sum > c) 15 | right--; 16 | else if(sum < c) 17 | left++; 18 | else 19 | return true; 20 | } 21 | return false; */ 22 | for (int i = 0; i <= floor(sqrt(c)); i++) { 23 | if (floor(sqrt(c - i * i)) == sqrt(c - i * i)) 24 | return true; 25 | } 26 | return false; 27 | } 28 | }; 29 | 30 | int main() 31 | { 32 | Solution s; 33 | cout << s.judgeSquareSum(3); 34 | cout << endl; 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /sumOfTwoIntegers/sumOfTwoIntegers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution{ 5 | public: 6 | int getSum(int a, int b) { 7 | if (a == 0) 8 | return b; 9 | if (b == 0) 10 | return a; 11 | int carry = a & b; 12 | int ans = a ^ b; 13 | while (carry != 0) { 14 | b = carry << 1; 15 | carry = ans & b; 16 | ans = ans ^ b; 17 | } 18 | return ans; 19 | } 20 | }; 21 | 22 | int main() 23 | { 24 | Solution s; 25 | cout << s.getSum(5,3); 26 | cout << endl; 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /superPow/superPow.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution{ 7 | public: 8 | int superPow(int a, vector& b) { 9 | if (b.empty()) 10 | return 1; 11 | int last_digit = b.back(); 12 | b.pop_back(); 13 | return powmod(superPow(a, b), 10) * powmod(a, last_digit) % 1337; 14 | } 15 | int powmod(int a, int k) { 16 | int res = 1; 17 | a %= 1337; 18 | for (int i = 0; i < k; i++) { 19 | res = (res * a) % 1337; 20 | } 21 | return res; 22 | } 23 | }; 24 | 25 | int main() 26 | { 27 | Solution s; 28 | int a[2] = {1,0}; 29 | vector vec(a, a+2); 30 | cout << s.superPow(2, vec); 31 | cout << endl; 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /swapSalary/swapSalary: -------------------------------------------------------------------------------- 1 | update salary set sex = CHAR(ASCII('f') ^ ASCII('m') ^ ASCII(sex)); -------------------------------------------------------------------------------- /targetSum/targetSum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution{ 7 | public: 8 | int findTargetSumWays(vector& nums, int S) { 9 | int sum = accumulate(nums.begin(), nums.end(), 0); 10 | return sum < S || (S + sum) & 1 ? 0 : subsetSum(nums, (S + sum) >> 1); 11 | } 12 | int subsetSum(vector& nums, int target) { 13 | vector m(target+1, 0); 14 | m[0] = 1; 15 | for (int n : nums) 16 | for (int i = target; i >= n;i--) 17 | m[i] += m[i-n]; 18 | return m[target]; 19 | } 20 | }; 21 | 22 | int main() 23 | { 24 | Solution s; 25 | vector vec(5, 1); 26 | cout << s.findTargetSumWays(vec, 3); 27 | cout << endl; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /targetSum/targetSum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findTargetSumWays(int[] nums, int target) { 3 | int sum = 0; 4 | for (int num : nums) sum += num; 5 | if (sum < target) return 0; 6 | int p = target + sum; 7 | if (p < 0 || p % 2 != 0) return 0; 8 | p = p / 2; 9 | 10 | int[][] dp = new int[nums.length + 1][p + 1]; 11 | dp[0][0] = 1; 12 | for (int i = 1; i <= nums.length; i++) { 13 | for (int j = 0; j <= p; j++) { 14 | dp[i][j] += dp[i - 1][j]; 15 | if (j >= nums[i - 1]) { 16 | dp[i][j] += dp[i - 1][j - nums[i - 1]]; 17 | } 18 | } 19 | } 20 | return dp[nums.length][p]; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /taskScheduler/taskScheduler.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution{ 7 | public: 8 | int leastInterval(vector& tasks, int n) { 9 | int res = 0; 10 | unordered_map m; 11 | int maxN = 1; 12 | for (char c : tasks) 13 | maxN = max (maxN, ++m[c]); 14 | int num = 0; 15 | for (auto& p : m) { 16 | if (p.second == maxN) 17 | num++; 18 | } 19 | return max ( (int)tasks.size(), (maxN - 1) * (n + 1) + num ); 20 | } 21 | }; 22 | 23 | int main() 24 | { 25 | Solution s; 26 | char a[6] = {'A','A','A','B','B','B'}; 27 | vector vec(a, a+6); 28 | cout << s.leastInterval(vec, 2); 29 | cout << endl; 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /toLowerCase/toLowerCase.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String toLowerCase(String str) { 3 | char[] arr = str.toCharArray(); 4 | for (int i = 0; i < arr.length; i++) { 5 | if (arr[i] >= 'A' && arr[i] <= 'Z') 6 | arr[i] = (char) (arr[i] - 'A' + 'a'); 7 | } 8 | return new String(arr); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /totalHammingDistance/totalHammingDistance.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | int totalHammingDistance(vector& nums) { 8 | int res = 0; 9 | if (nums.size() == 0) 10 | return res; 11 | for (int i = 0; i < sizeof(int) * 8; i++) { 12 | int countOne = 0; 13 | for (int num : nums) { 14 | num >>= i; 15 | if ((num & 1) == 1) 16 | countOne++; 17 | } 18 | res += (countOne) * (nums.size() - countOne); 19 | } 20 | return res; 21 | } 22 | }; 23 | 24 | int main() 25 | { 26 | Solution s; 27 | vector vec = {4,14,2}; 28 | cout << s.totalHammingDistance(vec); 29 | cout << endl; 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /trappingRainWater/trappingRainWater.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int trap(int[] height) { 3 | int res = 0; 4 | int left = 0, right = height.length - 1; 5 | int leftM = 0, rightM = 0; 6 | while (left < right) { 7 | if (height[left] < height[right]) { 8 | if (height[left] > leftM) { 9 | leftM = height[left]; 10 | } else { 11 | res += leftM - height[left]; 12 | } 13 | left++; 14 | } else { 15 | if (height[right] > rightM) { 16 | rightM = height[right]; 17 | } else { 18 | res += rightM - height[right]; 19 | } 20 | right--; 21 | } 22 | } 23 | return res; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /twoSum/twoSum.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class TwoSum { 4 | public int[] twoSum(int[] nums, int target) { 5 | int[] res = new int[2]; 6 | Map m = new HashMap(); 7 | for (int i = 0; i < nums.length; i++) { 8 | if (m.containsKey(target - nums[i])) { 9 | res[1] = i; 10 | res[0] = m.get(target - nums[i]); 11 | return res; 12 | } 13 | m.put(nums[i], i); 14 | } 15 | return res; 16 | } 17 | public static void main(String[] args) { 18 | TwoSum s = new TwoSum(); 19 | int[] nums = {2, 7, 11, 15}; 20 | int target = 9; 21 | for (int n : s.twoSum(nums, target)) { 22 | System.out.print(n + " "); 23 | } 24 | System.out.println(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /uglyNumber/uglyNumber.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution{ 5 | public: 6 | bool isUgly(int num) { 7 | if (num == 0) 8 | return false; 9 | while (num % 5 == 0) 10 | num = num / 5; 11 | while (num % 3 == 0) 12 | num = num / 3; 13 | while (num % 2 == 0) 14 | num = num / 2; 15 | return num == 1; 16 | } 17 | }; 18 | 19 | int main() 20 | { 21 | Solution s; 22 | cout << s.isUgly(11)<< endl; 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /uglyNumberII/uglyNumberII.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int nthUglyNumber(int n) { 3 | int[] uglys = new int[n]; 4 | uglys[0] = 1; 5 | int p2 = 0, p3 = 0, p5 = 0; 6 | for (int i = 1; i < n; i++) { 7 | int min2 = uglys[p2] * 2; 8 | int min3 = uglys[p3] * 3; 9 | int min5 = uglys[p5] * 5; 10 | int ugly = Math.min(min2, Math.min(min3, min5)); 11 | uglys[i] = ugly; 12 | if (min2 == ugly) p2++; 13 | if (min3 == ugly) p3++; 14 | if (min5 == ugly) p5++; 15 | } 16 | return uglys[n - 1]; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /uncrossedLines/uncrossedLines.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxUncrossedLines(vector& A, vector& B) { 4 | int size_a = A.size(), size_b = B.size(); 5 | if (size_a == 0 || size_b == 0) 6 | return 0; 7 | vector > dp(size_a + 1, vector(size_b + 1, 0)); 8 | for (int i = 1; i <= size_a; i++) { 9 | for (int j = 1; j <= size_b; j++) { 10 | if (A[i - 1] == B[j - 1]) { 11 | dp[i][j] = dp[i - 1][j - 1] + 1; 12 | } else { 13 | dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); 14 | } 15 | } 16 | } //for 17 | return dp[size_a][size_b]; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /uniqueEmailAddresses/uniqueEmailAddresses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numUniqueEmails(vector& emails) { 4 | unordered_set s; 5 | for (string& email : emails) { 6 | string key = ""; 7 | bool ignore = false; 8 | for (int i = 0; i < email.length(); i++) { 9 | char c = email[i]; 10 | if (c == '+') { 11 | ignore = true; 12 | } else if (c == '@') { 13 | key += email.substr(i); 14 | break; 15 | } 16 | if (!ignore && c != '.') 17 | key += c; 18 | } 19 | //cout << key << endl; 20 | s.insert(key); 21 | } 22 | return s.size(); 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /uniqueEmailAddresses/uniqueEmailAddresses.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numUniqueEmails(String[] emails) { 3 | Set set = new HashSet<>(); 4 | for (String email : emails) { 5 | String[] parts = email.split("@"); 6 | String[] firstPart = parts[0].split("\\+"); 7 | set.add(firstPart[0].replace(".", "") + "@" + parts[1]); 8 | } 9 | return set.size(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /uniquePaths/uniquePaths.cpp: -------------------------------------------------------------------------------- 1 | // clang++ uniquePaths.cpp -std=c++11 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | int uniquePaths(int m, int n) { 10 | vector > dp(m + 1, vector(n + 1, 0)); 11 | for (int i = 1; i <= m; i++) { 12 | for (int j = 1; j <= n; j++) { 13 | if (i == 1 && j == 1) 14 | dp[i][j] = 1; 15 | else 16 | dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; 17 | } 18 | } 19 | return dp[m][n]; 20 | } 21 | }; 22 | 23 | int main() 24 | { 25 | Solution s; 26 | cout << s.uniquePaths(2,1) << endl;; 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /uniquePaths/uniquePaths_2.cpp: -------------------------------------------------------------------------------- 1 | // clang++ uniquePaths_2.cpp -std=c++11 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | int uniquePaths(int m, int n) { 10 | vector dp(n + 1, 0); 11 | for (int i = 1; i <= m; i++) { 12 | for (int j = 1; j <= n; j++) { 13 | if (i == 1 && j == 1) 14 | dp[j] = 1; 15 | else 16 | dp[j] += dp[j - 1]; 17 | } 18 | } 19 | return dp[n]; 20 | } 21 | }; 22 | 23 | int main() 24 | { 25 | Solution s; 26 | cout << s.uniquePaths(2,1) << endl;; 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /validAnagram/validAnagram.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | bool isAnagram(string s, string t) { 8 | if (s.length() != t.length()) return false; 9 | unordered_map m; 10 | for (int i = 0; i < s.length(); i++) { 11 | m[s[i]]++; 12 | m[t[i]]--; 13 | } 14 | for (auto& p : m) { 15 | if (p.second) return false; 16 | } 17 | return true; 18 | } 19 | }; 20 | 21 | int main() 22 | { 23 | Solution s; 24 | string str1 = "anagram"; 25 | string str2 = "nagaram"; 26 | cout << s.isAnagram(str1, str2); 27 | cout << endl; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /validPalindromeII/validPalindromeII.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean validPalindrome(String s) { 3 | int left = 0, right = s.length() - 1; 4 | while (left < right) { 5 | if (s.charAt(left) != s.charAt(right)) { 6 | return isPalindrome(s, left + 1, right) || isPalindrome(s, left, right - 1); 7 | } else { 8 | left++; right--; 9 | } 10 | } 11 | return true; 12 | } 13 | 14 | private boolean isPalindrome(String s, int left, int right) { 15 | while (left < right) { 16 | if (s.charAt(left++) != s.charAt(right--)) return false; 17 | } 18 | return true; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /validParentheses/validParentheses.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | bool isValid(string s) { 9 | unordered_map m; 10 | m.insert({')', '('}); 11 | m.insert({'}', '{'}); 12 | m.insert({']', '['}); 13 | stack stk; 14 | for (char c : s) { 15 | if (c == ')' || c == '}' || c == ']') { 16 | if (stk.empty() || stk.top() != m[c]) return false; 17 | else stk.pop(); 18 | } else { 19 | stk.push(c); 20 | } 21 | } 22 | return stk.empty(); 23 | } 24 | }; 25 | 26 | int main() 27 | { 28 | Solution s; 29 | cout << s.isValid(string("{}{}{}{}[][]")) << endl; 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /validPerfectSquare/validPerfectSquare.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution{ 5 | public: 6 | bool isPerfectSquare(int num) { 7 | int left = 1, right = num; 8 | while (left <= right) { 9 | long long mid = left + (right - left)/2; 10 | if (mid * mid > num) 11 | right = mid - 1; 12 | else if (mid * mid < num) 13 | left = mid + 1; 14 | else 15 | return true; 16 | } 17 | return false; 18 | } 19 | }; 20 | 21 | int main() 22 | { 23 | Solution s; 24 | cout << s.isPerfectSquare(14)<< endl; 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /validTriangleNumber/validTriangleNumber.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution{ 7 | public: 8 | int triangleNumber(vector& nums) { 9 | int ans = 0; 10 | int size = nums.size(); 11 | sort(nums.begin(), nums.end()); 12 | for (int i = size-1; i >= 2; i--) { 13 | int left = 0, right = i - 1; 14 | while (left < right) { 15 | if (nums[right] + nums[left] > nums[i]) { 16 | ans += right - left; 17 | right--; 18 | } else 19 | left++; 20 | } 21 | } 22 | return ans; 23 | } 24 | }; 25 | 26 | int main() 27 | { 28 | Solution s; 29 | int a[4] = {2,2,3,4}; 30 | vector vec(a, a+4); 31 | cout << s.triangleNumber(vec); 32 | cout << endl; 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /verifyPreorderSerializationOfBinaryTree/verifyPreorderSerializationOfBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | bool isValidSerialization(string preorder) { 8 | istringstream iss(preorder); 9 | string str; 10 | int indegree = 1; 11 | while (getline(iss, str, ',')) { 12 | if (--indegree < 0) 13 | return false; 14 | if (str != "#") { 15 | indegree += 2; 16 | } 17 | } 18 | return indegree == 0; 19 | } 20 | }; 21 | 22 | int main() { 23 | Solution s; 24 | string ss = "9,3,4,#,#,1,#,#,2,#,6,#,#"; 25 | cout << s.isValidSerialization(ss) << endl; 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /waterAndJugProblem/waterAndJugProblem.cpp: -------------------------------------------------------------------------------- 1 | // clang++ waterAndJugProblem.cpp -std=c++11 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | 8 | class Solution{ 9 | public: 10 | bool canMeasureWater(int x, int y, int z) { 11 | return z == 0 || (x + y >= z && z % gcd(x, y) == 0); 12 | } 13 | int gcd(int x, int y) { 14 | return y == 0 ? x : gcd(y, x % y); 15 | } 16 | }; 17 | 18 | int main() 19 | { 20 | Solution s; 21 | cout << s.canMeasureWater(3, 5, 4) << endl; 22 | cout << s.canMeasureWater(2, 6, 5) << endl; 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /wiggleSort/wiggleSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | void wiggleSort(vector& nums) { 8 | if (nums.size() < 1) 9 | return; 10 | for (int i = 1; i < nums.size(); i++) { 11 | if (i % 2 != 0) { 12 | if (nums[i - 1] > nums[i]) 13 | swap(nums[i - 1], nums[i]); 14 | } else { 15 | if (nums[i - 1] < nums[i]) 16 | swap(nums[i - 1], nums[i]); 17 | } 18 | } 19 | } 20 | }; 21 | 22 | int main() { 23 | Solution s; 24 | vector nums = {3, 5, 2, 1, 6, 4}; 25 | s.wiggleSort(nums); 26 | for (int n : nums) 27 | cout << n << " "; 28 | cout << endl; 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /wiggleSortII/wiggleSortII.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | class Solution { 5 | public: 6 | void wiggleSort(vector& nums) { 7 | vector tmp = nums; 8 | sort(tmp.begin(), tmp.end()); 9 | int n = nums.size(); 10 | int mid = (n - 1) / 2; 11 | int index = 0; 12 | for (int i = 0; i <= mid; i++) { 13 | nums[index] = tmp[mid - i]; 14 | if (index + 1 < n) { 15 | nums[index + 1] = tmp[n - 1 - i]; 16 | } 17 | index += 2; 18 | } 19 | } 20 | }; 21 | 22 | int main() { 23 | Solution s; 24 | vector nums = {1, 5, 1, 1, 6, 4}; 25 | s.wiggleSort(nums); 26 | for (int n : nums) 27 | cout << n << " "; 28 | cout << endl; 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /wordBreak/wordBreak.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean wordBreak(String s, List wordDict) { 3 | if (s == null) 4 | return true; 5 | boolean[] dp = new boolean[s.length() + 1]; 6 | dp[0] = true; 7 | Set set = new HashSet<>(wordDict); 8 | for (int i = 0; i < s.length(); i++) { 9 | for (int j = i; j >= 0; j--) { 10 | if (dp[j] && set.contains(s.substring(j, i + 1))) { 11 | dp[i + 1] = true; 12 | break; 13 | } 14 | } 15 | } 16 | return dp[s.length()]; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /wordBreak/wordBreak_2.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean wordBreak(String s, List wordDict) { 3 | boolean[] dp = new boolean[s.length() + 1]; 4 | dp[0] = true; 5 | for (int i = 1; i < dp.length; i++) { 6 | for (String word : wordDict) { 7 | if (i - word.length() >= 0 && word.equals(s.substring(i - word.length(), i))) { 8 | if (dp[i - word.length()]){ 9 | dp[i] = true; 10 | break; 11 | } 12 | } 13 | } 14 | } 15 | return dp[s.length()]; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /zigzagConversion/zigzagConversion.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | string convert(string s, int numRows) { 8 | vector rows(numRows); 9 | int i = 0; 10 | while (i < s.length()) { 11 | for (int j = 0; j < numRows && i < s.length(); j++) { // up to down 12 | rows[j] += s[i++]; 13 | } 14 | for (int j = numRows - 2; j >= 1 && i < s.length(); j--) { 15 | rows[j] += s[i++]; 16 | } 17 | } 18 | string res = ""; 19 | for (string& row : rows) 20 | res += row; 21 | return res; 22 | } 23 | }; 24 | 25 | int main() 26 | { 27 | Solution s; 28 | string ss = "ABCDE"; 29 | cout << s.convert(ss, 3) << endl; 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /zigzagConversion/zigzagConversion.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String convert(String s, int numRows) { 3 | StringBuilder[] sb = new StringBuilder[numRows]; 4 | for (int i = 0; i < numRows; i++) sb[i] = new StringBuilder(); 5 | char[] arr = s.toCharArray(); 6 | int i = 0; 7 | while (i < arr.length) { 8 | for (int j = 0; j < numRows && i < arr.length; j++) 9 | sb[j].append(arr[i++]); 10 | for (int j = numRows - 2; j >= 1 && i < arr.length; j--) 11 | sb[j].append(arr[i++]); 12 | } 13 | for (i = 1; i < sb.length; i++) 14 | sb[0].append(sb[i]); 15 | return sb[0].toString(); 16 | } 17 | } 18 | --------------------------------------------------------------------------------