├── JumpFloor ├── JumpFloor.cpp ├── JumpFloor.py └── README.md ├── RectCover ├── RectCover.cpp ├── RectCover.py └── README.md ├── ReorderArray ├── ReorderArray.py └── ReorderArray.cpp ├── ReverseList ├── ReverseList.cpp └── ReverseList.py ├── KLeastNumbers ├── KLeastNumbers.cpp ├── KLeastNumbers.py └── Images │ └── Partition.png ├── ReplaceSpaces ├── ReplaceSpaces.py ├── Images │ ├── 1.jpg │ ├── 2.jpg │ └── 3.jpg └── ReplaceSpaces.cpp ├── MaxInSlidingWindow ├── MaxInSlidingWindow.cpp ├── MaxInSlidingWindow.py └── README.md ├── MoreThanHalfNumber ├── MoreThanHalfNumber.cpp └── MoreThanHalfNumber.py ├── SubstructureInTree ├── SubstructureInTree.cpp └── SubstructureInTree.py ├── SortArrayForMinNumber ├── SortArrayForMinNumber.py ├── Images │ ├── 1.png │ ├── 2.png │ └── 3.png └── SortArrayForMinNumber.cpp ├── SymmetricalBinaryTree ├── SymmetricalBinaryTree.cpp ├── SymmetricalBinaryTree.py └── README.md ├── ContinuousSquenceWithSum ├── ContinuousSquenceWithSum.py └── ContinuousSquenceWithSum.cpp ├── CuttingRope ├── 1.jpg ├── CuttingRope.py └── CuttingRope.cpp ├── InversePairs ├── 1.jpg ├── InversePairs.py └── InversePairs.cpp ├── TranslateNum ├── 1.jpg ├── TranslateNum.py ├── TranslateNum.cpp └── README.md ├── Sort └── img │ └── sort_summary.jpg ├── CopyComplexList ├── Images │ ├── 1.png │ ├── 2.png │ ├── 3.png │ ├── 4.png │ └── 5.png ├── CopyComplexList.py └── CopyComplexList.cpp ├── KthNodeFromEnd ├── Images │ ├── 1.png │ └── 2.jpg ├── KthNodeFromEnd.py └── KthNodeFromEnd.cpp ├── ConstuctArray ├── Image │ └── image.png ├── ConstuctArray.cpp └── ConstuctArray.py ├── DeleteNodeInList ├── Images │ └── 1.png ├── DeleteNodeInList.py ├── DeleteNodeInList.cpp └── README.md ├── StackPushPopOrder ├── Images │ ├── 1.png │ └── 2.png ├── StackPushPopOrder.py ├── StackPushPopOrder.cpp └── README.md ├── ConstructBinaryTree ├── Images │ └── 1.jpg ├── ConstructBinaryTree.cpp └── ConstructBinaryTree.py ├── MirrorOfBinaryTree ├── Images │ └── 1.png ├── MirrorOfBinaryTree.py ├── MirrorOfBinaryTree.cpp └── README.md ├── RegularExpressionsMatching ├── Image │ ├── 1.png │ └── 复杂度分析.png ├── RegularExpressionsMatching.py └── RegularExpressionsMatching.cpp ├── Accumulate ├── Accumulate.py ├── Accumulate.cpp └── README.md ├── NumberOf1InBinary ├── NumberOf1InBinary.py ├── NumberOf1InBinary.cpp └── README.md ├── JumpFloorII ├── JumpFloorII.py ├── JumpFloorII.cpp └── README.md ├── AddTwoNumbers ├── AddTwoNumbers.cpp ├── AddTwoNumbers.py └── README.md ├── NumbersAppearOnce ├── NumbersAppearOnce.py └── NumbersAppearOnce.cpp ├── Fibonacci ├── Fibonacci.py └── Fibonacci.cpp ├── Power ├── Power.py ├── Power.cpp └── README.md ├── LastNumberInCircle ├── LastNumberInCircle.py ├── LastNumberInCircle.cpp └── README.md ├── FirstNotRepeatingChar ├── FirstNotRepeatingChar.py ├── FirstNotRepeatingChar.cpp └── README.md ├── NumberAppearingOnce ├── NumberAppearingOnce.py └── NumberAppearingOnce.cpp ├── FirstCharacterInStream ├── FirstCharacterInStream.cpp ├── FirstCharacterInStream.py └── README.md ├── QueueWithTwoStacks ├── QueueWithTwoStacks.py ├── QueueWithTwoStacks.cpp └── README.md ├── ConvertBinarySearchTree ├── ConvertBinarySearchTree.py └── ConvertBinarySearchTree.cpp ├── NextNodeInBinaryTrees ├── NextNodeInBinaryTrees.py └── NextNodeInBinaryTrees.cpp ├── CMyString ├── CMyString.cpp ├── main.cpp └── CMyString.h ├── ContinousCards ├── ContinousCards.py ├── ContinousCards.cpp └── README.md ├── FindNthDigit ├── FindNthDigit.py ├── FindNthDigit.cpp └── README.md ├── MinInStack ├── MinInStack.cpp ├── MinInStack.py └── README.md ├── DuplicationInArray ├── DuplicationInArray.py ├── DuplicationInArrayNoEdit.py └── DuplicationInArrayNoEdit.cpp ├── EntryNodeInListLoop ├── EntryNodeInListLoop.py └── EntryNodeInListLoop.cpp ├── ReverseWordsInSentence ├── ReverseWordsInSentence.py └── ReverseWordsInSentence.cpp ├── IntegerIdenticalToIndex ├── IntegerIdenticalToIndex.py └── IntegerIdenticalToIndex.cpp ├── MaxQueue ├── MaxQueue.py ├── MaxQueue.cpp └── README.md ├── RobotMove ├── RobotMove.py └── RobotMove.cpp ├── SquenceOfBST ├── SquenceOfBST.py └── SquenceOfBST.cpp ├── PathInTree ├── PathInTree.py └── PathInTree.cpp ├── TreeDepth ├── TreeDepth.py └── TreeDepth.cpp ├── PrintNumbers ├── PrintNumbers.py └── PrintNumbers.cpp ├── NumericStrings ├── NumericStrings.py └── NumericStrings.cpp ├── PrintTreesInZigzag ├── PrintTreesInZigzag.py └── PrintTreesInZigzag.cpp ├── NumberOf1 ├── NumberOf1.py └── NumberOf1.cpp ├── PrintTreeFromTopToBottom ├── PrintTreeFromTopToBottom.py └── PrintTreeFromTopToBottom.cpp ├── PrintMatrix ├── PrintMatrix.py └── PrintMatrix.cpp ├── MinNumberInRotatedArray ├── MinNumberInRotatedArray.py └── MinNumberInRotatedArray.cpp ├── Nge └── README.md ├── MissingNumber ├── MissingNumber.py └── MissingNumber.cpp ├── PrintListInReversedOrder ├── PrintListInReversedOrder.py └── PrintListInReversedOrder.cpp ├── PrintTreesInLines ├── PrintTreesInLines.py └── PrintTreesInLines.cpp ├── BalancedBinaryTree ├── BalancedBinaryTree.py └── BalancedBinaryTree.cpp ├── NumberOfK ├── NumberOfK.py └── NumberOfK.cpp ├── DeleteDuplicatedNode ├── DeleteDuplicatedNode.py └── DeleteDuplicatedNode.cpp ├── LeftRotateString ├── LeftRotateString.py └── LeftRotateString.cpp ├── MergeSortedLists ├── MergeSortedLists.py └── MergeSortedLists.cpp ├── KthNodeInBST ├── KthNodeInBST.py └── KthNodeInBST.cpp ├── StringPathInMatrix ├── StringPathInMatrix.cpp └── StringPathInMatrix.py ├── LongestConsecutive └── README.md ├── TwoNumbersWithSum ├── TwoNumbersWithSum.py └── TwoNumbersWithSum.cpp ├── StringPermutation ├── StringPermutation.py └── StringPermutation.cpp ├── FirstCommonNodesInLists ├── FirstCommonNodesInLists.py └── FirstCommonNodesInLists.cpp ├── UglyNumber ├── UglyNumber.py └── UglyNumber.cpp ├── SerializeBinaryTrees └── SerializeBinaryTrees.py ├── FindInPartiallySortedMatrix ├── FindInPartiallySortedMatrix.py └── FindInPartiallySortedMatrix.cpp ├── StreamMedian ├── StreamMedian.cpp └── StreamMedian.py └── StringToInt └── StringToInt.py /JumpFloor/JumpFloor.cpp: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /JumpFloor/JumpFloor.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /RectCover/RectCover.cpp: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /RectCover/RectCover.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /ReorderArray/ReorderArray.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /ReverseList/ReverseList.cpp: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /ReverseList/ReverseList.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /KLeastNumbers/KLeastNumbers.cpp: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /KLeastNumbers/KLeastNumbers.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /ReorderArray/ReorderArray.cpp: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /ReplaceSpaces/ReplaceSpaces.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /MaxInSlidingWindow/MaxInSlidingWindow.cpp: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /MaxInSlidingWindow/MaxInSlidingWindow.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /MoreThanHalfNumber/MoreThanHalfNumber.cpp: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /MoreThanHalfNumber/MoreThanHalfNumber.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /SubstructureInTree/SubstructureInTree.cpp: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /SubstructureInTree/SubstructureInTree.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /SortArrayForMinNumber/SortArrayForMinNumber.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /SymmetricalBinaryTree/SymmetricalBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /SymmetricalBinaryTree/SymmetricalBinaryTree.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /ContinuousSquenceWithSum/ContinuousSquenceWithSum.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /CuttingRope/1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/CodingInterviews/HEAD/CuttingRope/1.jpg -------------------------------------------------------------------------------- /InversePairs/1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/CodingInterviews/HEAD/InversePairs/1.jpg -------------------------------------------------------------------------------- /TranslateNum/1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/CodingInterviews/HEAD/TranslateNum/1.jpg -------------------------------------------------------------------------------- /Sort/img/sort_summary.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/CodingInterviews/HEAD/Sort/img/sort_summary.jpg -------------------------------------------------------------------------------- /CopyComplexList/Images/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/CodingInterviews/HEAD/CopyComplexList/Images/1.png -------------------------------------------------------------------------------- /CopyComplexList/Images/2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/CodingInterviews/HEAD/CopyComplexList/Images/2.png -------------------------------------------------------------------------------- /CopyComplexList/Images/3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/CodingInterviews/HEAD/CopyComplexList/Images/3.png -------------------------------------------------------------------------------- /CopyComplexList/Images/4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/CodingInterviews/HEAD/CopyComplexList/Images/4.png -------------------------------------------------------------------------------- /CopyComplexList/Images/5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/CodingInterviews/HEAD/CopyComplexList/Images/5.png -------------------------------------------------------------------------------- /KthNodeFromEnd/Images/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/CodingInterviews/HEAD/KthNodeFromEnd/Images/1.png -------------------------------------------------------------------------------- /KthNodeFromEnd/Images/2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/CodingInterviews/HEAD/KthNodeFromEnd/Images/2.jpg -------------------------------------------------------------------------------- /ReplaceSpaces/Images/1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/CodingInterviews/HEAD/ReplaceSpaces/Images/1.jpg -------------------------------------------------------------------------------- /ReplaceSpaces/Images/2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/CodingInterviews/HEAD/ReplaceSpaces/Images/2.jpg -------------------------------------------------------------------------------- /ReplaceSpaces/Images/3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/CodingInterviews/HEAD/ReplaceSpaces/Images/3.jpg -------------------------------------------------------------------------------- /ConstuctArray/Image/image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/CodingInterviews/HEAD/ConstuctArray/Image/image.png -------------------------------------------------------------------------------- /DeleteNodeInList/Images/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/CodingInterviews/HEAD/DeleteNodeInList/Images/1.png -------------------------------------------------------------------------------- /StackPushPopOrder/Images/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/CodingInterviews/HEAD/StackPushPopOrder/Images/1.png -------------------------------------------------------------------------------- /StackPushPopOrder/Images/2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/CodingInterviews/HEAD/StackPushPopOrder/Images/2.png -------------------------------------------------------------------------------- /ConstructBinaryTree/Images/1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/CodingInterviews/HEAD/ConstructBinaryTree/Images/1.jpg -------------------------------------------------------------------------------- /MirrorOfBinaryTree/Images/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/CodingInterviews/HEAD/MirrorOfBinaryTree/Images/1.png -------------------------------------------------------------------------------- /KLeastNumbers/Images/Partition.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/CodingInterviews/HEAD/KLeastNumbers/Images/Partition.png -------------------------------------------------------------------------------- /SortArrayForMinNumber/Images/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/CodingInterviews/HEAD/SortArrayForMinNumber/Images/1.png -------------------------------------------------------------------------------- /SortArrayForMinNumber/Images/2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/CodingInterviews/HEAD/SortArrayForMinNumber/Images/2.png -------------------------------------------------------------------------------- /SortArrayForMinNumber/Images/3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/CodingInterviews/HEAD/SortArrayForMinNumber/Images/3.png -------------------------------------------------------------------------------- /RegularExpressionsMatching/Image/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/CodingInterviews/HEAD/RegularExpressionsMatching/Image/1.png -------------------------------------------------------------------------------- /RegularExpressionsMatching/Image/复杂度分析.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/CodingInterviews/HEAD/RegularExpressionsMatching/Image/复杂度分析.png -------------------------------------------------------------------------------- /Accumulate/Accumulate.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sumNums(self, n: int) -> int: 3 | res = n 4 | if res: 5 | res+= self.sumNums(n-1) 6 | return res 7 | -------------------------------------------------------------------------------- /Accumulate/Accumulate.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int sumNums(int n) { 4 | int res = n; 5 | res && (res += sumNums(n-1)); 6 | return res; 7 | } 8 | }; 9 | -------------------------------------------------------------------------------- /NumberOf1InBinary/NumberOf1InBinary.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hammingWeight(self, n: int) -> int: 3 | count= 0 4 | while n: 5 | count+=1 6 | n&=n-1 7 | return count 8 | -------------------------------------------------------------------------------- /JumpFloorII/JumpFloorII.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class Solution: 3 | def jumpFloorII(self, n): 4 | # write code here 5 | if n==0: 6 | return 0 7 | res = 1 8 | for i in range(1,n): 9 | res *= 2 10 | return res 11 | -------------------------------------------------------------------------------- /NumberOf1InBinary/NumberOf1InBinary.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int NumberOf1(int n) { 4 | int count = 0; 5 | while(n) 6 | { 7 | count++; 8 | n = (n-1)&n; 9 | } 10 | return count; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /JumpFloorII/JumpFloorII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int jumpFloorII(int n) { 4 | if (n==0) 5 | return 0; 6 | int res = 1; 7 | for (int i=1;i int: 3 | res = 0 4 | for i in range(0,32): 5 | count = 0 6 | for num in nums: 7 | if (num&(1< int: 3 | s = str(num) 4 | n = len(s) 5 | dp = [1 for _ in range(n+1)] 6 | for i in range(2,n+1): 7 | if s[i-2] == '0' or (s[i-2:i]>"25"): 8 | dp[i] = dp[i-1] 9 | else: 10 | dp[i] = dp[i-1] + dp[i-2] 11 | return dp[n] 12 | -------------------------------------------------------------------------------- /Power/Power.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class Solution: 3 | def Power(self, x, n): 4 | # write code here 5 | if x==0.0 and n<0: 6 | return 0.0 7 | res = 1.0 8 | if n <0: 9 | x=1.0/x 10 | n=-n 11 | while n: 12 | if n&1==1: 13 | res*=x 14 | x*=x 15 | n=n>>1 16 | return res 17 | -------------------------------------------------------------------------------- /AddTwoNumbers/AddTwoNumbers.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class Solution: 3 | def Add(self, num1, num2): 4 | # write code here 5 | MAX = 0x7fffffff 6 | mask = 0xffffffff 7 | while num2 != 0: 8 | num1, num2 = (num1 ^ num2), ((num1 & num2) << 1) 9 | num1 = num1 & mask 10 | num2 = num2 & mask 11 | return num1 if num1 <= MAX else ~(num1 ^ mask) 12 | -------------------------------------------------------------------------------- /Fibonacci/Fibonacci.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int Fibonacci(int n) { 4 | if (n<2) 5 | return n; 6 | int fn_one = 1; 7 | int fn_two = 0; 8 | int fn = 0; 9 | for (int i=2;i<=n;i++) 10 | { 11 | fn = fn_one + fn_two; 12 | fn_two = fn_one; 13 | fn_one = fn; 14 | } 15 | return fn; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /LastNumberInCircle/LastNumberInCircle.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class Solution: 3 | def LastRemaining_Solution(self, n, m): 4 | # write code h; 5 | res = -1 6 | if n<=0 or m<0: 7 | return res 8 | nums =range(n)## 0-n-1数组 9 | start=0 10 | while len(nums)>1: 11 | end = (start+m-1)%(len(nums)) 12 | del nums[end] 13 | start = end 14 | return nums[0] 15 | -------------------------------------------------------------------------------- /FirstNotRepeatingChar/FirstNotRepeatingChar.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class Solution: 3 | def FirstNotRepeatingChar(self, s): 4 | # write code here 5 | import collections 6 | n = len(s) 7 | res = -1 8 | if n==0: 9 | return res 10 | count = collections.Counter(s) 11 | for index,ch in enumerate(s): 12 | if count[ch]==1: 13 | return index 14 | return res 15 | -------------------------------------------------------------------------------- /NumberAppearingOnce/NumberAppearingOnce.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def singleNumbers(self, nums: List[int]) -> List[int]: 3 | number = 0 4 | res = [0,0] 5 | for num in nums: 6 | number ^= num 7 | pos = 1 8 | while (number&pos) == 0: 9 | pos <<=1 10 | for num in nums: 11 | if (num&pos) == pos: 12 | res[0] ^= num 13 | else: 14 | res[1] ^= num 15 | return res 16 | -------------------------------------------------------------------------------- /NumbersAppearOnce/NumbersAppearOnce.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int singleNumber(vector& nums) { 4 | int ans = 0; 5 | for (int i = 0; i < 32; i++) 6 | { 7 | int count = 0; 8 | for (auto n : nums) 9 | { 10 | if ((1 << i ) & n) 11 | count++; 12 | } 13 | if (count % 3) 14 | ans += (1 << i); 15 | } 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Power/Power.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double Power(double x, int n) { 4 | long a = n; 5 | if (x==0 && n<0) 6 | return 0.0; 7 | double res = 1.0; 8 | // 负数的右移操作不是除2,所以要先转换成非负 9 | if (n<0) 10 | { 11 | x = 1/x; 12 | a=-a; 13 | } 14 | while(a!=0) 15 | { 16 | if (a&1==1) 17 | res *= x; 18 | x*=x; 19 | a = a>>1; 20 | } 21 | return res; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /FirstNotRepeatingChar/FirstNotRepeatingChar.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int FirstNotRepeatingChar(string s) { 4 | int res = -1; 5 | int n = s.size(); 6 | if (n==0) return res; 7 | unordered_map m; 8 | for (int i=0;i0 and s[-1]==popV[index]: 14 | s.pop() 15 | index+=1 16 | if len(s)==0: 17 | return True 18 | return False 19 | -------------------------------------------------------------------------------- /StackPushPopOrder/StackPushPopOrder.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool IsPopOrder(vector pushV,vector popV) { 4 | int n = pushV.size(); 5 | int m = popV.size(); 6 | if (n!=m) return false; 7 | stack s; 8 | int index = 0; 9 | for (int i=0;i m; 6 | string s; 7 | void Insert(char ch) 8 | { 9 | s += ch; 10 | m[ch]++; 11 | } 12 | //return the first appearence once char in current stringstream 13 | char FirstAppearingOnce() 14 | { 15 | char res = '#'; 16 | int n = s.size(); 17 | for (int i=0;i nums; 9 | for (int i=0;i<=n;i++) 10 | { 11 | nums.push_back(i); 12 | } 13 | int start =0; 14 | while(nums.size()>1) 15 | { 16 | int end = (start+m-1)%(nums.size()); 17 | nums.erase(nums.begin()+end); 18 | start = end; 19 | } 20 | res = nums[0]; 21 | return res; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /QueueWithTwoStacks/QueueWithTwoStacks.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | void push(int node) { 5 | stack1.push(node); 6 | } 7 | 8 | int pop() { 9 | int temp = 0; 10 | if (stack2.empty()) 11 | { 12 | while(!stack1.empty()) 13 | { 14 | temp = stack1.top(); 15 | stack1.pop(); 16 | stack2.push(temp); 17 | } 18 | } 19 | int res = stack2.top(); 20 | stack2.pop(); 21 | return res; 22 | } 23 | 24 | private: 25 | stack stack1; 26 | stack stack2; 27 | }; 28 | -------------------------------------------------------------------------------- /ConvertBinarySearchTree/ConvertBinarySearchTree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def Convert(self, root): 3 | # write code here 4 | if root is None: 5 | return None 6 | pre = None 7 | self.helper(root, pre) 8 | res = root 9 | while res.left: 10 | res = res.left 11 | return res 12 | def helper(self, cur, pre): 13 | if cur is None: 14 | return pre 15 | pre = self.helper(cur.left, pre) 16 | cur.left = pre 17 | if pre: 18 | pre.right = cur 19 | pre = cur 20 | return self.helper(cur.right, pre) 21 | -------------------------------------------------------------------------------- /TranslateNum/TranslateNum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int translateNum(int num) { 4 | string s = to_string(num); 5 | int n = s.size(); 6 | vector dp(n+1, 0); // dp[i]表示前i个数字的翻译种数,注意dp[i]对应的数字是s[i-1] 7 | dp[0] = 1; 8 | dp[1] = 1; 9 | for (int i =2;i"25") 12 | { 13 | dp[i] = dp[i-1]; 14 | } 15 | else 16 | { 17 | dp[i] = dp[i-1] + dp[i-2]; 18 | } 19 | } 20 | return dp[n]; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /NextNodeInBinaryTrees/NextNodeInBinaryTrees.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def GetNext(self, Node): 3 | # write code here 4 | if Node is None: 5 | return None 6 | res = None 7 | if Node.right: 8 | pRight = Node.right 9 | while pRight.left: 10 | pRight = pRight.left 11 | res = pRight 12 | elif Node.next: 13 | pCur = Node 14 | pNext = Node.next 15 | while pNext and pNext.right == pCur: 16 | pCur = pNext 17 | pNext = pNext.next 18 | res = pNext 19 | return res 20 | -------------------------------------------------------------------------------- /CMyString/CMyString.cpp: -------------------------------------------------------------------------------- 1 | //方法一: 2 | 3 | CMyString& CMyString::operator = (const CMyString &str) 4 | { 5 | if (this == &str) 6 | return *this; 7 | delete [] m_pData; 8 | m_pData = nullptr; 9 | 10 | m_pData = new char[strlen(str.m_pData)+1]; 11 | strcpy(m_pData,str.m_pData); 12 | 13 | return *this; 14 | } 15 | 16 | 17 | // 方法二:考虑异常安全性的解法: 18 | CMyString& CMyString::operator = (const CMyString &str) 19 | { 20 | if(this!=str) 21 | { 22 | CMyString strTemp(str); 23 | 24 | char* pTemp = strTemp.m_pData; 25 | strTemp.m_pData = m_pData; 26 | m_pData = pTemp; 27 | } 28 | return *this; 29 | } 30 | -------------------------------------------------------------------------------- /ContinousCards/ContinousCards.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class Solution: 3 | def IsContinuous(self, nums): 4 | # write code here 5 | n = len(nums) 6 | if nums is None or n!=5: 7 | return False 8 | nums = sorted(nums) 9 | numZero = 0 10 | gap = 0 11 | for num in nums: 12 | if num ==0: 13 | numZero+=1 14 | for i in range(numZero,n-1): 15 | j=i+1 16 | if nums[j]==nums[i]: 17 | return False 18 | gap += nums[j]-nums[i]-1 19 | if gap > numZero: 20 | return False 21 | return True 22 | -------------------------------------------------------------------------------- /FindNthDigit/FindNthDigit.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findNthDigit(self, n: int) -> int: 3 | if n<0: 4 | return -1 5 | if n<10: 6 | return n 7 | digits = 1 8 | numbers = 9 9 | while n>digits*numbers: 10 | n-=digits*numbers 11 | digits+=1 12 | numbers*=10 13 | n-=1 14 | a = n//digits 15 | b = n%digits 16 | num = int(pow(10,digits-1) + a) 17 | idx = digits-b 18 | for i in range(1, idx): 19 | num//=10 20 | return num%10 21 | # s = str(num) 22 | # res = int(s[b]) 23 | # return res 24 | -------------------------------------------------------------------------------- /CMyString/main.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Created by Bryce on 2021/3/29. 3 | // 4 | 5 | #include "CMyString.h" 6 | #include 7 | 8 | using namespace std; 9 | 10 | int main() 11 | { 12 | char *temp = "Hello World"; 13 | CMyString myStr(temp); 14 | 15 | cout << "myStr: " << myStr.getData() << endl; 16 | 17 | CMyString test = myStr; 18 | 19 | cout << "test: " << test.getData() << endl; 20 | 21 | char *temp2 = "show the difference."; 22 | CMyString myStr2(temp2); 23 | cout << "myStr2: " << myStr2.getData() << endl; 24 | 25 | myStr2 = test; 26 | cout << "myStr2 after operator \"=\": " << myStr2.getData() << endl; 27 | 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /MirrorOfBinaryTree/MirrorOfBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | struct TreeNode { 3 | int val; 4 | struct TreeNode *left; 5 | struct TreeNode *right; 6 | TreeNode(int x) : 7 | val(x), left(NULL), right(NULL) { 8 | } 9 | };*/ 10 | class Solution { 11 | public: 12 | void Mirror(TreeNode *root) { 13 | if (root ==NULL) 14 | return; 15 | //交换根节点的左右结点 16 | TreeNode* temp = root->left; 17 | root->left = root->right; 18 | root->right =temp; 19 | 20 | //递归左子树 21 | if (root->left) 22 | Mirror(root->left); 23 | 24 | //递归右子树 25 | if (root->right) 26 | Mirror(root->right); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /ContinousCards/ContinousCards.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool IsContinuous( vector nums ) { 4 | int n = nums.size(); 5 | if (nums.empty()|| n!=5) 6 | return false; 7 | sort(nums.begin(),nums.end()); 8 | int numZero = 0; 9 | int gap = 0; 10 | for (int i=0;i stack1; 29 | stack stack2; 30 | }; 31 | -------------------------------------------------------------------------------- /DuplicationInArray/DuplicationInArray.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class Solution: 3 | # 这里要特别注意~找到任意重复的一个值并赋值到duplication[0] 4 | # 函数返回True/False 5 | def duplicate(self, nums): 6 | duplication=[] 7 | n = len(nums) 8 | for i in range (n): 9 | while nums[i]!=i: 10 | if nums[i]==nums[nums[i]]: 11 | duplication.append(nums[i]) 12 | return True 13 | temp = nums[i] 14 | nums[i] = nums[nums[i]] 15 | nums[temp] = temp 16 | return False 17 | 18 | if __name__ == '__main__': 19 | nums=[2,3,1,0,2,5,3] 20 | res = Solution().duplicate(nums) 21 | print(res) 22 | -------------------------------------------------------------------------------- /EntryNodeInListLoop/EntryNodeInListLoop.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | class Solution: 7 | def EntryNodeOfLoop(self, head): 8 | # write code here 9 | if head==None or head.next==None: 10 | return None 11 | p = head 12 | q = head 13 | while q and q.next: 14 | p = p.next 15 | q = q.next.next 16 | if p == q: 17 | p = head 18 | while p!=q: 19 | p = p.next 20 | q = q.next 21 | if p==q: 22 | return p 23 | return None 24 | -------------------------------------------------------------------------------- /NumberAppearingOnce/NumberAppearingOnce.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector singleNumber(vector& nums) { 4 | vector res (2,0); 5 | int number = 0; 6 | int n = nums.size(); 7 | for (int i=0;i int: 3 | res = 0 4 | n = len(nums) 5 | for i in range(n): 6 | if nums[i] == i: 7 | res = nums[i] 8 | break 9 | return res 10 | ### Python Solution 2: 11 | class Solution: 12 | def IntegerIdenticalToIndex(self, nums: List[int]) -> int: 13 | n = len(nums) 14 | start = 0 15 | end = n-1 16 | while end>=start: 17 | mid = start + (end-start)//2 18 | if nums[mid] == mid: 19 | return mid 20 | if nums[mid] > mid: 21 | end = mid - 1 22 | else: 23 | start = mid + 1 24 | if start == n: 25 | return n 26 | return -1 27 | -------------------------------------------------------------------------------- /MinInStack/MinInStack.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class Solution: 3 | def __init__(self): 4 | self.stack1 = [] 5 | self.stack2 = [] 6 | def push(self, node): 7 | # write code here 8 | self.stack1.append(node) 9 | if len(self.stack2)==0 or node < self.stack2[-1]: 10 | self.stack2.append(node) 11 | else: 12 | temp = self.stack2[-1] 13 | self.stack2.append(temp) 14 | def pop(self): 15 | # write code here 16 | self.stack1.pop() 17 | self.stack2.pop() 18 | def top(self): 19 | # write code here 20 | return self.stack1[-1] 21 | def min(self): 22 | # write code here 23 | return self.stack2[-1] 24 | -------------------------------------------------------------------------------- /MaxQueue/MaxQueue.py: -------------------------------------------------------------------------------- 1 | class MaxQueue: 2 | 3 | def __init__(self): 4 | self.queue=[] 5 | self.max_queue=[] 6 | 7 | def max_value(self) -> int: 8 | if not self.queue: 9 | return -1 10 | return self.max_queue[0] 11 | 12 | 13 | def push_back(self, value: int) -> None: 14 | self.queue.append(value) 15 | while self.max_queue and value > self.max_queue[-1]: 16 | self.max_queue.pop(-1) 17 | self.max_queue.append(value) 18 | 19 | def pop_front(self) -> int: 20 | if not self.queue: 21 | return -1 22 | if self.queue[0]==self.max_queue[0]: 23 | self.max_queue.pop(0) 24 | return self.queue.pop(0) 25 | -------------------------------------------------------------------------------- /DuplicationInArray/DuplicationInArrayNoEdit.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class Solution: 3 | # 这里要特别注意~找到任意重复的一个值并赋值到duplication[0] 4 | # 函数返回True/False 5 | def duplicate(self, nums): 6 | n = len(nums)-1 7 | start = 1 8 | end = n 9 | while start < end: 10 | m = 0 11 | mid = start + (end-start)//2 12 | for i in range(n+1): 13 | if nums[i] >= start and nums[i] <= mid: 14 | m += 1 15 | if m > mid-start+1: 16 | end = mid 17 | else: 18 | start = mid+1 19 | return start 20 | 21 | 22 | if __name__ == '_ main__': 23 | nums = [2, 3, 5, 4, 3, 2, 6, 7] 24 | res = Solution().duplicate(nums) 25 | print(res) 26 | -------------------------------------------------------------------------------- /RobotMove/RobotMove.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def movingCount(self, m: int, n: int, k: int) -> int: 3 | if (m<=0 or n<=0 or k<0): 4 | return 0 5 | visited = [[0 for _ in range(n)]for _ in range(m)] 6 | res = self.dfs(m,n,0,0,k,visited) 7 | return res 8 | def dfs(self, m, n, i, j, k, visited): 9 | if i<0 or i>=m or j<0 or j>=n or self.bitSum(i) + self.bitSum(j) >k or visited[i][j]==1: 10 | return 0 11 | visited[i][j]=1 12 | return self.dfs(m,n,i-1,j,k,visited) + self.dfs(m,n,i+1,j,k,visited) + self.dfs(m,n,i,j+1,k,visited) + self.dfs(m,n,i,j-1,k,visited) + 1 13 | def bitSum(self, num): 14 | s = 0 15 | while num: 16 | s+=num%10 17 | num = num//10 18 | return s 19 | -------------------------------------------------------------------------------- /DeleteNodeInList/DeleteNodeInList.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | class Solution: 7 | def DeleteNode(self, head,tobedeleted): 8 | # write code here 9 | if head==None or tobedeleted == None: 10 | return 11 | ### 非尾节点 12 | if tobedeleted.next!= None: 13 | tobedeleted.val = tobedeleted.next.val 14 | tobedeleted.next = tobedeleted.next.next 15 | ## 链表只有一个节点,既是头结点,又是尾节点 16 | if head == tobedeleted: 17 | tobedeleted = None 18 | head = None 19 | p = head 20 | while p.next: 21 | if p.next!=None: 22 | p=p.next 23 | p.next = None 24 | -------------------------------------------------------------------------------- /SquenceOfBST/SquenceOfBST.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class Solution: 3 | def VerifySquenceOfBST(self, sequence): 4 | # write code here 5 | if sequence is None or len(sequence) == 0: 6 | return False 7 | root = sequence[-1] 8 | n = len(sequence) 9 | i=0 10 | for i in range(n): 11 | if sequence[i] > root: 12 | break 13 | for j in range(i,n): 14 | if sequence[j] < root: 15 | return False 16 | left = True 17 | if i > 0: 18 | left = self.VerifySquenceOfBST(sequence[:i]) # a[ : n]表示从第0个元素到第n个元素(不包括n) 19 | right = True 20 | if i < n - 1: 21 | right = self.VerifySquenceOfBST(sequence[i:-1]) 22 | return left and right 23 | -------------------------------------------------------------------------------- /PathInTree/PathInTree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # 返回二维列表,内部每个列表表示找到的路径 3 | def __init__(self): 4 | self.res = [] 5 | self.path = [] 6 | def FindPath(self, root, expectNumber): 7 | # write code here 8 | if root is None: 9 | return self.res 10 | self.dfs(root, self.path, expectNumber) 11 | return self.res 12 | def dfs(self, root, path, expectNumber): 13 | if root is None: 14 | return 15 | self.path.append(root.val) 16 | if expectNumber == root.val and (root.left is None and root.right is None): 17 | self.res.append(self.path[:]) 18 | self.dfs(root.left, self.path, expectNumber - root.val) 19 | self.dfs(root.right, self.path, expectNumber - root.val) 20 | self.path.pop() 21 | -------------------------------------------------------------------------------- /FindNthDigit/FindNthDigit.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findNthDigit(int n) { 4 | if (n<0) 5 | return -1; 6 | if (n<10) 7 | return n; 8 | int digits = 1; 9 | long number = 9; 10 | while (n>digits*number) 11 | { 12 | n-=digits*number; 13 | digits++; 14 | number*=10; 15 | } 16 | n-=1; // 计算时从1开始,但实际是从0开始,所以要减1 17 | int a = n / digits; 18 | int idx = n%digits; 19 | int num = int (pow(10, digits-1)) + a; 20 | int idxFromRight = digits-idx; 21 | for (int i=1;i int: 43 | res = n 44 | if res: 45 | res+= self.sumNums(n-1) 46 | return res 47 | ``` 48 | -------------------------------------------------------------------------------- /MaxQueue/MaxQueue.cpp: -------------------------------------------------------------------------------- 1 | class MaxQueue { 2 | public: 3 | queue q1; 4 | deque q2; 5 | MaxQueue() { 6 | 7 | } 8 | 9 | int max_value() { 10 | int res = -1; 11 | if (!q2.empty()) 12 | { 13 | res = q2.front(); 14 | } 15 | return res; 16 | } 17 | 18 | void push_back(int value) { 19 | q1.push(value); 20 | while (!q2.empty() && q2.back() 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | class Solution { 7 | public: 8 | string PrintMinNumber(vector nums) 9 | { 10 | string res; 11 | int n = nums.size(); 12 | sort(nums.begin(),nums.end(),compare); 13 | for (int i=0;i nums = {3,1,2}; 30 | string res = Solution().PrintMinNumber(nums); 31 | cout << res << endl; 32 | system ("pause"); 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /ConvertBinarySearchTree/ConvertBinarySearchTree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* Convert(TreeNode* root) 4 | { 5 | if (root == NULL) 6 | return NULL; 7 | // 定义一个pre指针 8 | TreeNode* pre = NULL; 9 | helper(root, pre); 10 | TreeNode* res = root; 11 | // 寻找到头结点 12 | while (res->left) 13 | { 14 | res = res->left; 15 | } 16 | return res; 17 | } 18 | void helper(TreeNode* cur, TreeNode* &pre) // 中序遍历 19 | { 20 | if (cur == NULL) 21 | return; 22 | // 先递归遍历左子树 23 | helper(cur->left, pre); 24 | // 修改为双向链表 25 | //左指针 26 | cur->left = pre; 27 | //右指针 28 | if(pre != NULL) 29 | { 30 | pre->right = cur; 31 | } 32 | //更新双向链表尾结点 33 | pre = cur; 34 | // 再递归遍历右子树 35 | helper(cur->right, pre); 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /TreeDepth/TreeDepth.py: -------------------------------------------------------------------------------- 1 | ## Solution 1: 2 | class Solution: 3 | def TreeDepth(self, root): 4 | # write code here 5 | if root is None: 6 | return 0 7 | left = self.TreeDepth(root.left) 8 | right = self.TreeDepth(root.right) 9 | return max(left, right)+1 10 | ## Solution 2: 11 | class Solution: 12 | def TreeDepth(self, root): 13 | # write code here 14 | depth = 0 15 | if root is None: 16 | return depth 17 | q = [] 18 | q.append(root) 19 | while q: 20 | # count 是每一层的节点数 21 | count = len(q) 22 | while count > 0: 23 | node = q.pop(0) 24 | if node.left: 25 | q.append(node.left) 26 | if node.right: 27 | q.append(node.right) 28 | count-=1 29 | # 遍历完一层后,深度+1 30 | depth+=1 31 | return depth 32 | -------------------------------------------------------------------------------- /DeleteNodeInList/DeleteNodeInList.cpp: -------------------------------------------------------------------------------- 1 | void DeleteNode(ListNode* head,ListNode* ToBeDeleted) 2 | { 3 | if (head == NULL ||ToBeDeleted == NULL) 4 | return; 5 | // 删除节点不是尾节点 6 | if (ToBeDeleted->next != NULL) 7 | { 8 | ListNode* p = ToBeDeleted->next; 9 | ToBeDeleted->val = p->val; 10 | ToBeDeleted->next = p->next; 11 | delete p; 12 | p = NULL; 13 | } 14 | // 链表只有一个节点,既是头结点,又是尾节点 15 | if (head == ToBeDeleted) 16 | { 17 | delete ToBeDeleted; 18 | ToBeDeleted = NULL; 19 | head = NULL; 20 | } 21 | // 链表中有多个节点,删除尾节点 22 | else 23 | { 24 | ListNode* p = head; 25 | while(p->next) 26 | { 27 | if (p->next != ToBeDeleted) 28 | { 29 | p = p->next; 30 | } 31 | p->next = NULL; 32 | delete ToBeDeleted; 33 | ToBeDeleted = NULL; 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /CuttingRope/CuttingRope.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def cuttingRope(self, n: int) -> int: 3 | dp = [0 for _ in range(n+1)] 4 | dp[2] = 1 5 | for i in range(3,n+1): 6 | for j in range(1, i-1): 7 | dp[i] = max(dp[i], j*(i-j), j*dp[i-j]) 8 | return dp[n] 9 | ## Solution 2: 10 | class Solution: 11 | def cuttingRope(self, n: int) -> int: 12 | dp = [0, 1, 1] 13 | 14 | for i in range(3, n + 1): 15 | dp[i % 3] = max(max(dp[(i - 1) % 3], i - 1), 16 | 2 * max(dp[(i - 2) % 3], i - 2), 17 | 3 * max(dp[(i - 3) % 3], i - 3)) 18 | return dp[n % 3] 19 | ## Solution 3: 20 | class Solution: 21 | def cuttingRope(self, n: int) -> int: 22 | if n <= 3: return n - 1 23 | a, b = n // 3, n % 3 24 | if b == 0: return int(math.pow(3, a)) 25 | if b == 1: return int(math.pow(3, a - 1) * 4) 26 | return int(math.pow(3, a) * 2) 27 | -------------------------------------------------------------------------------- /PathInTree/PathInTree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> res; 4 | vector > FindPath(TreeNode* root,int expectNumber) { 5 | if (root == NULL) 6 | return res; 7 | vector path; 8 | dfs(root,path,expectNumber); 9 | return res; 10 | } 11 | void dfs(TreeNode* root, vector& path, int expectNumber) 12 | { 13 | if (root == NULL) 14 | return; 15 | path.push_back(root->val); 16 | // 如果是叶节点,并且路径上的节点值的和为输入的值,就像结果中添加这一path 17 | bool isLeaf = (root->left == NULL && root->right == NULL); 18 | if (expectNumber == root->val && isLeaf) 19 | { 20 | res.push_back(path); 21 | } 22 | // 不是叶节点就遍历他的子节点 23 | dfs(root->left, path, expectNumber-root->val); 24 | dfs(root->right, path, expectNumber-root->val); 25 | // 到这一步说明不满足要求,要返回父节点,需要删除路径上的当前节点 26 | path.pop_back(); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /PrintNumbers/PrintNumbers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def __init__(self): 3 | self.res = [] 4 | def printNumbers(self, n: int) -> List[int]: 5 | self.res = [] 6 | if n<=0: 7 | return self.res 8 | numer = ['0' for _ in range(n)] 9 | self.helper(0, n, numer) 10 | return self.res; 11 | def helper(self, index, n, numer): 12 | if index == n: 13 | self.saveNumber(numer) 14 | return 15 | for i in range(10): 16 | numer[index] = str(i) 17 | self.helper(index+1, n, numer) 18 | def saveNumber(self, numer): 19 | index = 0 20 | s = "" 21 | while (index& nums) { 4 | int n = nums.size(); 5 | int res = 0; 6 | if (nums.empty()) 7 | return 0; 8 | for (int i=0;i& nums) { 24 | int res = 0; 25 | int n = nums.size(); 26 | int start = 0; 27 | int end = n-1; 28 | while(end>=start) 29 | { 30 | int mid = start + (end -start) /2; 31 | if (nums[mid]==mid) 32 | { 33 | res = mid; 34 | break; 35 | } 36 | if (nums[mid]>mid) 37 | { 38 | end = mid-1; 39 | } 40 | else 41 | { 42 | start = mid +1; 43 | } 44 | } 45 | return res; 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /EntryNodeInListLoop/EntryNodeInListLoop.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | struct ListNode { 3 | int val; 4 | struct ListNode *next; 5 | ListNode(int x) : 6 | val(x), next(NULL) { 7 | } 8 | }; 9 | */ 10 | class Solution { 11 | public: 12 | ListNode* EntryNodeOfLoop(ListNode* head) 13 | { 14 | if (head==NULL || head->next==NULL) 15 | return NULL; 16 | ListNode* p = head; 17 | ListNode* q = head; 18 | while(q && q->next) 19 | { 20 | p = p->next;//慢指针走一步 21 | q = q->next->next;//快指针走两步 22 | if (p==q) // 找到环中相遇点,如果没找到就会跳出循环,因为会指向NULL 23 | { 24 | p = head; //将两个指针设置为一个在开头,一个在相遇点 25 | // 并同时同步移动,再次相遇时就是环的入口节点 26 | while(p!=q) 27 | { 28 | p = p->next; 29 | q = q->next; 30 | } 31 | if (p==q) 32 | return p; 33 | } 34 | } 35 | return NULL; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /CopyComplexList/CopyComplexList.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # class RandomListNode: 3 | # def __init__(self, x): 4 | # self.label = x 5 | # self.next = None 6 | # self.random = None 7 | class Solution: 8 | # 返回 RandomListNode 9 | def Clone(self, head): 10 | # write code here 11 | if head==None: 12 | return None 13 | cur = head 14 | while cur: 15 | temp = RandomListNode(cur.label) 16 | temp.next = cur.next 17 | cur.next = temp 18 | cur = temp.next 19 | cur = head 20 | while cur: 21 | temp = cur.next 22 | if cur.random: 23 | temp.random = cur.random.next 24 | cur = temp.next 25 | cur = head 26 | p = head.next 27 | while cur: 28 | temp = cur.next 29 | cur.next = temp.next 30 | if temp.next: 31 | temp.next = temp.next.next 32 | cur = cur.next 33 | return p 34 | -------------------------------------------------------------------------------- /JumpFloorII/README.md: -------------------------------------------------------------------------------- 1 | # 题目: 变态跳台阶 2 | 3 | ## 题目描述: 4 | 一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。 5 | 6 | # 解题思路: 7 | 我想说,这青蛙真变态,真能跳。 8 | 9 | - 当n=1时,结果为1; 10 | - 当n=2时,结果为2; 11 | - 当n=3时,结果为4; 12 | 13 | 以此类推,我们使用数学归纳法不难发现,跳法f(n)=2^(n-1)。 14 | # 时间复杂度: 15 | O(n); 16 | # 空间复杂度 17 | O(1) 18 | 19 | # 代码 20 | 21 | [C++](./JumpFloorII.cpp) 22 | 23 | [Python](./JumpFloorII.py) 24 | 25 | # C++: 26 | ### 通项公式 27 | ```c++ 28 | class Solution { 29 | public: 30 | int jumpFloorII(int n) { 31 | if (n==0) 32 | return 0; 33 | int res = 1; 34 | for (int i=1;iright != NULL) 10 | { 11 | TreeLinkNode* pRight = Node->right; 12 | while(pRight->left!=NULL) 13 | { 14 | pRight = pRight->left; 15 | } 16 | res = pRight; 17 | } 18 | // 当前结点无右子树,则需要找到一个是它父结点的左子树结点的结点 19 | else if (Node->next!=NULL) 20 | { 21 | // 当前结点 22 | TreeLinkNode* pCur = Node; 23 | // 父节点 24 | TreeLinkNode* pNext = Node->next; 25 | while( pNext != NULL && pNext->right == pCur) 26 | { 27 | pCur = pNext; 28 | pNext = pNext->next; 29 | } 30 | res = pNext; 31 | } 32 | return res; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /DuplicationInArray/DuplicationInArrayNoEdit.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution{ 7 | public: 8 | int getDuplication(const vector nums, int n){ 9 | if ( nums.empty() || n <=0) return -1; 10 | int start = 1; 11 | int end = n -1; 12 | while(end >= start) 13 | { 14 | int k = 0; 15 | int mid = start + (end-start)/2; 16 | for (int i=0;i=start && nums[i]<=mid) 19 | { 20 | m++; 21 | } 22 | if (m > mid) 23 | { 24 | end = mid; 25 | } 26 | else 27 | { 28 | start = mid + 1; 29 | } 30 | } 31 | } 32 | return start; 33 | } 34 | }; 35 | 36 | int main() 37 | { 38 | vector nums = {2,3,5,4,3,2,6,7}; 39 | int n = nums.size()-1; 40 | cout<left); 9 | int right = TreeDepth(root->right); 10 | return max(left, right) + 1; 11 | } 12 | }; 13 | // Solution 2: 14 | class Solution { 15 | public: 16 | int TreeDepth(TreeNode* root) 17 | { 18 | int depth = 0; 19 | if (root == NULL) 20 | return depth; 21 | queue q; 22 | q.push(root); 23 | while(!q.empty()) 24 | { 25 | int count = q.size(); 26 | while(count>0) 27 | { 28 | TreeNode* node = q.front(); 29 | q.pop(); 30 | if (node->left) 31 | q.push(node->left); 32 | if (node->right) 33 | q.push(node->right); 34 | count--; 35 | } 36 | depth++; 37 | } 38 | return depth; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /NumericStrings/NumericStrings.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class Solution: 3 | # s字符串 4 | def isNumeric(self, s): 5 | # write code here 6 | n = len(s) 7 | if n==0: 8 | return False 9 | sign = False 10 | decimal = False 11 | hasE = False 12 | for i in range(0,n): 13 | if s[i] == 'e' or s[i]=='E': 14 | if i == n-1: 15 | return False 16 | if hasE: 17 | return False 18 | hasE = True 19 | elif s[i]=='+' or s[i]=='-': 20 | if sign and s[i-1]!= 'e' and s[i-1] != 'E': 21 | return False 22 | if not sign and i>0 and s[i-1] != 'e' and s[i-1]!='E': 23 | return False 24 | sign = True 25 | elif s[i]=='.': 26 | if hasE or decimal: 27 | return False 28 | decimal = True 29 | elif s[i]<'0' or s[i]>'9': 30 | return False 31 | return True 32 | -------------------------------------------------------------------------------- /PrintTreesInZigzag/PrintTreesInZigzag.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def Print(self, root): 3 | # write code here 4 | res = [] 5 | if root is None: 6 | return res 7 | import collections 8 | q = collections.deque() 9 | q.append(root) 10 | zigzag = True 11 | while q: 12 | n = len(q) 13 | out = [] 14 | node = None 15 | while n>0: 16 | if zigzag: 17 | node = q.popleft() 18 | if node.left: 19 | q.append(node.left) 20 | if node.right: 21 | q.append(node.right) 22 | else: 23 | node = q.pop() 24 | if node.right: 25 | q.appendleft(node.right) 26 | if node.left: 27 | q.appendleft(node.left) 28 | out.append(node.val) 29 | n-=1 30 | res.append(out[:]) 31 | zigzag = not zigzag 32 | return res 33 | -------------------------------------------------------------------------------- /NumberOf1/NumberOf1.py: -------------------------------------------------------------------------------- 1 | # Solution 1: 2 | # -*- coding:utf-8 -*- 3 | class Solution: 4 | def NumberOf1Between1AndN_Solution(self, n): 5 | # write code here 6 | res = 0 7 | for i in range(1,n+1): 8 | res += self.NumberOf1(i) 9 | return res 10 | def NumberOf1(self,n): 11 | num = 0 12 | while n>0: 13 | if n%10==1: 14 | num+=1 15 | n/=10 16 | return num 17 | # Solution 2: 18 | # -*- coding:utf-8 -*- 19 | class Solution: 20 | def NumberOf1Between1AndN_Solution(self, n): 21 | # write code here 22 | res = 0 23 | i = 1 24 | while i<=n: 25 | a = n//i 26 | b = n%i 27 | res += (a+8)//10*i + (a%10==1)*(b+1) 28 | i*=10 29 | return res 30 | # Solution 3: 31 | # -*- coding:utf-8 -*- 32 | class Solution: 33 | def NumberOf1Between1AndN_Solution(self, n): 34 | # write code here 35 | res = 0 36 | for i in range(1,n+1): 37 | s = str(i) 38 | res+=s.count('1') 39 | return res 40 | -------------------------------------------------------------------------------- /PrintTreeFromTopToBottom/PrintTreeFromTopToBottom.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # 返回从上到下每个节点值列表,例:[1,2,3] 3 | def PrintFromTopToBottom(self, root): 4 | # write code here 5 | res = [] 6 | if root is None: 7 | return res 8 | q = [] 9 | q.append(root) 10 | while len(q)>0: 11 | temp = q.pop(0) 12 | res.append(temp.val) 13 | if temp.left: 14 | q.append(temp.left) 15 | if temp.right: 16 | q.append(temp.right) 17 | return res 18 | ## collections.deque() 19 | class Solution: 20 | # 返回从上到下每个节点值列表,例:[1,2,3] 21 | def PrintFromTopToBottom(self, root): 22 | # write code here 23 | res = [] 24 | if root is None: 25 | return res 26 | q = collections.deque() 27 | q.append(root) 28 | while q: 29 | node = q.popleft() 30 | res.append(node.val) 31 | if node.left: 32 | q.append(node.left) 33 | if node.right: 34 | q.append(node.right) 35 | return res 36 | -------------------------------------------------------------------------------- /PrintMatrix/PrintMatrix.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class Solution: 3 | def printMatrix(self, matrix): 4 | res = [] 5 | m = len(matrix) 6 | if m==0: 7 | return res 8 | n = len(matrix[0]) 9 | u = 0 10 | d = m-1 11 | l = 0 12 | r = n-1 13 | while (true): 14 | for i in range(l,r+1): 15 | res.append(matrix[u][i]) 16 | u+=1 17 | if u>d: 18 | break 19 | for i in range(u,d+1): 20 | res.append(matrix[i][r]) 21 | r-=1 22 | if rr: 33 | break 34 | return res 35 | 36 | 37 | if __name__ == '_ main__': 38 | nums = [[1,2,3,4],[5,6,7,8,[9,10,11,12],[13,14,15,16]] 39 | res = Solution().printMatrix(nums) 40 | print(res) 41 | -------------------------------------------------------------------------------- /CuttingRope/CuttingRope.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int cuttingRope(int n) { 4 | vector dp (n+1,0); // # dp[0] dp[1]其实没用 5 | dp[2] = 1; 6 | for (int i=3;i<=n;i++) 7 | { 8 | for(int j=1;j<=i-1;j++) 9 | { 10 | dp[i] = max(dp[i], max(j*(i-j), j*dp[i-j])); 11 | } 12 | } 13 | return dp[n]; 14 | } 15 | }; 16 | 17 | // Solution 2: 18 | class Solution { 19 | public: 20 | int cuttingRope(int n) { 21 | vector dp(3,1); 22 | dp[0] = 0; 23 | for (int i=3;i<=n;i++) 24 | { 25 | dp[i % 3] = max((max(dp[(i-1)%3],i-1)), 26 | max((2*max(dp[(i-2)%3], i-2)), (3*max(dp[(i-3)%3] 27 | i-3)))); 28 | } 29 | return dp[n%3]; 30 | } 31 | }; 32 | 33 | // Solution 3: 34 | class Solution { 35 | public: 36 | int cuttingRope(int n) { 37 | if (n<=3) 38 | return n-1; 39 | int a = n/3; 40 | int b = n%3; 41 | if (b==0) 42 | return pow(3,a); 43 | if (b==1) 44 | return pow(3,a-1)*4; 45 | return pow(3,a)*2; 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /ConstuctArray/ConstuctArray.cpp: -------------------------------------------------------------------------------- 1 | // C++ Solution 1: 2 | class Solution { 3 | public: 4 | vector multiply(const vector& A) { 5 | if (A.empty()) 6 | return {}; 7 | int n = A.size(); 8 | vector B (n,0); 9 | for (int i =0;i multiply(const vector& A) { 28 | if (A.empty()) 29 | return {}; 30 | int n = A.size(); 31 | vector B (n,0); 32 | //计算下三角连乘 33 | B[0]=1; 34 | for (int i=1;i=0;i--) 41 | { 42 | temp *= A[i+1]; 43 | B[i] *= temp; 44 | } 45 | return B; 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /MinNumberInRotatedArray/MinNumberInRotatedArray.py: -------------------------------------------------------------------------------- 1 | ## Python Solution 1: 2 | class Solution: 3 | def findMin(self, nums: List[int]) -> int: 4 | n = len(nums) 5 | if n==0: 6 | return 0 7 | res = nums[0] 8 | for i in range (n): 9 | if res >nums[i]: 10 | res = nums[i] 11 | return res 12 | ## Python Solution 2: 13 | class Solution: 14 | def findMin(self, nums: List[int]) -> int: 15 | n = len(nums) 16 | if n==0: 17 | return 0 18 | res = nums[0] 19 | start = 0 20 | end = n-1 21 | while end>=start: 22 | mid = start+(end-start)//2 23 | if nums[mid]>=res: 24 | start=mid+1 25 | if nums[mid] int: 32 | n = len(nums) 33 | if n==0: 34 | return 0 35 | res = nums[0] 36 | for i in range (n): 37 | if res >nums[i]: 38 | res = nums[i] 39 | return res 40 | -------------------------------------------------------------------------------- /Nge/README.md: -------------------------------------------------------------------------------- 1 | ## 题目描述 2 | 3 | 把n个骰子扔在地上,所有骰子朝上一面的点数之和为s。输入n,打印出s的所有可能的值出现的概率。 4 | 5 | 你需要用一个浮点数数组返回答案,其中第 i 个元素代表这 n 个骰子所能掷出的点数集合中第 i 小的那个的概率。 6 | 7 | 8 | dp动态规划 9 | 10 | 定义状态:dp[i][j]表示掷第i枚骰子获得点数为j的次数 11 | 12 | 状态转移方程: 13 | ``` 14 | for (第n枚骰子的点数 i = 1; i <= 6; i ++) { 15 | dp[n][j] += dp[n-1][j - i] 16 | } 17 | ``` 18 | 初始化状态: 19 | ``` 20 | for (int i = 1; i <= 6; i ++) { 21 | dp[1][i] = 1; 22 | } 23 | ``` 24 | ```c++ 25 | class Solution { 26 | public: 27 | vector twoSum(int n) { 28 | vector res; 29 | vector> dp(n+1, vector(6*n+1,0)); 30 | for (int i = 1; i <= 6; i++) { 31 | dp[1][i] = 1; 32 | } 33 | for (int i = 2; i <= n; i++) { 34 | for (int j = i; j <= 6 * i; j++) { 35 | for (int k = 1; k <= 6; k++) { 36 | if (j > k) { 37 | dp[i][j] += dp[i-1][j-k]; 38 | } 39 | } 40 | } 41 | } 42 | double base = pow(6, n) * 1.0; 43 | for (int i = n; i <= 6 * n; i++) { 44 | res.push_back(dp[n][i] / base); 45 | } 46 | return res; 47 | } 48 | }; 49 | ``` 50 | -------------------------------------------------------------------------------- /KthNodeFromEnd/KthNodeFromEnd.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | def FindKthToTail(self, head, k): 9 | # write code here 10 | if head==None or k<=0: 11 | return None 12 | temp = head 13 | n = 0 14 | while temp: 15 | n+=1 16 | temp = temp.next 17 | if n int: 4 | res = 0 5 | n = len(nums) 6 | nums_set = set(nums) 7 | for num in range(n+1): 8 | if num not in nums_set: 9 | return num 10 | return res 11 | ### Python Solution 2: 12 | # -*- coding:utf-8 -*- 13 | class Solution: 14 | def missingNumber(self, nums: List[int]) -> int: 15 | res = 0; 16 | n = len(nums) 17 | x = range(n+1) 18 | x = list(x) ### Python3 需要用list转换成数组 19 | res = sum(x)-sum(nums) 20 | return res 21 | 22 | 23 | # -*- coding:utf-8 -*- 24 | class Solution: 25 | def missingNumber(self, nums: List[int]) -> int: 26 | n = len(nums) 27 | res = n 28 | for i in range(n): 29 | res = res ^ nums[i] 30 | res = res ^ i 31 | return res 32 | ### Python Solution 3: 33 | # -*- coding:utf-8 -*- 34 | class Solution: 35 | def missingNumber(self, nums: List[int]) -> int: 36 | nums = sorted(nums) 37 | n = len(nums) 38 | if nums[-1] != n: 39 | return n 40 | for i in range(0,n): 41 | if i!=nums[i]: 42 | return i 43 | -------------------------------------------------------------------------------- /InversePairs/InversePairs.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reversePairs(self, nums: List[int]) -> int: 3 | if nums ==[]: 4 | return 0 5 | temp = [i for i in nums] 6 | count = 0 7 | n = len(nums) 8 | count = self.helper(nums, temp, 0, n-1) 9 | return count 10 | def helper(self, nums, temp, start, end): 11 | if start == end: 12 | temp[start] = nums[start] 13 | return 0 14 | mid = start + (end-start)//2 15 | left = self.helper(temp, nums, start, mid) 16 | right = self.helper(temp, nums, mid+1, end) 17 | 18 | i = mid 19 | j = end 20 | index = end 21 | count = 0 22 | while i>=start and j>=mid+1: 23 | if nums[i] > nums[j]: 24 | temp[index] = nums[i] 25 | index-=1 26 | i-=1 27 | count+=j-mid 28 | else: 29 | temp[index] = nums[j] 30 | index-=1 31 | j-=1 32 | while i>=start: 33 | temp[index] = nums[i] 34 | index-=1 35 | i-=1 36 | while j>=mid+1: 37 | temp[index] = nums[j] 38 | index-=1 39 | j-=1 40 | return left + right + count 41 | -------------------------------------------------------------------------------- /PrintTreeFromTopToBottom/PrintTreeFromTopToBottom.cpp: -------------------------------------------------------------------------------- 1 | // C++ Solution 1: 2 | class Solution { 3 | public: 4 | vector PrintFromTopToBottom(TreeNode* root) { 5 | vector res; 6 | if (root==NULL) 7 | return res; 8 | queue q; 9 | q.push(root); 10 | while(!q.empty()) 11 | { 12 | TreeNode* temp = q.front(); 13 | q.pop(); 14 | res.push_back(temp->val); 15 | if (temp->left) 16 | q.push(temp->left); 17 | if (temp->right) 18 | q.push(temp->right); 19 | } 20 | return res; 21 | } 22 | }; 23 | // C++ Solution 2: 24 | class Solution { 25 | public: 26 | vector PrintFromTopToBottom(TreeNode* root) { 27 | vector res; 28 | if (root==NULL) 29 | return res; 30 | deque q; 31 | q.push_back(root); 32 | while(q.size()) 33 | { 34 | TreeNode* temp = q.front(); 35 | q.pop_front(); 36 | res.push_back(temp->val); 37 | if (temp->left) 38 | q.push_back(temp->left); 39 | if (temp->right) 40 | q.push_back(temp->right); 41 | } 42 | return res; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /SquenceOfBST/SquenceOfBST.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool VerifySquenceOfBST(vector sequence) { 4 | bool res = false; 5 | if (sequence.empty()) 6 | return res; 7 | int n = sequence.size(); 8 | res = helper(sequence,0,n-1); 9 | return res; 10 | } 11 | bool helper(vector seq, int start, int end) 12 | { 13 | if (seq.empty() || start > end) 14 | { 15 | return false; 16 | } 17 | //根结点 18 | int root = seq[end]; 19 | 20 | //在二叉搜索树中左子树的结点小于根结点 21 | int i = start; 22 | for (;iroot) 25 | break; 26 | } 27 | 28 | //在二叉搜索书中右子树的结点大于根结点 29 | for (int j =i;jstart) 38 | { 39 | left = helper(seq, start, i-1); 40 | } 41 | 42 | //判断右子树是不是二叉搜索树 43 | bool right = true; 44 | if (i < end-1) 45 | { 46 | right = helper(seq, i, end-1); 47 | } 48 | return left && right; 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /PrintMatrix/PrintMatrix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | vector printMatrix(vector> matrix) { 8 | vector res; 9 | if (matrix.empty()) return res; 10 | int m = matrix.size(); 11 | int n = matrix[0].size(); 12 | int u = 0; 13 | int d = m-1; 14 | int l = 0; 15 | int r = n-1; 16 | while(true) 17 | { 18 | for (int i=l;i<=r;i++) res.push_back(matrix[u][i]);//向右移动至最右 19 | if (++u > d) break;//重新定义上边界 20 | for (int i=u;i<=d;i++) res.push_back(matrix[i][r]);//向下 21 | if (--r < l) break;//重新定义右边界 22 | for (int i=r;i>=l;i--) res.push_back(matrix[d][i]);//向左 23 | if (--d < u) break;//重新定义下边界 24 | for (int i=d;i>=u;i--) res.push_back(matrix[i][l]);//向上 25 | if (++l > r) break;//重新定义左边界 26 | } 27 | return res; 28 | } 29 | }; 30 | 31 | 32 | int main() 33 | { 34 | vector> nums = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}}; 35 | vector> res; 36 | res = Solution().printMatrix(nums); 37 | for (int i=0;i0: 15 | node = q.pop(0) 16 | out.append(node.val) 17 | if node.left: 18 | q.append(node.left) 19 | if node.right: 20 | q.append(node.right) 21 | n-=1 22 | res.append(out[:]) 23 | return res 24 | ### Python Solution 2: 25 | class Solution: 26 | # 返回二维列表[[1,2],[4,5]] 27 | def Print(self, root): 28 | # write code here 29 | res = [] 30 | if root is None: 31 | return res 32 | self.helper(root, res, 0) 33 | return res 34 | def helper(self, root, res, level): 35 | if root is None: 36 | return 37 | if len(res) == level: 38 | res.append([]) 39 | res[level].append(root.val) 40 | if root.left: 41 | self.helper(root.left,res,level+1) 42 | if root.right: 43 | self.helper(root.right, res, level+1) 44 | -------------------------------------------------------------------------------- /BalancedBinaryTree/BalancedBinaryTree.py: -------------------------------------------------------------------------------- 1 | # Solution 1: 2 | class Solution: 3 | def IsBalanced_Solution(self, root): 4 | # write code here 5 | if root is None: 6 | return True 7 | left = self.TreeDepth(root.left) 8 | right = self.TreeDepth(root.right) 9 | if left - right > 1 or left - right < -1: 10 | return False 11 | return self.IsBalanced_Solution(root.left) and self.IsBalanced_Solution(root.right) 12 | def TreeDepth(self, root): 13 | if root is None: 14 | return 0 15 | left = self.TreeDepth(root.left) 16 | right = self.TreeDepth(root.right) 17 | return max(left, right) + 1 18 | ## Solution 2: 19 | class Solution: 20 | def __init__(self): 21 | self.depth = 0 22 | def IsBalanced_Solution(self, root): 23 | # write code here 24 | if root is None: 25 | return True 26 | return self.helper(root)[0] 27 | def helper(self,root): 28 | if root is None: 29 | return True, 0 30 | leftIsBalanced, left = self.helper(root.left) 31 | if not leftIsBalanced: 32 | return False, 0 33 | rightIsBalanced, right = self.helper(root.right) 34 | if not rightIsBalanced: 35 | return False, 0 36 | return abs(left-right)<=1, max(left,right)+1 37 | -------------------------------------------------------------------------------- /RectCover/README.md: -------------------------------------------------------------------------------- 1 | # 题目: 矩形覆盖 2 | 3 | ## 题目描述: 4 | 我们可以用2\*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2\*1的小矩形无重叠地覆盖一个2\*n的大矩形,总共有多少种方法? 5 | 6 | 比如n=3时,2\*3的矩形块有3种覆盖方法: 7 | 8 | ![](https://uploadfiles.nowcoder.com/images/20200218/6384065_1581999858239_64E40A35BE277D7E7C87D4DCF588BE84) 9 | 10 | # 解题思路: 11 | 实质还是斐波那契数列 12 | 13 | 使用动态规划,避免用递归,只用前两个数计算节省空间。 14 | # 时间复杂度: 15 | O(n); 16 | # 空间复杂度 17 | O(1) 18 | 19 | # 代码 20 | 21 | [C++](./RectCover.cpp) 22 | 23 | [Python](./RectCover.py) 24 | 25 | # C++: 26 | ### 动态规划 27 | ```c++ 28 | class Solution { 29 | public: 30 | int rectCover(int n) { 31 | if (n<=2) 32 | return n; 33 | int fn_one = 2; 34 | int fn_two = 1; 35 | int fn = 0; 36 | for (int i=3;i<=n;i++) 37 | { 38 | fn = fn_one + fn_two; 39 | fn_two = fn_one; 40 | fn_one = fn; 41 | } 42 | return fn; 43 | } 44 | }; 45 | ``` 46 | # Python: 47 | ### 动态规划 48 | ```python 49 | # -*- coding:utf-8 -*- 50 | class Solution: 51 | def rectCover(self, n): 52 | # write code here 53 | if n<=2: 54 | return n 55 | fn_one = 2 56 | fn_two = 1 57 | fn = 0 58 | for i in range(3,n+1): 59 | fn = fn_one + fn_two 60 | fn_two = fn_one 61 | fn_one = fn 62 | return fn 63 | ``` 64 | -------------------------------------------------------------------------------- /BalancedBinaryTree/BalancedBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool IsBalanced_Solution(TreeNode* root) { 4 | if (root == NULL) 5 | return true; 6 | int left = TreeDepth(root->left); 7 | int right = TreeDepth(root->right); 8 | if (left-right > 1 || left-right<-1) 9 | return false; 10 | return IsBalanced_Solution(root->left) && IsBalanced_Solution(root->right); 11 | } 12 | int TreeDepth(TreeNode* root) 13 | { 14 | if (root == NULL) 15 | return 0; 16 | int left = TreeDepth(root->left); 17 | int right = TreeDepth(root->right); 18 | return max(left, right) + 1; 19 | } 20 | }; 21 | 22 | 23 | class Solution { 24 | public: 25 | bool IsBalanced_Solution(TreeNode* root) { 26 | if (root == NULL) 27 | return true; 28 | int depth = 0; 29 | return helper(root, depth); 30 | } 31 | bool helper(TreeNode* root, int &depth) 32 | { 33 | if (root == NULL) 34 | { 35 | depth = 0; 36 | return true; 37 | } 38 | int left, right; 39 | if (helper(root->left, left) && helper(root->right, right) && abs(left-right)<=1) 40 | { 41 | depth = max(left,right)+1; 42 | return true; 43 | } 44 | return false; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /NumberOfK/NumberOfK.py: -------------------------------------------------------------------------------- 1 | ### Python Solution 1: 2 | # -*- coding:utf-8 -*- 3 | class Solution: 4 | def GetNumberOfK(self, nums, k): 5 | # write code here 6 | res = 0 7 | n = len(nums) 8 | if n==0: 9 | return 0 10 | for i in range(n): 11 | if nums[i]==k: 12 | res+=1 13 | return res 14 | ### Python Solution 2: 15 | # -*- coding:utf-8 -*- 16 | class Solution: 17 | def GetNumberOfK(self, nums, k): 18 | # write code here 19 | res = 0 20 | n = len(nums) 21 | if n==0: 22 | return 0 23 | start = 0 24 | end = n 25 | while end > start: 26 | mid = start + (end-start)//2 27 | if nums[mid]==k: 28 | end = mid 29 | if nums[mid] < k: 30 | start = mid+1 31 | if nums[mid] > k: 32 | end = mid 33 | temp1 = start ## 一次二分查找寻找左侧边界 34 | start = 0 35 | end = n 36 | while end > start: 37 | mid = start + (end - start)//2 38 | if nums[mid] == k: 39 | start = mid + 1 40 | if nums[mid] < k: 41 | start = mid + 1 42 | if nums[mid] > k: 43 | end = mid 44 | temp2 = end - 1 ## 一次二分查找寻找右侧边界,注意右侧边界要减一 45 | res = temp2-temp1+1 46 | return res 47 | -------------------------------------------------------------------------------- /InversePairs/InversePairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int reversePairs(vector& nums) { 4 | int count = 0; 5 | if (nums.empty()) return count; 6 | int n = nums.size(); 7 | vector temp; 8 | for (int i=0;i &nums, vector &temp, int start, int end) 16 | { 17 | if (start==end) 18 | { 19 | temp[start] = nums[start]; 20 | return 0; 21 | } 22 | int mid = start + (end-start)/2; 23 | int left = helper(temp, nums, start, mid); 24 | int right = helper(temp, nums, mid+1, end); 25 | 26 | int i = mid; 27 | int j = end; 28 | int index = end; 29 | int count = 0; 30 | while (i>=start && j>=mid+1) 31 | { 32 | if (nums[i]>nums[j]) 33 | { 34 | temp[index--] = nums[i--]; 35 | count += j-mid; 36 | } 37 | else 38 | { 39 | temp[index--] = nums[j--]; 40 | } 41 | } 42 | while(i>=start) temp[index--] = nums[i--]; 43 | while(j>=mid+1) temp[index--] = nums[j--]; 44 | return left + right + count; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /DeleteDuplicatedNode/DeleteDuplicatedNode.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | class Solution: 7 | def deleteDuplication(self, head): 8 | # write code here 9 | if head == None or head.next == None: 10 | return head 11 | p = ListNode(-1) 12 | p.next = head 13 | prev = p 14 | cur = head 15 | while cur and cur.next: 16 | if cur.val == cur.next.val: 17 | while cur.next and cur.val == cur.next.val: 18 | cur = cur.next 19 | prev.next = cur.next 20 | else: 21 | prev = cur 22 | cur = cur.next 23 | return p.next 24 | ## Solution 2: 25 | # -*- coding:utf-8 -*- 26 | # class ListNode: 27 | # def __init__(self, x): 28 | # self.val = x 29 | # self.next = None 30 | class Solution: 31 | def deleteDuplication(self, head): 32 | # write code here 33 | if head == None or head.next == None: 34 | return head 35 | if head.val == head.next.val: 36 | while head.next and head.val == head.next.val: 37 | head = head.next 38 | head = self.deleteDuplication(head.next) 39 | else: 40 | head.next = self.deleteDuplication(head.next) 41 | return head 42 | -------------------------------------------------------------------------------- /NumericStrings/NumericStrings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | // 数字的格式可以用A[.[B]][e|EC]或者.B[e|EC]表示, 4 | // 其中A和C都是整数(可以有正负号,也可以没有) 5 | // 而B是一个无符号整数 6 | bool isNumeric(char* str) 7 | { 8 | // 非法输入处理 9 | if (*str == '\0') 10 | return false; 11 | // 标记符号、小数点、e是否出现过 12 | bool sign = false, decimal = false, hasE = false; 13 | int n = strlen(str); 14 | for (int i=0;i0 && str[i-1]!='e' && str[i-1]!='E') // 第一次出现'+''-'符号且不在字符串开头 则必须出现在e之后 27 | return false; 28 | sign = true; 29 | } 30 | else if (str[i]=='.') 31 | { 32 | if (hasE || decimal) 33 | return false; 34 | decimal = true; 35 | } 36 | else if (str[i]<'0'||str[i]>'9') 37 | return false; 38 | } 39 | return true; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /ContinuousSquenceWithSum/ContinuousSquenceWithSum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | class Solution { 5 | public: 6 | vector > FindContinuousSequence(int target) { 7 | //存放结果 8 | vector> res; 9 | //两个起点,相当于动态窗口的两边,根据其窗口内的值的和来确定窗口的位置和大小 10 | int low = 1; 11 | int high = 2; 12 | int sum = 3; 13 | while (high>low) 14 | { 15 | //由于是连续的,差为1的一个序列,那么求和公式是(a0+an)*n/2 16 | sum = (low+high)*(high-low+1)/2; 17 | //相等,那么就将窗口范围的所有数添加进结果集 18 | if (sum==target) 19 | { 20 | vector out; 21 | for (int i=low;i<=high;i++) 22 | { 23 | out.push_back(i); 24 | } 25 | res.push_back(out); 26 | low++; 27 | } 28 | //如果当前窗口内的值之和大于sum,那么左边窗口右移一下 29 | if (sum > target) 30 | { 31 | low++; 32 | } 33 | //如果当前窗口内的值之和小于sum,那么右边窗口右移一下 34 | if (sum < target) 35 | { 36 | high++; 37 | } 38 | } 39 | return res; 40 | } 41 | }; 42 | 43 | int main() 44 | { 45 | int target = 100; 46 | vector >res; 47 | res = Solution().FindContinuousSequence(target); 48 | system("pause"); 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /CopyComplexList/CopyComplexList.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | struct RandomListNode { 3 | int label; 4 | struct RandomListNode *next, *random; 5 | RandomListNode(int x) : 6 | label(x), next(NULL), random(NULL) { 7 | } 8 | }; 9 | */ 10 | class Solution { 11 | public: 12 | RandomListNode* Clone(RandomListNode* head) 13 | { 14 | if (head==NULL) return NULL; 15 | RandomListNode* cur = head; 16 | //复制next 如原来是A->B->C 变成A->A'->B->B'->C->C' 17 | while(cur) 18 | { 19 | RandomListNode* temp = new RandomListNode(cur->label); 20 | temp->next = cur->next; 21 | cur->next = temp; 22 | cur = temp->next; 23 | } 24 | cur = head; 25 | //复制random cur是原来链表的结点 cur->next是复制cur的结点 26 | while(cur) 27 | { 28 | RandomListNode* temp = cur->next; 29 | if (cur->random) 30 | { 31 | temp->random = cur->random->next; 32 | } 33 | cur = temp->next; 34 | } 35 | // 拆分链表,将链表拆分为原链表和复制后的链表 36 | cur = head; 37 | RandomListNode* p = head->next; 38 | while(cur) 39 | { 40 | RandomListNode* temp = cur->next; 41 | cur->next = temp->next; 42 | if (temp->next!=NULL) 43 | temp->next = temp->next->next; 44 | cur = cur->next; 45 | } 46 | return p; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /LeftRotateString/LeftRotateString.py: -------------------------------------------------------------------------------- 1 | ## Python Solution 1: 2 | # -*- coding:utf-8 -*- 3 | class Solution: 4 | def LeftRotateString(self, s, n): 5 | # write code here 6 | m = len(s) 7 | if n>m: 8 | return "" 9 | for i in range(n): 10 | s = self.move(s) 11 | return s 12 | def move(self,s): 13 | s = list(s) 14 | n = len(s) 15 | temp = s[0] 16 | for i in range(n): 17 | if i!=n-1: 18 | s[i]=s[i+1] 19 | else: 20 | s[i] = temp 21 | return ''.join(s) 22 | ## Python Solution 2: 23 | # -*- coding:utf-8 -*- 24 | class Solution: 25 | def LeftRotateString(self, s, n): 26 | # write code here 27 | m = len(s) 28 | if n>m: 29 | return "" 30 | s = self.Reverse(s,0,n-1) 31 | s = self.Reverse(s,n,m-1) 32 | s = self.Reverse(s,0,m-1) 33 | return s 34 | def Reverse(self,s,i,j): 35 | s = list(s) 36 | while inext) 16 | { 17 | n++; 18 | } 19 | if (nnext; 24 | } 25 | return p; 26 | } 27 | }; 28 | // Solution 2: 29 | /* 30 | struct ListNode { 31 | int val; 32 | struct ListNode *next; 33 | ListNode(int x) : 34 | val(x), next(NULL) { 35 | } 36 | };*/ 37 | class Solution { 38 | public: 39 | ListNode* FindKthToTail(ListNode* head, unsigned int k) { 40 | if (head==NULL || k<=0) 41 | return NULL; 42 | ListNode* p = head; 43 | ListNode* q = head; 44 | // 从第1一个节点开始计数,所以走k-1步到达k节点,注意判断k是否超过链表总长度 45 | for (int i=0;inext!=NULL) 48 | q = q->next; 49 | else 50 | return NULL; 51 | } 52 | while(q->next!=NULL) 53 | { 54 | p = p->next; 55 | q = q->next; 56 | } 57 | return p; 58 | } 59 | }; 60 | -------------------------------------------------------------------------------- /JumpFloor/README.md: -------------------------------------------------------------------------------- 1 | # 题目: 跳台阶 2 | 3 | ## 题目描述: 4 | 一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。 5 | 6 | # 解题思路: 7 | 首先我们考虑最简单的情况。如果只有1级台阶,那么显然只一种跳法。如果有2级台阶,那就有两种跳法:一种是分两次跳,每次跳1级;另一种是一次跳2级。 8 | 9 | 接着,我们来讨论一般情况。我们把n级台阶时的跳法看成是n的函数,记为f(n)。当n>2时,第一次跳的时候就有两种不同的选择:一是第一次只跳1级,此时跳法数目等于后面剩下的n-1级台阶的跳法数目,即为f(n-1);另外一种选择是跳一次跳2级,此时跳法数目等于后面剩下的n-2级台阶的跳法数目,即为f(n-2)。因此n级台阶的不同跳法的总数f(n)=f(n-1)+f(n-2)。分析到这里,我们不难看出这实际上就是斐波那契数列了。 10 | 11 | 注意,f(2) = 2, f(1) =1,f(0) =0 12 | # 时间复杂度: 13 | O(n); 14 | # 空间复杂度 15 | O(1) 16 | 17 | # 代码 18 | 19 | [C++](./JumpFloor.cpp) 20 | 21 | [Python](./JumpFloor.py) 22 | 23 | # C++: 24 | ### 动态规划 25 | ```c++ 26 | class Solution { 27 | public: 28 | int jumpFloor(int n) { 29 | if (n<=2) 30 | return n; 31 | int fn_one = 2; 32 | int fn_two = 1; 33 | int fn = 0; 34 | for (int i=3;i<=n;i++) 35 | { 36 | fn = fn_one + fn_two; 37 | fn_two = fn_one; 38 | fn_one = fn; 39 | } 40 | return fn; 41 | } 42 | }; 43 | ``` 44 | # Python: 45 | ### 动态规划 46 | ```python 47 | # -*- coding:utf-8 -*- 48 | class Solution: 49 | def jumpFloor(self, n): 50 | # write code here 51 | if n<=2: 52 | return n 53 | fn_one = 2 54 | fn_two = 1 55 | fn = 0 56 | for i in range(3,n+1): 57 | fn = fn_one + fn_two 58 | fn_two = fn_one 59 | fn_one = fn 60 | return fn 61 | ``` 62 | 63 | -------------------------------------------------------------------------------- /LeftRotateString/LeftRotateString.cpp: -------------------------------------------------------------------------------- 1 | // C++ Solution 1: 2 | class Solution { 3 | public: 4 | void move(string &s) 5 | { 6 | int n = s.size(); 7 | char temp = s[0]; 8 | for (int i=0;i nums ,int k) { 5 | int res = 0; 6 | if (nums.empty()) 7 | return 0; 8 | int n = nums.size(); 9 | for (int i=0;i nums ,int k) { 22 | int res = 0; 23 | if (nums.empty()) 24 | return 0; 25 | int n = nums.size(); 26 | int start = 0; 27 | int end = n; 28 | while (end > start) 29 | { 30 | int mid = start + (end-start)/2; 31 | if (nums[mid]==k) 32 | end=mid; 33 | if (nums[mid]k) 36 | end = mid; 37 | } 38 | int temp1 = start; 39 | start = 0; 40 | end = n; 41 | while (end > start) 42 | { 43 | int mid = start + (end-start)/2; 44 | if (nums[mid]==k) 45 | start=mid+1; 46 | if (nums[mid]k) 49 | end = mid; 50 | } 51 | int temp2 = start; 52 | res = temp2-temp1; 53 | return res; 54 | } 55 | }; 56 | 57 | -------------------------------------------------------------------------------- /CMyString/CMyString.h: -------------------------------------------------------------------------------- 1 | // 2 | // Created by Bryce on 2021/3/29. 3 | // 4 | 5 | #ifndef INC_1_CMYSTRING_H 6 | #define INC_1_CMYSTRING_H 7 | 8 | #include 9 | #include 10 | 11 | class CMyString { 12 | public: 13 | CMyString(char *pData = nullptr); 14 | CMyString(const CMyString &); 15 | ~CMyString(); 16 | CMyString &operator = (const CMyString &str); 17 | char *getData(); 18 | private: 19 | char *m_pData; 20 | }; 21 | 22 | CMyString::CMyString(char *pData){ 23 | m_pData = new char[strlen(pData) + 1]; 24 | strcpy(m_pData, pData); 25 | } 26 | 27 | CMyString::~CMyString() { 28 | if (m_pData) { 29 | delete[] m_pData; 30 | m_pData = nullptr; 31 | } 32 | } 33 | 34 | //拷贝构造函数 35 | CMyString::CMyString(const CMyString &str) { 36 | std::cout << "这是拷贝构造函数!" << std::endl; 37 | m_pData = new char[strlen(str.m_pData) + 1]; 38 | strcpy(m_pData, str.m_pData); 39 | } 40 | 41 | //赋值运算符函数 42 | CMyString &CMyString::operator=(const CMyString &str) { 43 | std::cout << "这是拷贝赋值运算符!" << std::endl; 44 | if (this == &str) { 45 | //检查自赋值的情况 46 | return *this; 47 | } 48 | 49 | //释放原本的内存 50 | if (m_pData) { 51 | delete[] m_pData; 52 | m_pData = nullptr; 53 | } 54 | 55 | m_pData = new char[strlen(str.m_pData) + 1]; 56 | strcpy(m_pData, str.m_pData); 57 | 58 | return *this; 59 | } 60 | 61 | char *CMyString::getData() { 62 | return m_pData; 63 | } 64 | 65 | #endif //INC_1_CMYSTRING_H 66 | -------------------------------------------------------------------------------- /MinNumberInRotatedArray/MinNumberInRotatedArray.cpp: -------------------------------------------------------------------------------- 1 | // C++ Solution 1: 2 | class Solution { 3 | public: 4 | int findMin(vector& nums) { 5 | if (nums.empty()) return 0; 6 | int n = nums.size(); 7 | int res = nums[0]; 8 | for (int i=1;inums[i]) 11 | res = nums[i]; 12 | } 13 | return res; 14 | } 15 | }; 16 | 17 | 18 | 19 | // C++ Solution 2: 20 | class Solution{ 21 | public: 22 | int MinNumberInRotatedArray(vector&nums) 23 | { 24 | if (nums.empty()) return 0; 25 | int n = nums.size(); 26 | int start = 0; 27 | int end = n-1; 28 | int res = nums[0]; 29 | while (end>=start) 30 | { 31 | int mid = start + (end-start)/2; 32 | if (nums[mid]>=res) 33 | { 34 | start = mid+1; 35 | } 36 | if (nums[mid]& nums) { 51 | if (nums.empty()) return 0; 52 | int res = 0; 53 | sort(nums.begin(),nums.end()); 54 | res =nums[0]; 55 | return res; 56 | } 57 | }; 58 | -------------------------------------------------------------------------------- /MergeSortedLists/MergeSortedLists.py: -------------------------------------------------------------------------------- 1 | ### Solution 1: 2 | # -*- coding:utf-8 -*- 3 | # class ListNode: 4 | # def __init__(self, x): 5 | # self.val = x 6 | # self.next = None 7 | class Solution: 8 | # 返回合并后列表 9 | def Merge(self, l1, l2): 10 | # write code here 11 | dummyhead = ListNode(-1) 12 | l3 = dummyhead 13 | if l1==None: 14 | return l2 15 | if l2==None: 16 | return l1 17 | if l1==None and l2==None: 18 | return None 19 | while l1 and l2: 20 | if l1.val<=l2.val: 21 | l3.next = l1 22 | l1 = l1.next 23 | else: 24 | l3.next = l2 25 | l2 = l2.next 26 | l3 = l3.next 27 | if l1==None: 28 | l3.next = l2 29 | if l2==None: 30 | l3.next = l1 31 | return dummyhead.next 32 | 33 | ### Solution 2: 34 | # -*- coding:utf-8 -*- 35 | # class ListNode: 36 | # def __init__(self, x): 37 | # self.val = x 38 | # self.next = None 39 | class Solution: 40 | # 返回合并后列表 41 | def Merge(self, l1, l2): 42 | # write code here 43 | if l1==None: 44 | return l2 45 | if l2==None: 46 | return l1 47 | if l1==None and l2==None: 48 | return None 49 | if l1.val <= l2.val: 50 | l1.next = self.Merge(l1.next,l2) 51 | return l1 52 | else: 53 | l2.next = self.Merge(l1,l2.next) 54 | return l2 55 | -------------------------------------------------------------------------------- /RegularExpressionsMatching/RegularExpressionsMatching.py: -------------------------------------------------------------------------------- 1 | ### Solution 1: 2 | # -*- coding:utf-8 -*- 3 | class Solution: 4 | # s, pattern都是字符串 5 | def match(self, s, p): 6 | # write code here 7 | if len(s)==0 and len(p)==0: 8 | return True 9 | if len(s)!=0 and len(p)==0: 10 | return False 11 | if len(p)>1 and p[1]=='*': 12 | if len(s)>0 and (s[0] == p[0] or p[0]=='.'): 13 | return self.match(s,p[2:]) or self.match(s[1:],p) 14 | else: 15 | return self.match(s,p[2:]) 16 | if len(s)>0 and (s[0] == p[0] or p[0]=='.'): 17 | return self.match(s[1:],p[1:]) 18 | else: 19 | return False 20 | 21 | 22 | ### Solution 2: 23 | # -*- coding:utf-8 -*- 24 | class Solution: 25 | # s, pattern都是字符串 26 | def match(self, s, p): 27 | # write code here 28 | n = len(s) 29 | m = len(p) 30 | dp = [[0 for _ in range(m+2)] for _ in range(n+2)] 31 | s = ' ' + s 32 | p = ' ' + p 33 | dp[0][0] = 1 34 | for i in range(n+1): 35 | for j in range(1,m+1): 36 | if i > 0 and (s[i]==p[j] or p[j]=='.'): 37 | dp[i][j] = dp[i][j] or dp[i-1][j-1] 38 | if p[j]=='*': 39 | if j>=2: 40 | dp[i][j] = dp[i][j] or dp[i][j-2] 41 | if i > 0 and (s[i]==p[j-1] or p[j-1]=='.'): 42 | dp[i][j] = dp[i][j] or dp[i-1][j] 43 | return dp[n][m] 44 | -------------------------------------------------------------------------------- /ConstructBinaryTree/ConstructBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 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 | TreeNode* reConstructBinaryTree(vector pre,vector vin) { 13 | if (pre.empty() || vin.empty()) 14 | return NULL; 15 | int n = pre.size(); 16 | // 前序遍历的第一个数字是根节点的值 17 | int root = pre[0]; 18 | // 创建根节点 19 | TreeNode* t = new TreeNode(root); 20 | // 如果长度为1,直接返回根节点 21 | if (n==1) return t; 22 | // 找到root所在的位置,确定好前序和中序中左子树和右子树序列的范围 23 | int root_index = 0; 24 | for (int i=0;i left_pre,left_in, right_pre, right_in; 34 | for (int i=0;ileft = reConstructBinaryTree(left_pre,left_in); 46 | t->right = reConstructBinaryTree(right_pre,right_in); 47 | return t; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /KthNodeInBST/KthNodeInBST.py: -------------------------------------------------------------------------------- 1 | ### Solution 1: 2 | class Solution: 3 | def kthLargest(self, root: TreeNode, k: int) -> int: 4 | res = 0 5 | if root is None or k < 1: 6 | return res 7 | out = [] 8 | self.helper(root, out) 9 | res = out[-k] 10 | return res 11 | def helper(self, root, out): 12 | if root is None: 13 | return 14 | self.helper(root.left, out) 15 | out.append(root.val) 16 | self.helper(root.right, out) 17 | ### Solution 2: 18 | class Solution: 19 | def __init__(self): 20 | self.res = 0 21 | self.count = 0 22 | def kthLargest(self, root: TreeNode, k: int) -> int: 23 | if root is None or k < 1: 24 | return self.res 25 | self.helper(root, k) 26 | return self.res 27 | def helper(self, root, k): 28 | if (root==None): 29 | return 30 | self.helper(root.right, k) 31 | self.count = self.count + 1 32 | if self.count == k: 33 | self.res = root.val 34 | return 35 | self.helper(root.left, k) 36 | ### Solution 3: 37 | class Solution: 38 | def kthLargest(self, root: TreeNode, k: int) -> int: 39 | n = 0 40 | s = [] 41 | p = root 42 | while s or p: 43 | while p: 44 | s.append(p) 45 | p = p.right 46 | p = s.pop() 47 | n+=1 48 | if n == k: 49 | return p.val 50 | p = p.left 51 | return 0 52 | -------------------------------------------------------------------------------- /StringPathInMatrix/StringPathInMatrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool hasPath(char* matrix, int rows, int cols, char* str) 4 | { 5 | if(matrix == NULL || rows <1 || cols < 1 || str == NULL) 6 | return false; 7 | vector> visited (rows, vector(cols,0)); 8 | for (int i=0;i> &visited) 21 | { 22 | //因为是一维数组存放二维的值,index值就是相当于二维数组的(i,j)在一维数组的下标 23 | int index = i*cols + j; 24 | if(i<0||i>=rows||j<0||j>=cols||matrix[index]!=str[k]||visited[i][j]==1) 25 | return false; 26 | //字符串已经查找结束,说明找到该路径了 27 | if (str[k+1]=='\0') 28 | return true; 29 | //标记访问过 30 | visited[i][j]=1; 31 | //向四个方向进行递归查找,向左,向右,向上,向下查找 32 | if (helper(matrix, rows, cols, i, j-1, str, k+1, visited)|| 33 | helper(matrix, rows, cols, i, j+1, str, k+1, visited)|| 34 | helper(matrix, rows, cols, i-1, j, str, k+1, visited)|| 35 | helper(matrix, rows, cols, i+1, j, str, k+1, visited)) 36 | { 37 | return true; 38 | } 39 | visited[i][j]=0; 40 | return false; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /RobotMove/RobotMove.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int movingCount(int threshold, int rows, int cols) 4 | { 5 | int res = 0; 6 | vector> visited (rows, vector(cols,0)); 7 | res = helper(threshold, rows, cols,0, 0, visited); 8 | return res; 9 | } 10 | int helper(int threshold, int rows, int cols, int i, int j, vector> &visited) 11 | { 12 | int sum = bitSum(i) + bitSum(j); 13 | // 或者转成字符串来计算 14 | //string s1 = to_string(i); 15 | // string s2 = to_string(j); 16 | // int sum = 0; 17 | // for (int x =0; x k|| i<0|| i>=m || j<0|| j>=n||visited[i][j]==1) 26 | // { 27 | // return 0; 28 | // } 29 | if (sum > threshold || i<0 || i>=rows || j<0 || j>=cols || visited[i][j]==1) 30 | return 0; 31 | visited[i][j]=1; 32 | return helper(threshold, rows, cols,i-1, j, visited) + helper(threshold, rows, cols,i+1, j, visited) + 33 | helper(threshold, rows, cols,i, j-1, visited) + helper(threshold, rows, cols,i, j+1, visited) + 1; 34 | } 35 | //计算位置的数值 36 | int bitSum(int num) 37 | { 38 | int sum = 0; 39 | while(num>0) 40 | { 41 | sum+=num%10; 42 | num/=10; 43 | } 44 | return sum; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /MergeSortedLists/MergeSortedLists.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | struct ListNode { 3 | int val; 4 | struct ListNode *next; 5 | ListNode(int x) : 6 | val(x), next(NULL) { 7 | } 8 | };*/ 9 | class Solution { 10 | public: 11 | ListNode* Merge(ListNode* l1, ListNode* l2) 12 | { 13 | ListNode* dummyhead = new ListNode(-1); 14 | ListNode* l3 = dummyhead; 15 | if (l1==NULL) return l2; 16 | if (l2==NULL) return l1; 17 | if (l1==NULL && l2==NULL) return NULL; 18 | while(l1 && l2) 19 | { 20 | if (l1->val<=l2->val) 21 | { 22 | l3->next = l1; 23 | l1 = l1->next; 24 | } 25 | else 26 | { 27 | l3->next = l2; 28 | l2 = l2->next; 29 | } 30 | l3 = l3->next; 31 | } 32 | if (l1==NULL) l3->next = l2; 33 | if (l2==NULL) l3->next = l1; 34 | return dummyhead->next; 35 | } 36 | }; 37 | 38 | // Solution 2: 39 | /* 40 | struct ListNode { 41 | int val; 42 | struct ListNode *next; 43 | ListNode(int x) : 44 | val(x), next(NULL) { 45 | } 46 | };*/ 47 | class Solution { 48 | public: 49 | ListNode* Merge(ListNode* l1, ListNode* l2) 50 | { 51 | if (l1==NULL) return l2; 52 | if (l2==NULL) return l1; 53 | if (l1==NULL && l2==NULL) return NULL; 54 | if (l1->val <= l2->val) 55 | { 56 | l1->next = Merge(l1->next,l2); 57 | return l1; 58 | } 59 | else 60 | { 61 | l2->next = Merge(l1,l2->next); 62 | return l2; 63 | } 64 | } 65 | }; 66 | -------------------------------------------------------------------------------- /TranslateNum/README.md: -------------------------------------------------------------------------------- 1 | # 题目:把数字翻译成字符串 2 | ## 题目描述: 3 | 给定一个数字,我们按照如下规则把它翻译为字符串:0 翻译成 “a” ,1 翻译成 “b”,……,11 翻译成 “l”,……,25 翻译成 “z”。一个数字可能有多个翻译。请编程实现一个函数,用来计算一个数字有多少种不同的翻译方法。 4 | 5 | **示例:** 6 | ``` 7 | 输入: 12258 8 | 输出: 5 9 | 解释: 12258有5种不同的翻译,分别是"bccfi", "bwfi", "bczi", "mcfi"和"mzi" 10 | ``` 11 | 12 | # 本题考点: 13 | 14 | 动态规划。 15 | 16 | # 解题思路: 17 | 18 | ![](https://github.com/bryceustc/CodingInterviews/blob/master/TranslateNum/1.jpg) 19 | 20 | **注意:dp范围那里应该是10-25之间** 21 | 22 | # 代码 23 | 24 | [C++](./TranslateNum.cpp) 25 | 26 | [Python](./TranslateNum.py) 27 | 28 | # C++: 29 | ### dp 30 | ```c++ 31 | class Solution { 32 | public: 33 | int translateNum(int num) { 34 | string s = to_string(num); 35 | int n = s.size(); 36 | vector dp(n+1, 0); // dp[i]表示前i个数字的翻译种数,注意dp[i]对应的数字是s[i-1] 37 | dp[0] = 1; 38 | dp[1] = 1; 39 | for (int i =2;i"25") 42 | { 43 | dp[i] = dp[i-1]; 44 | } 45 | else 46 | { 47 | dp[i] = dp[i-1] + dp[i-2]; 48 | } 49 | } 50 | return dp[n]; 51 | } 52 | }; 53 | ``` 54 | # Python: 55 | ```python 56 | class Solution: 57 | def translateNum(self, num: int) -> int: 58 | s = str(num) 59 | n = len(s) 60 | dp = [1 for _ in range(n+1)] 61 | for i in range(2,n+1): 62 | if s[i-2] == '0' or (s[i-2:i]>"25"): 63 | dp[i] = dp[i-1] 64 | else: 65 | dp[i] = dp[i-1] + dp[i-2] 66 | return dp[n] 67 | ``` 68 | 69 | -------------------------------------------------------------------------------- /LongestConsecutive/README.md: -------------------------------------------------------------------------------- 1 | # 题目描述:顺时针打印矩阵 2 | 3 | ## 题目: 4 | 给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。 5 | 6 | 请你设计并实现时间复杂度为 O(n) 的算法解决此问题。 7 | 8 | 示例 1: 9 | 10 | 输入:nums = [100,4,200,1,3,2] 11 | 输出:4 12 | 解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。 13 | 14 | 15 | 示例 2: 16 | 17 | 输入:nums = [0,3,7,2,5,8,4,6,0,1] 18 | 输出:9 19 | 20 | 21 | # 解题思路: 22 | 在一个未排序的整数数组 nums中 ,找出最长的数字连续序列,朴素的做法是:枚举nums中的每一个数x,并以x起点,在nums数组中查询x + 1,x + 2,,,x + y是否存在。假设查询到了 x + y,那么长度即为 y - x + 1,不断枚举更新答案即可。 23 | 24 | 如果每次查询一个数都要遍历一遍nums数组的话,时间复杂度为O(n) ,其实我们可以用一个哈希表来存贮数组中的数,这样查询的时间就能优化为O(1) 。 25 | 26 | 如何每次只枚举连续序列的起始数字x? 27 | 28 | 其实只需要每次在哈希表中检查是否存在 x−1即可。如果x-1存在,说明当前数x不是连续序列的起始数字,我们跳过这个数。 29 | 30 | 具体过程如下: 31 | 32 | 1、定义一个哈希表hash,将nums数组中的数都放入哈希表中。 33 | 34 | 2、遍历哈希表hash,如果当前数x的前驱x-1不存在,我们就以当前数x为起点向后枚举。 35 | 36 | 3、假设最长枚举到了数y,那么连续序列长度即为y-x+1。 37 | 38 | 4、不断枚举更新答案。 39 | 40 | # 代码 41 | ```c++ 42 | class Solution { 43 | public: 44 | int longestConsecutive(vector& nums) { 45 | unordered_set hash; 46 | for(auto x : nums) hash.insert(x); //放入hash表中 47 | int res = 0; 48 | for(auto x : hash) 49 | { 50 | // 前一个存在,说明会计算到,直接跳过 51 | if(!hash.count(x-1)) 52 | { 53 | int y = x; //以当前数x向后枚举 54 | while(hash.count(y + 1)) y++; 55 | res = max(res, y - x + 1); //更新答案 56 | } 57 | } 58 | return res; 59 | } 60 | }; 61 | 62 | ``` 63 | 64 | # 参考: 65 | - [LeetCode旋转矩阵](https://github.com/bryceustc/LeetCode_Note/blob/master/cpp/Spiral-Matrix/README.md) 66 | 67 | -------------------------------------------------------------------------------- /PrintTreesInZigzag/PrintTreesInZigzag.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | struct TreeNode { 3 | int val; 4 | struct TreeNode *left; 5 | struct TreeNode *right; 6 | TreeNode(int x) : 7 | val(x), left(NULL), right(NULL) { 8 | } 9 | }; 10 | */ 11 | class Solution { 12 | public: 13 | vector > Print(TreeNode* root) { 14 | vector> res; 15 | if (root==NULL) 16 | return res; 17 | deque q; 18 | q.push_back(root); 19 | bool zigzag = true; // 从右打印为True,从左打印为False 20 | while (!q.empty()) 21 | { 22 | int count = q.size(); 23 | vector out; 24 | TreeNode* node; 25 | while (count>0) 26 | { 27 | if (zigzag) //前取后放:从左向右,所以从前边取,后边放入 28 | { 29 | node = q.front(); 30 | q.pop_front(); 31 | if (node->left) 32 | q.push_back(node->left); 33 | if (node->right) 34 | q.push_back(node->right); 35 | } 36 | else // 后取前放:从右向左,从后边取,前边放入 37 | { 38 | node = q.back(); 39 | q.pop_back(); 40 | if (node->right) 41 | q.push_front(node->right); 42 | if (node->left) 43 | q.push_front(node->left); 44 | } 45 | out.push_back(node->val); 46 | count--; 47 | } 48 | res.push_back(out); 49 | zigzag = !zigzag; 50 | } 51 | return res; 52 | } 53 | }; 54 | -------------------------------------------------------------------------------- /TwoNumbersWithSum/TwoNumbersWithSum.py: -------------------------------------------------------------------------------- 1 | ### Python Solution 1: 2 | class Solution: 3 | def FindNumbersWithSum(self, nums, target): 4 | # write code here 5 | res = [] 6 | n = len(nums) 7 | if n==0: 8 | return res 9 | for i in range(n): 10 | for j in range(i+1,n): 11 | if nums[i]+nums[j]==target: 12 | res.append(nums[i]) 13 | res.append(nums[j]) 14 | return res 15 | return res 16 | ### Python Solution 2: 17 | # -*- coding:utf-8 -*- 18 | class Solution: 19 | def FindNumbersWithSum(self, nums, target): 20 | # write code here 21 | res = [] 22 | record = {} 23 | n = len(nums) 24 | if n==0: 25 | return res 26 | for index,num in enumerate (nums): 27 | complement = target - num 28 | if complement in record: 29 | res.append(complement) 30 | res.append(num) 31 | return res 32 | record[num] = index 33 | return res 34 | ### Python Solution 3: 35 | # -*- coding:utf-8 -*- 36 | class Solution: 37 | def FindNumbersWithSum(self, nums, target): 38 | # write code here 39 | res = [] 40 | n = len(nums) 41 | left = 0 42 | right = n-1 43 | while right>left: 44 | if nums[left]+nums[right]==target: 45 | res.append(nums[left]) 46 | res.append(nums[right]) 47 | return res 48 | if nums[left]+nums[right]>target: 49 | right-=1 50 | else: 51 | left+=1 52 | return res 53 | -------------------------------------------------------------------------------- /PrintTreesInLines/PrintTreesInLines.cpp: -------------------------------------------------------------------------------- 1 | // C++ Solution 1: 2 | class Solution { 3 | public: 4 | vector > Print(TreeNode* root) { 5 | vector> res; 6 | if (root==NULL) 7 | return res; 8 | queue q; 9 | q.push(root); 10 | while(!q.empty()) 11 | { 12 | int count = q.size(); 13 | vector out; 14 | while(count>0) 15 | { 16 | TreeNode* node = q.front(); 17 | q.pop(); 18 | out.push_back(node->val); 19 | if (node->left) 20 | q.push(node->left); 21 | if (node->right) 22 | q.push(node->right); 23 | count--; 24 | } 25 | res.push_back(out); 26 | } 27 | return res; 28 | } 29 | 30 | }; 31 | // C++ Solution 2: 32 | class Solution { 33 | public: 34 | vector> Print(TreeNode* root) { 35 | vector> res; 36 | if (root==NULL) 37 | return res; 38 | helper(root, res,0); 39 | return res; 40 | } 41 | 42 | void helper(TreeNode* root, vector> &res, int level) 43 | { 44 | if (root==NULL) 45 | return; 46 | if (res.size()==level) 47 | res.push_back(vector()); 48 | res[level].push_back(root->val); 49 | if (root->left) 50 | helper(root->left,res,level+1); 51 | if (root->right) 52 | helper(root->right,res,level+1); 53 | } 54 | }; 55 | -------------------------------------------------------------------------------- /StringPermutation/StringPermutation.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class Solution: 3 | def Permutation(self, s): 4 | # write code here 5 | n = len(s) 6 | res = [] 7 | if n==0: 8 | return res 9 | out = "" 10 | visited = [0 for _ in range(n)] 11 | self.DFS(s,0,visited,out,res) 12 | return res 13 | def DFS(self,s,level,visited,out,res): 14 | n = len(s) 15 | if level == n: 16 | res.append(out) 17 | return 18 | for i in range(n): 19 | if visited[i]==1: 20 | continue 21 | if i >= 1 and s[i]==s[i-1] and visited[i-1]==0: 22 | continue 23 | out += s[i] 24 | visited[i]=1 25 | self.DFS(s,level+1,visited,out,res) 26 | out = out[:-1] 27 | visited[i]=0 28 | ### Solution 2: 29 | # -*- coding:utf-8 -*- 30 | class Solution: 31 | def __init__(self): 32 | self.result = [] 33 | def Permutation(self, ss): 34 | # write code here 35 | if len(ss) == 0: 36 | return [] 37 | self.PermutationCore(ss, 0) 38 | sorted(self.result) 39 | return self.result 40 | def PermutationCore(self, str_, begin): 41 | if begin == len(str_): 42 | self.result.append(str_) 43 | return 44 | for i in range(begin, len(str_)): 45 | if i != begin and str_[i] == str_[begin]: 46 | continue 47 | str_list = list(str_) 48 | str_list[i], str_list[begin] = str_list[begin], str_list[i] 49 | str_ = ''.join(str_list) 50 | self.PermutationCore(str_, begin+1) 51 | -------------------------------------------------------------------------------- /FirstCommonNodesInLists/FirstCommonNodesInLists.py: -------------------------------------------------------------------------------- 1 | ## Python Solution 1: 2 | # -*- coding:utf-8 -*- 3 | # class ListNode: 4 | # def __init__(self, x): 5 | # self.val = x 6 | # self.next = None 7 | class Solution: 8 | def FindFirstCommonNode(self, l1, l2): 9 | # write code here 10 | if l1==None or l2 == None: 11 | return None 12 | p = l1 13 | q = l2 14 | while p: 15 | q = l2 16 | while q: 17 | if p.val==q.val: 18 | return p 19 | else: 20 | q = q.next 21 | p = p.next 22 | return None 23 | ## Python Solution 2: 24 | # -*- coding:utf-8 -*- 25 | # class ListNode: 26 | # def __init__(self, x): 27 | # self.val = x 28 | # self.next = None 29 | class Solution: 30 | def FindFirstCommonNode(self, l1, l2): 31 | # write code here 32 | if l1==None or l2 == None: 33 | return None 34 | p = l1 35 | q = l2 36 | n=0 37 | m=0 38 | while p: 39 | n+=1 40 | p = p.next 41 | while q: 42 | m+=1 43 | q = q.next 44 | temp_long = l1 45 | temp_short = l2 46 | k = 0 47 | if n>=m: 48 | k = n-m 49 | else: 50 | k = m-n 51 | temp_long = l2 52 | temp_short = l1 53 | for i in range(k): 54 | temp_long = temp_long.next 55 | while temp_long and temp_short and temp_long!=temp_short: 56 | temp_long = temp_long.next 57 | temp_short = temp_short.next 58 | res = temp_long 59 | return res 60 | -------------------------------------------------------------------------------- /ConstuctArray/ConstuctArray.py: -------------------------------------------------------------------------------- 1 | ### Python Solution 1: 2 | # -*- coding:utf-8 -*- 3 | class Solution: 4 | def multiply(self, A): 5 | # write code here 6 | n = len(A) 7 | if n==0: 8 | return [] 9 | B = [0 for _ in range(n)] 10 | for i in range(n): 11 | temp = 1 12 | for j in range(n): 13 | if j==i: 14 | continue 15 | temp*=A[j] 16 | B[i] = temp 17 | return B 18 | ### Python Solution 2: 19 | # -*- coding:utf-8 -*- 20 | class Solution: 21 | def multiply(self, A): 22 | # write code here 23 | n = len(A) 24 | if n==0: 25 | return [] 26 | B = [0 for _ in range(n)] 27 | ## 计算下三角 28 | B[0]=1 29 | for i in range(1,n): 30 | B[i]=B[i-1]*A[i-1] 31 | ## 计算上三角 32 | temp = 1 33 | for i in range(n-2,-1,-1): 34 | temp *= A[i+1] 35 | B[i] *= temp 36 | return B 37 | ## Python Solution 3: 38 | # -*- coding:utf-8 -*- 39 | class Solution: 40 | def multiply(self, A): 41 | # write code here 42 | B = [] 43 | n = len(A) 44 | if n == 0: 45 | return B 46 | else: 47 | for i in range(n): 48 | ## 求B[i],就把A[i]设为1,完了把A[i]值恢复 49 | temp = A[i] 50 | A[i] = 1 51 | B.append(reduce(lambda x,y:x*y, A)) 52 | # reduce() 函数会对参数序列中元素进行累积。 53 | # 函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 54 | # function(有两个参数)先对集合中的第 1、2 个元素进行操作, 55 | # 得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。 56 | A[i] = temp 57 | return B 58 | -------------------------------------------------------------------------------- /ReverseWordsInSentence/ReverseWordsInSentence.cpp: -------------------------------------------------------------------------------- 1 | // Solution 1: 2 | class Solution { 3 | public: 4 | string ReverseSentence(string s) { 5 | string res=""; 6 | int n = s.size(); 7 | if (n==0) 8 | return res; 9 | if (n==1) 10 | return s; 11 | for (int i=n,j=n-1;j>=0;j--) 12 | { 13 | if (s[j]==' ') 14 | { 15 | for(int k=j+1;k out; 10 | helper(root, out); 11 | int n = out.size(); 12 | res = out[n-k]; 13 | return res; 14 | } 15 | void helper(TreeNode* root, vector &v) 16 | { 17 | if (root==NULL) 18 | return; 19 | helper(root->left, v); 20 | v.push_back(root->val); 21 | helper(root->right,v); 22 | } 23 | } 24 | 25 | 26 | class Solution { 27 | public: 28 | int kthLargest(TreeNode* root, int k) { 29 | if (root == NULL || k<1) 30 | { 31 | return 0; 32 | } 33 | helper(root, k); 34 | return res; 35 | } 36 | void helper(TreeNode* root, int k) 37 | { 38 | if (root==NULL) 39 | return; 40 | helper(root->right, k); 41 | if (++count==k) 42 | { 43 | res = root->val; 44 | return; 45 | } 46 | helper(root->left, k); 47 | } 48 | private: 49 | int res = 0; 50 | int count = 0; 51 | }; 52 | 53 | class Solution { 54 | public: 55 | int kthLargest(TreeNode* root, int k) { 56 | int n=0; 57 | stack s; 58 | TreeNode* p = root; 59 | while (!s.empty() || p!=NULL) 60 | { 61 | while(p!=NULL) 62 | { 63 | s.push(p); 64 | p = p->right; 65 | } 66 | p =s.top(); 67 | s.pop(); 68 | if (++n==k) 69 | { 70 | return p->val; 71 | } 72 | p = p->left; 73 | } 74 | return 0; 75 | } 76 | }; 77 | 78 | -------------------------------------------------------------------------------- /ReplaceSpaces/ReplaceSpaces.cpp: -------------------------------------------------------------------------------- 1 | // C++ Solution 1: 2 | class Solution { 3 | public: 4 | void replaceSpace(char *str,int length) { 5 | if (str == NULL || length <=0) 6 | return; 7 | for (int i=0;ii+2;j--) 13 | { 14 | *(str+j)=*(str+j-2); 15 | } 16 | *(str+i) = '/%'; 17 | *(str+i+1) = '2'; 18 | *(str+i+2) = '0'; 19 | } 20 | } 21 | } 22 | }; 23 | 24 | 25 | // C++ Solution 2: 26 | class Solution { 27 | public: 28 | void replaceSpace(char *str,int length) { 29 | if (str == NULL || length <=0) 30 | return; 31 | int i=0; 32 | int oldLength = 0; // 原字符串长度 33 | int newLength = 0; // 替换后字符串长度 34 | int numberofBlank = 0; //空格数量 35 | while(str[i]!='\0') 36 | { 37 | oldLength++; 38 | if (str[i]==' ') 39 | { 40 | numberofBlank++; 41 | } 42 | i++; 43 | } 44 | newLength = oldLength + numberofBlank*2; // 计算替换后字符串的长度 45 | if (newLength > length) // 如果大于最大长度直接返回 因为无法插入 46 | return; 47 | // 设置两个指针,一个指向原始字符串的末尾,另一个指向替换之后的字符串的末尾 注意不要减一 48 | int p = oldLength; //设置p指针指向旧字符串的末尾 49 | int q = newLength; //设置q指针指向新字符串的末尾 50 | while (p>=0 && p bool: 5 | if num <1: 6 | return False 7 | while num%5 == 0: 8 | num//=5 9 | while num%3 == 0: 10 | num//=3 11 | while num%2 == 0: 12 | num//=2 13 | return num==1 14 | def GetUglyNumber_Solution(self, n: int) -> int: 15 | i = 0 16 | num = 0 17 | while i来进行次数统计,可以用int类型是因为c++会自动将字符转成对应的ASCII码数字,可以利用unordered_map来进行次数统计.Python 利用collections.Counter()模块进行次数统计。 11 | 12 | 时间复杂度为O(n),空间复杂度O(n)。 13 | 14 | 15 | 16 | # 代码 17 | 18 | [C++](./FirstNotRepeatingChar.cpp) 19 | 20 | [Python](./FirstNotRepeatingChar.py) 21 | 22 | # C++: 23 | ### 哈希表,时间复杂度O(n),空间复杂度O(n) 24 | ```c++ 25 | class Solution { 26 | public: 27 | int FirstNotRepeatingChar(string s) { 28 | int res = -1; 29 | int n = s.size(); 30 | if (n==0) return res; 31 | unordered_map m; 32 | for (int i=0;i len(lis): 15 | return 16 | root = None 17 | if lis[self.flag] != "n": 18 | root = TreeNode(int(lis[self.flag])) 19 | root.left = self.Deserialize(s) 20 | root.right = self.Deserialize(s) 21 | return root 22 | ## Solution 2: 23 | class Solution: 24 | def Serialize(self, root): 25 | # write code here 26 | s = "" 27 | q = [] 28 | q.append(root) 29 | while q: 30 | node = q.pop(0) 31 | if node: 32 | s += str(node.val) + "," 33 | q.append(node.left) 34 | q.append(node.right) 35 | else: 36 | s += "n," 37 | return s 38 | def Deserialize(self, s): 39 | # write code here 40 | s = s.split(",") 41 | if s[0] == 'n': 42 | return None 43 | q = [] 44 | i = 1 45 | res = TreeNode(int(s[0])) 46 | q.append(res) 47 | while q: 48 | node = q.pop(0) 49 | if node == None: 50 | continue 51 | if s[i] != 'n': 52 | node.left = TreeNode(int(s[i])) 53 | else: 54 | node.left = None 55 | if s[i+1] != 'n': 56 | node.right = TreeNode(int(s[i+1])) 57 | else: 58 | node.right = None 59 | i+=2 60 | q.append(node.left) 61 | q.append(node.right) 62 | return res 63 | -------------------------------------------------------------------------------- /RegularExpressionsMatching/RegularExpressionsMatching.cpp: -------------------------------------------------------------------------------- 1 | // C++ Solution 1: 2 | class Solution { 3 | public: 4 | bool match(char* str, char* pattern) 5 | { 6 | if (*str == '\0' && *pattern == '\0') 7 | return true; 8 | if (*str != '\0' && *pattern == '\0') 9 | return false; 10 | if (*(pattern +1) !='*') 11 | { 12 | if (* str == * pattern || (*str !='\0'&& *pattern =='.')) 13 | return match(str+1,pattern+1); 14 | else 15 | return false; 16 | } 17 | else 18 | { 19 | if (* str == * pattern || (*str!='\0')&& *pattern == '.') 20 | return (match(str,pattern+2) || match(str+1,pattern)); 21 | else 22 | return (match(str,pattern+2)); 23 | } 24 | } 25 | }; 26 | 27 | 28 | // C++ Solution 2: 29 | class Solution { 30 | public: 31 | bool isMatch(string s, string p) { 32 | int n = s.size(); 33 | int m = p.size(); 34 | vector> dp(n+1,vector(m+1,false)); 35 | dp[0][0]=true; 36 | s = ' '+s; 37 | p = ' '+p; 38 | for (int i=0;i<=n;i++) // i从0开始,因为dp(0,j)有可能是有意义的 39 | { 40 | for(int j=1;j<=m;j++) 41 | { 42 | if (i>0 && (s[i]==p[j] || p[j]=='.')) 43 | { 44 | dp[i][j] = dp[i][j] | dp[i-1][j-1]; // | 表示按位或 45 | } 46 | if (p[j]=='*') 47 | { 48 | if (j>=2) 49 | { 50 | dp[i][j] = dp[i][j] | dp[i][j-2]; 51 | } 52 | if (i>0 && (s[i]==p[j-1] || p[j-1]=='.')) 53 | { 54 | dp[i][j] = dp[i][j] | dp[i-1][j]; 55 | } 56 | } 57 | } 58 | } 59 | return dp[n][m]; 60 | } 61 | }; 62 | -------------------------------------------------------------------------------- /NumberOf1/NumberOf1.cpp: -------------------------------------------------------------------------------- 1 | // Solution 1: 2 | class Solution { 3 | public: 4 | int NumberOf1Between1AndN_Solution(int n) 5 | { 6 | int res = 0; 7 | if (n<1) 8 | return res; 9 | for (int i=1;i<=n;i++) 10 | { 11 | res += NumberOf1(i); 12 | } 13 | return res; 14 | } 15 | int NumberOf1(int n) 16 | { 17 | int num = 0; 18 | while (n) 19 | { 20 | if(n%10==1) 21 | num++; 22 | n /= 10; 23 | } 24 | return num; 25 | } 26 | }; 27 | 28 | // Solution 2: 29 | class Solution { 30 | public: 31 | int NumberOf1Between1AndN_Solution(int n) 32 | { 33 | // 统计次数 34 | int res = 0; 35 | //i表示当前分析的是哪一个数位 36 | for (long int i= 1; i<=n; i*=10) 37 | { 38 | // 分别以个位、十位、百位...分隔数字,然后统计1出现的次数 39 | long int a = n/i; 40 | long int b = n%i; 41 | // 以百位为例,如果百位数字>=2,n=31456为例,a=314,b=56,百位为4>=2, 42 | // 则总共有0~31个百位为1的,也就是(a/10+1)*100=3200个百位为1的数字,同理从个位统计到最高位再相加。 43 | // 如果百位为1,n=31156为例,a=311,b=56,百位1==1 44 | // 则总共最高两位有0~30开头且百位为1的,100~199共100个,所以(a/10)* 100 = 3100 再加上31开头百位为1的(b+1)=57个1 45 | // 如果百位为0,以n=31056为例,a=310,b=56,百位0==0 46 | // 则总共最高两位有0~30开头且百位为1的,所以(a/10)* 100 = 3100,31开头没有百位为1的,所以不加 47 | // 综上:三种情况,可以用(a+8)/10来表示,因为只有>=2时+8才等价于(a/10+1) 48 | // 而b的数字,要结合a%10取a的最低位,也就是实际数字相应的位数,就是对应个位、十位、百位...判断是否为1,在进行相加 49 | res += (a+8)/10*i + (a%10==1)*(b+1); 50 | } 51 | return res; 52 | } 53 | }; 54 | // Solution 3: 55 | class Solution { 56 | public: 57 | int NumberOf1Between1AndN_Solution(int n) 58 | { 59 | int res = 0; 60 | for (int i = 1; i <= n; i++) { 61 | string str = to_string(i); 62 | res += count(str.begin(), str.end(), '1'); 63 | } 64 | return res; 65 | } 66 | }; 67 | -------------------------------------------------------------------------------- /FindInPartiallySortedMatrix/FindInPartiallySortedMatrix.py: -------------------------------------------------------------------------------- 1 | ## Python Solution 1: 2 | # -*- coding:utf-8 -*- 3 | class Solution: 4 | def Find(self, nums, target): 5 | m = len(nums) 6 | if m == 0: 7 | return False 8 | n = len(nums[0]) 9 | for i in range(m): 10 | for j in range(n): 11 | if nums[i][j] == target: 12 | return True 13 | return False 14 | 15 | ## Python Solution 2: 16 | # -*- coding:utf-8 -*- 17 | class Solution: 18 | def Find(self, nums, target): 19 | m = len(nums) 20 | if m == 0: 21 | return False 22 | n = len(nums[0]) 23 | for i in range(m): 24 | start = 0 25 | end = n-1 26 | while end>=start: 27 | mid = start+(end-start)//2 28 | if nums[i][mid]==target: 29 | return True 30 | if nums[i][mid]target: 33 | end=mid-1 34 | return False 35 | ## Python Solution 3: 36 | ## 右上角查找 37 | class Solution: 38 | def Find(self, nums, target): 39 | m = len(nums) 40 | if m == 0: 41 | return False 42 | n = len(nums[0]) 43 | i=0 44 | j=n-1 45 | while i=0 : 46 | if nums[i][j]==target: 47 | return True 48 | elif nums[i][j]>target: 49 | j-=1 ## 左移 50 | else: 51 | i+=1 ## 下移 52 | return False 53 | ## Python Solution 4: 54 | ## 左下角开始查找 55 | class Solution: 56 | def Find(self, nums, target): 57 | m = len(nums) 58 | if m == 0: 59 | return False 60 | n = len(nums[0]) 61 | i=m-1 62 | j=0 63 | while i>=0 and jtarget: 67 | i-=1 ##上移 68 | else: 69 | j+=1 ##右移 70 | return False 71 | -------------------------------------------------------------------------------- /TwoNumbersWithSum/TwoNumbersWithSum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector FindNumbersWithSum(vector nums,int target) { 4 | int n = nums.size(); 5 | vector res; 6 | if (nums.empty()) 7 | return res; 8 | for(int i=0;i twoSum(vector& numbers, int target) { 27 | vector res (2,0); 28 | if (numbers.empty()) 29 | return res; 30 | int n = numbers.size(); 31 | unordered_map record; 32 | for (int i=0;i FindNumbersWithSum(vector nums,int target) { 50 | vector res; 51 | if(nums.empty()) 52 | return res; 53 | int n =nums.size(); 54 | int left=0; 55 | int right=n-1; 56 | while (right>left) 57 | { 58 | if (nums[left]+nums[right]==target) 59 | { 60 | res.push_back(nums[left]); 61 | res.push_back(nums[right]); 62 | break; 63 | } 64 | if (nums[left]+nums[right]>target) 65 | { 66 | right--; 67 | } 68 | else 69 | left++; 70 | } 71 | return res; 72 | } 73 | }; 74 | -------------------------------------------------------------------------------- /QueueWithTwoStacks/README.md: -------------------------------------------------------------------------------- 1 | # 题目: 用两个栈实现队列 2 | ## 题目描述: 3 | 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。理解题意就是利用两个先进后出的栈实现一个先进先出的队列 4 | # 本题考点: 5 | 6 | 数据结构栈的编程能力 7 | 8 | # 解题思路: 9 | 理解题意后是要用两个“先进后出”的栈实现一个“先进先出”的队列,先将元素填进stack1,stack1.push(node),然后stack2为空,但stack1不为空,就将stack1的元素弹出,再压入栈2,这样先进的元素就在栈2顶,这样就实现了先进先出。就是先进后出+后进先出=先进先出。 10 | # 代码 11 | 12 | [C++](./QueueWithTwoStacks.cpp) 13 | 14 | [Python](./QueueWithTwoStacks.py) 15 | 16 | ## C++: 17 | ```c++ 18 | class MyQueue { 19 | public: 20 | MyQueue() { 21 | 22 | } 23 | 24 | void push(int x) { 25 | s1.push(x); 26 | } 27 | 28 | int pop() { 29 | int res = this->peek(); 30 | s2.pop(); 31 | return res; 32 | } 33 | 34 | int peek() { 35 | // 注意要加这个判断,因为有可能先加进去3个元素,只弹出一个 36 | // 后边再加元素,剩下的两个元素优先级还是最高 37 | if (s2.empty()) { 38 | while(!s1.empty()) { 39 | s2.push(s1.top()); 40 | s1.pop(); 41 | } 42 | } 43 | if (!s2.empty()) return s2.top(); 44 | return -1; 45 | } 46 | 47 | bool empty() { 48 | return s1.empty() && s2.empty(); 49 | } 50 | private: 51 | stack s1; 52 | stack s2; 53 | }; 54 | ``` 55 | 56 | ## Python: 57 | ```python 58 | # -*- coding:utf-8 -*- 59 | class MyQueue: 60 | 61 | def __init__(self): 62 | self.s1, self.s2 = [], [] 63 | 64 | def push(self, x: int) -> None: 65 | self.s1.append(x) 66 | 67 | def pop(self) -> int: 68 | peek = self.peek() 69 | self.s2.pop() 70 | return peek 71 | 72 | def peek(self) -> int: 73 | if not self.s2: 74 | while self.s1: 75 | self.s2.append(self.s1.pop()) 76 | if self.s2: 77 | return self.s2[-1] 78 | return -1 79 | 80 | def empty(self) -> bool: 81 | return (not self.s1) and (not self.s2) 82 | 83 | ``` 84 | ## 参考 85 | - [C++ stl容器stack栈pop用法](https://blog.csdn.net/l494926429/article/details/52066918) 86 | - [Python list pop()用法](https://www.runoob.com/python/att-list-pop.html) 87 | - [Python栈实现](https://www.jianshu.com/p/1327cc0de255) 88 | -------------------------------------------------------------------------------- /StreamMedian/StreamMedian.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | class Solution { 7 | public: 8 | int count = 0; // count要声明为全局变量 9 | void Insert(int num) { 10 | if (count % 2 == 0) // 偶数放入最大堆 11 | { 12 | max.push(num); 13 | int max_num = max.top(); 14 | max.pop(); 15 | min.push(max_num); 16 | } 17 | else // 奇数放入最小堆 18 | { 19 | min.push(num); 20 | int min_num = min.top(); 21 | min.pop(); 22 | max.push(min_num); 23 | } 24 | count++; 25 | } 26 | 27 | double GetMedian() { 28 | if (count % 2 == 0) 29 | { 30 | return ((max.top() + min.top()) / 2.0); 31 | } 32 | else 33 | { 34 | return (min.top()); 35 | } 36 | 37 | } 38 | private: 39 | priority_queue> max; //大顶堆 40 | priority_queue, greater> min; // 小顶堆 41 | }; 42 | 43 | int main() 44 | { 45 | Solution* obj = new Solution(); 46 | obj->Insert(5); 47 | obj->Insert(2); 48 | obj->Insert(3); 49 | double res = obj->GetMedian(); 50 | cout << res << endl; 51 | system("pause"); 52 | return 0; 53 | } 54 | 55 | // Solution 2: 56 | class Solution { 57 | public: 58 | vector store; 59 | void Insert(int num) 60 | { 61 | store.push_back(num); 62 | } 63 | 64 | double GetMedian() 65 | { 66 | sort(store.begin(), store.end()); 67 | int n = store.size(); 68 | if (n % 2 == 0) 69 | { 70 | return((store[n / 2] + store[n / 2 - 1]) / 2.0); 71 | } 72 | else 73 | { 74 | return (store[n / 2]); 75 | } 76 | } 77 | }; 78 | 79 | 80 | // Solution 3: 81 | class Solution { 82 | public: 83 | vector store; 84 | void Insert(int num) 85 | { 86 | if (store.empty()) 87 | store.push_back(num); 88 | else 89 | store.insert(lower_bound(store.begin(),store.end(),num),num); 90 | } 91 | 92 | double GetMedian() 93 | { 94 | int n = store.size(); 95 | if (n % 2 == 0) 96 | { 97 | return((store[n / 2] + store[n / 2 - 1]) / 2.0); 98 | } 99 | else 100 | { 101 | return (store[n / 2]); 102 | } 103 | } 104 | }; 105 | -------------------------------------------------------------------------------- /FindNthDigit/README.md: -------------------------------------------------------------------------------- 1 | # 题目:数字序列中某一位的数字 2 | ## 题目描述: 3 | 数字以0123456789101112131415…的格式序列化到一个字符序列中。在这个序列中,第5位(从下标0开始计数)是5,第13位是1,第19位是4,等等。 4 | 5 | 请写一个函数,求任意第n位对应的数字。 6 | 7 | **示例1:** 8 | ``` 9 | 输入:n = 3 10 | 输出:3 11 | ``` 12 | 13 | # 本题考点: 14 | 15 | 数学规律的发现,时间效率的提升。 16 | 17 | # 解题思路: 18 | 19 | ![](https://pic.leetcode-cn.com/4f913f7a795d55038dc3a480c8268d8cc3367b14cb0cb4a7ea0c9d23f26fff9b-1.png) 20 | 21 | 对于第 n 位对应的数字,我们令这个数字对应的数为 target,然后分三步进行。 22 | 23 | - 首先找到这个数字对应的数是几位数,用 digits 表示; 24 | - 然后确定这个对应的数的数值 target; 25 | - 最后确定返回值是 target 中的哪个数字。 26 | 27 | # 代码 28 | 29 | [C++](./FindNthDigit.cpp) 30 | 31 | [Python](./FindNthDigit.py) 32 | 33 | # C++: 34 | ### 35 | ```c++ 36 | class Solution { 37 | public: 38 | int findNthDigit(int n) { 39 | if (n<0) 40 | return -1; 41 | if (n<10) 42 | return n; 43 | int digits = 1; 44 | long number = 9; 45 | while (n>digits*number) 46 | { 47 | n-=digits*number; 48 | digits++; 49 | number*=10; 50 | } 51 | n-=1; // 计算时从1开始,但实际是从0开始,所以要减1 52 | int a = n / digits; 53 | int idx = n%digits; 54 | int num = int (pow(10, digits-1)) + a; 55 | int idxFromRight = digits-idx; 56 | for (int i=1;i int: 70 | if n<0: 71 | return -1 72 | if n<10: 73 | return n 74 | digits = 1 75 | numbers = 9 76 | while n>digits*numbers: 77 | n-=digits*numbers 78 | digits+=1 79 | numbers*=10 80 | n-=1 81 | a = n//digits 82 | b = n%digits 83 | num = int(pow(10,digits-1) + a) 84 | idx = digits-b 85 | for i in range(1, idx): 86 | num//=10 87 | return num%10 88 | # s = str(num) 89 | # res = int(s[b]) 90 | # return res 91 | ``` 92 | -------------------------------------------------------------------------------- /DeleteDuplicatedNode/DeleteDuplicatedNode.cpp: -------------------------------------------------------------------------------- 1 | // Solution 1: 2 | /* 3 | struct ListNode { 4 | int val; 5 | struct ListNode *next; 6 | ListNode(int x) : 7 | val(x), next(NULL) { 8 | } 9 | }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* deleteDuplication(ListNode* head) 14 | { 15 | if (head == NULL || head->next == NULL) 16 | return head; 17 | ListNode* p = new ListNode(-1); 18 | p->next = head; 19 | ListNode* prev = p; 20 | ListNode* cur = head; 21 | while(cur && cur->next) 22 | { 23 | if (cur->val == cur->next->val) 24 | { 25 | while(cur->next && cur->val == cur->next->val) 26 | { 27 | cur = cur->next; 28 | } 29 | prev->next = cur->next; 30 | } 31 | else 32 | { 33 | prev = cur; 34 | } 35 | cur = cur->next; 36 | } 37 | return p->next; 38 | } 39 | }; 40 | // Solution 2: 41 | /** 42 | * Definition for singly-linked list. 43 | * struct ListNode { 44 | * int val; 45 | * ListNode *next; 46 | * ListNode(int x) : val(x), next(NULL) {} 47 | * }; 48 | */ 49 | class Solution { 50 | public: 51 | ListNode* deleteDuplication(ListNode* head) { 52 | if(head==NULL || head->next == NULL) 53 | return head; 54 | //如果是这种情况 55 | // 1 --> 1 --> 1 --> 2 --> 3 56 | // head next 57 | //1.则需要移动next直到出现与当前head.value不相等的情况(含null) 58 | //2.并且此时的head已经不能要了,因为已经head是重复的节点 59 | //--------------else------------- 60 | // 1 --> 2 --> 3 61 | // head next 62 | //3.如果没有出现1的情况,则递归返回的节点就作为head的子节点 63 | if (head->val == head->next->val) 64 | { 65 | // 1 66 | while(head->next && head->val == head->next->val) 67 | { 68 | head = head->next; 69 | } 70 | // 2 71 | head = deleteDuplicates(head->next); 72 | } 73 | else 74 | { 75 | // 3 76 | head->next = deleteDuplicates(head->next); 77 | } 78 | return head; 79 | } 80 | }; 81 | -------------------------------------------------------------------------------- /Power/README.md: -------------------------------------------------------------------------------- 1 | # 题目: 数值的整数次方 2 | ## 题目描述: 3 | 实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。 4 | # 本题考点: 5 | 6 | 二进制与位运算的理解。 7 | 8 | # 解题思路: 9 | 方法一:直接根据定义暴力求解 10 | 11 | 方法二:使用折半计算,每次把n缩小一半,这样n最终会缩小到0,任何数的0次方都为1,这时候我们再往回乘,如果此时n是偶数,直接把上次递归得到的值算个平方返回即可,如果是奇数,则还需要乘上个x的值。还有一点需要引起我们的注意的是n有可能为负数,对于n是负数的情况,我们可以先用其绝对值计算出一个结果再取其倒数即可。我们让i初始化为n,然后看i是否是2的倍数,是的话x乘以自己,否则res乘以x,i每次循环缩小一半,直到为0停止循环。最后看n的正负,如果为负,返回其倒数 12 | 13 | ![](https://cuijiahua.com/wp-content/uploads/2017/11/basis_12_1.jpg) 14 | 15 | # 时间复杂度: 16 | 17 | 方法一:O(N) 18 | 19 | 方法二:O(log(N)) 20 | 21 | # 空间复杂度 22 | 方法一和方法二都为O(1) 23 | 24 | # 代码 25 | 26 | [C++](./Power.cpp) 27 | 28 | [Python](./Power.py) 29 | 30 | # C++: 31 | ### 32 | ```c++ 33 | class Solution { 34 | public: 35 | double Power(double x, int n) { 36 | double res = 1.0; 37 | for (int i=n;i!=0;i/=2) 38 | { 39 | if (i & 1 ==1) // 用位与运算符比取模更高效, (i%2!=0) 40 | { 41 | res*=x; 42 | } 43 | x*=x; 44 | } 45 | if (n<0) 46 | res = 1/res; 47 | return res; 48 | } 49 | }; 50 | ``` 51 | ### 完善版 52 | ```c++ 53 | class Solution { 54 | public: 55 | double Power(double x, int n) { 56 | long a = n; 57 | if (x==0 && n<0) 58 | return 0.0; 59 | double res = 1.0; 60 | // 负数的右移操作不是除2,所以要先转换成非负 61 | if (n<0) 62 | { 63 | x = 1/x; 64 | a=-a; 65 | } 66 | while(a!=0) 67 | { 68 | if (a&1==1) 69 | res *= x; 70 | x*=x; 71 | a = a>>1; 72 | } 73 | return res; 74 | } 75 | }; 76 | ``` 77 | # Python: 78 | ```python 79 | # -*- coding:utf-8 -*- 80 | class Solution: 81 | def Power(self, x, n): 82 | # write code here 83 | if x==0.0 and n<0: 84 | return 0.0 85 | res = 1.0 86 | if n <0: 87 | x=1.0/x 88 | n=-n 89 | while n: 90 | if n&1==1: 91 | res*=x 92 | x*=x 93 | n=n>>1 94 | return res 95 | ``` 96 | ## 参考 97 | - [LeetCode-50题-Pow(x, n)](https://github.com/bryceustc/LeetCode_Note/blob/master/cpp/PowX-N/README.md) 98 | -------------------------------------------------------------------------------- /StackPushPopOrder/README.md: -------------------------------------------------------------------------------- 1 | # 题目: 栈的压入、弹出元素 2 | ## 题目描述: 3 | 输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如,序列 {1,2,3,4,5} 是某栈的压栈序列,序列 {4,5,3,2,1} 是该压栈序列对应的一个弹出序列,但 {4,3,5,1,2} 就不可能是该压栈序列的弹出序列。 4 | # 本题考点: 5 | 6 | 数据结构栈的编程能力 7 | 8 | # 解题思路: 9 | 此题与LeetCode-946题一样 10 | 11 | 采用模拟法,借助一个辅助的栈,遍历压栈的顺序,依次放进辅助栈中。 12 | 13 | 对于每一个放进栈中的元素,栈顶元素都与出栈的popIndex对应位置的元素进行比较,是否相等,相等则popIndex++,再判断,直到为空或者不相等为止。 14 | 15 | 具体入栈出栈的操作模拟如下: 16 | ![1](https://github.com/bryceustc/CodingInterviews/blob/master/StackPushPopOrder/Images/1.png) 17 | 18 | ![2](https://github.com/bryceustc/CodingInterviews/blob/master/StackPushPopOrder/Images/2.png) 19 | # 代码 20 | 21 | [C++](./StackPushPopOrder.cpp) 22 | 23 | [Python](./StackPushPopOrder.py) 24 | 25 | # C++: 26 | ### 27 | ```c++ 28 | class Solution { 29 | public: 30 | bool IsPopOrder(vector pushV,vector popV) { 31 | int n = pushV.size(); 32 | int m = popV.size(); 33 | if (n!=m) return false; 34 | // 辅助栈 35 | stack s; 36 | //弹出序列的下表索引 37 | int index = 0; 38 | for (int i=0;i0 and s[-1]==popV[index]: 71 | s.pop() 72 | index+=1 73 | if len(s)==0: 74 | return True 75 | return False 76 | ``` 77 | ## 参考 78 | - [LeetCode-946题-最小栈](https://github.com/bryceustc/LeetCode_Note/blob/master/cpp/Validate-Stack-Sequences/README.md) 79 | - [Python栈实现](https://www.jianshu.com/p/1327cc0de255) 80 | 81 | 82 | -------------------------------------------------------------------------------- /FirstCommonNodesInLists/FirstCommonNodesInLists.cpp: -------------------------------------------------------------------------------- 1 | // C++ Solution 1: 2 | /* 3 | struct ListNode { 4 | int val; 5 | struct ListNode *next; 6 | ListNode(int x) : 7 | val(x), next(NULL) { 8 | } 9 | };*/ 10 | class Solution { 11 | public: 12 | ListNode* FindFirstCommonNode( ListNode* l1, ListNode* l2) { 13 | if (l1==NULL || l2 == NULL) return NULL; 14 | ListNode* p = l1; 15 | ListNode* q = l2; 16 | while(p) 17 | { 18 | q = l2; 19 | while(q) 20 | { 21 | if (p->val==q->val) 22 | { 23 | return p; 24 | } 25 | else 26 | { 27 | q = q->next; 28 | } 29 | } 30 | p = p->next; 31 | } 32 | return NULL; 33 | } 34 | }; 35 | // C++ Solution 2: 36 | /* 37 | struct ListNode { 38 | int val; 39 | struct ListNode *next; 40 | ListNode(int x) : 41 | val(x), next(NULL) { 42 | } 43 | };*/ 44 | class Solution { 45 | public: 46 | ListNode* FindFirstCommonNode( ListNode* l1, ListNode* l2) { 47 | if (l1==NULL || l2 == NULL) return NULL; 48 | ListNode* p = l1; 49 | ListNode* q = l2; 50 | int n=0,m=0; 51 | // 计算l1链表的长度 52 | while (p) 53 | { 54 | n++; 55 | p = p->next; 56 | } 57 | // 计算l2链表的长度 58 | while(q) 59 | { 60 | m++; 61 | q = q->next; 62 | } 63 | // 如果链表长度不一样,计算两个链表长度的差值 64 | int k = 0; 65 | ListNode* temp_long = l1; 66 | ListNode* temp_short = l2; 67 | if (n>=m) 68 | { 69 | k = n-m; 70 | } 71 | else 72 | { 73 | k = m-n; 74 | temp_long = l2; 75 | temp_short = l1; 76 | } 77 | // 长的链表先移动差值k,剩余长度与短链表的长度一致 78 | for (int i=0;inext; 81 | } 82 | // 然后同时移动,判断是否有公共节点 83 | while(temp_long && temp_short && temp_short!=temp_long) 84 | { 85 | temp_short = temp_short->next; 86 | temp_long = temp_long->next; 87 | } 88 | ListNode* res = temp_long; 89 | return res; 90 | } 91 | }; 92 | -------------------------------------------------------------------------------- /MinInStack/README.md: -------------------------------------------------------------------------------- 1 | # 题目: 包含min函数的栈 2 | ## 题目描述: 3 | 定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。 4 | # 本题考点: 5 | 6 | 数据结构栈的编程能力 7 | 8 | # 解题思路: 9 | 此题与LeetCode-155题一样 10 | 11 | 理解题意后是要用一个数据栈压入元素,另一个为辅助栈存储最小元素。 12 | 举个例子: 13 | 14 | 入栈的时候:首先往空的数据栈里压入数字3,显然现在3是最小值,我们也把最小值压入辅助栈。接下来往数据栈里压入数字4。由于4大于之前的最小值,因此我们只要入数据栈,不压入辅助栈。 15 | 16 | 出栈的时候:数据栈和辅助栈都出栈 17 | 18 | 获得栈顶元素的时候:直接返回数据栈的栈顶元素。 19 | 20 | 栈最小元素:直接返回辅助栈的栈顶元素。 21 | # 代码 22 | 23 | [C++](./MinInStack.cpp) 24 | 25 | [Python](./MinInStack.py) 26 | 27 | # C++: 28 | ### 29 | ```c++ 30 | class Solution { 31 | public: 32 | void push(int value) { 33 | stack1.push(value); 34 | if (stack2.empty() || value < stack2.top()) 35 | { 36 | stack2.push(value); 37 | } 38 | else 39 | { 40 | int t = stack2.top(); 41 | stack2.push(t); 42 | } 43 | } 44 | void pop() { 45 | stack1.pop(); 46 | stack2.pop(); 47 | } 48 | int top() { 49 | int a = stack1.top(); 50 | return a; 51 | } 52 | int min() { 53 | int b = stack2.top(); 54 | return b; 55 | } 56 | private: 57 | stack stack1; 58 | stack stack2; 59 | }; 60 | ``` 61 | 62 | # Python: 63 | ### 64 | ```python 65 | # -*- coding:utf-8 -*- 66 | class Solution: 67 | def __init__(self): 68 | self.stack1 = [] 69 | self.stack2 = [] 70 | def push(self, node): 71 | # write code here 72 | self.stack1.append(node) 73 | if len(self.stack2)==0 or node < self.stack2[-1]: 74 | self.stack2.append(node) 75 | else: 76 | temp = self.stack2[-1] 77 | self.stack2.append(temp) 78 | def pop(self): 79 | # write code here 80 | self.stack1.pop() 81 | self.stack2.pop() 82 | def top(self): 83 | # write code here 84 | return self.stack1[-1] 85 | def min(self): 86 | # write code here 87 | return self.stack2[-1] 88 | ``` 89 | ## 参考 90 | - [C++类成员的访问范围(C++ private、public、protected)](http://c.biancheng.net/view/219.html) 91 | - [LeetCode-155题-最小栈](https://github.com/bryceustc/LeetCode_Note/blob/master/cpp/Min-Stack/README.md) 92 | - [Python栈实现](https://www.jianshu.com/p/1327cc0de255) 93 | 94 | -------------------------------------------------------------------------------- /StringPermutation/StringPermutation.cpp: -------------------------------------------------------------------------------- 1 | ### C++ Solution 1: 2 | class Solution { 3 | public: 4 | vector Permutation(string str) { 5 | vector res; 6 | int n = str.size(); 7 | if (n==0) return res; 8 | // 数字排列时需要排序,不排序的话就重复了 9 | vector visited(n,0); 10 | string out = ""; 11 | DFS(str,res,0,visited,out); 12 | // 消除重复排列 13 | 14 | //unique只是去除(相邻)的重复元素,因此,为了去除重复的元素,应该,首先对数组/Vector进行排序,这样保证重复元素在相邻的位置。 15 | sort(res.begin(),res.end()); 16 | // unique()函数将重复的元素放到vector的尾部 然后返回指向第一个重复元素的迭代器再用erase函数擦除从这个元素到最后元素的所有的元素 17 | res.erase(unique(res.begin(),res.end()),res.end()); 18 | return res; 19 | } 20 | void DFS (string str,vector &res, int level, vector &visited,string &out) 21 | { 22 | int n = str.size(); 23 | if (level == n) 24 | { 25 | res.push_back(out); 26 | return; 27 | } 28 | for (int i=0;i=1 && str[i]==str[i-1]&&visited[i-1]==0) 31 | continue; 32 | if (visited[i]==1) 33 | continue; 34 | visited[i]=1; 35 | out += str[i]; 36 | DFS(str,res,level+1,visited,out); 37 | out.pop_back(); 38 | visited[i]=0; 39 | } 40 | } 41 | }; 42 | 43 | 44 | // C++ Solution 2: 45 | class Solution 46 | { 47 | public: 48 | vector Permutation(string str) { 49 | //判断输入 50 | if(str.length() == 0){ 51 | return result; 52 | } 53 | PermutationCore(str, 0); 54 | //对结果进行排序 55 | sort(result.begin(), result.end()); 56 | return result; 57 | } 58 | 59 | private: 60 | void PermutationCore(string str, int begin){ 61 | //递归结束的条件:第一位和最后一位交换完成 62 | int n = str.size(); 63 | if(begin == n) 64 | { 65 | result.push_back(str); 66 | return; 67 | } 68 | for(int i = begin; i < n; i++){ 69 | //如果字符串相同,则不交换 70 | if(i != begin && str[i] == str[begin]){ 71 | continue; 72 | } 73 | //位置交换 74 | swap(str[begin], str[i]); 75 | //递归调用,前面begin+1的位置不变,后面的字符串全排列 76 | PermutationCore(str, begin + 1); 77 | } 78 | } 79 | vector result; 80 | }; 81 | -------------------------------------------------------------------------------- /LastNumberInCircle/README.md: -------------------------------------------------------------------------------- 1 | ## 题目:圆圈中最后剩下的数字 2 | ### 题目描述: 3 | 0,1,···n-1这n个数字排成一个圆圈,从数字0开始,每次从这个圆圈里删除第m个数字。求出这个圆圈里剩下的最后一个数字。 4 | ## 本题考点: 5 | 6 | 约瑟夫环问题 7 | 8 | ## 解题思路: 9 | 10 | 1.) 模拟法 11 | 12 | 用数组列表模拟一下。创建一个数组存储0-n-1的数组,但数组长度大于1时,就计算end位置即为(start+m-1)%len(nums) ,删除该元素后然后start再等于之前end,最后数组中剩最后一个元素,返回nums[0] 13 | 14 | 时间复杂度O(n),空间复杂度O(n) 15 | 16 | 2.) 数学方法: 17 | 18 | 将上述问题建模为函数 f(n, m),该函数的返回值为最终留下的元素的序号。 19 | 20 | 每删除一个元素,下一个元素成为最开始的头,相当于把数组向前移动m位。若已知n-1个人时,删除下标位置位f(n−1,m),则n个人的时候,就是往后移动m位,(因为有可能数组越界,超过的部分会被接到头上,所以还要模n),既f(n,m) = (f(n-1,m) + m) % n 21 | 22 | 递归公式为:$f(n, m)=(f(n-1, m)+m) \\% n$ 23 | 24 | 时间复杂度O(n),空间复杂度O(n) 25 | ## 代码 26 | 27 | [C++](./LastNumberInCircle.cpp) 28 | 29 | [Python](./LastNumberInCircle.py) 30 | 31 | ### C++: 32 | #### 方法一:模拟法 33 | ```c++ 34 | #include 35 | #include 36 | using namespace std; 37 | 38 | class Solution { 39 | public: 40 | int LastRemaining_Solution(int n, int m) 41 | { 42 | int res =-1; 43 | if (n<=0 || m<=0) 44 | return res; 45 | vector nums; 46 | for (int i=0;i1) 52 | { 53 | int end = (start+m-1)%(nums.size()); 54 | nums.erase(nums.begin()+end); // vector插入删除操作时间复杂度是O(n) 55 | start = end; 56 | } 57 | res = nums[0]; 58 | return res; 59 | } 60 | }; 61 | 62 | int main() 63 | { 64 | int n = 5; 65 | int m = 3; 66 | int res = 0; 67 | res = Solution().LastRemaining_Solution(n,m); 68 | cout <& nums) { 4 | int n = nums.size(); 5 | int res = 0; 6 | if (nums.empty()) 7 | return 0; 8 | unordered_map map; 9 | for (int i=0;i& nums) { 25 | int res = 0; 26 | int n = nums.size(); 27 | unordered_set set; 28 | for(auto num : nums) 29 | { 30 | set.insert(num); 31 | } 32 | for (int i=0;i<=n;i++) 33 | { 34 | if (set.count(i)==0) 35 | { 36 | res = i; 37 | break; 38 | } 39 | } 40 | return res; 41 | } 42 | }; 43 | // C++ Solution 2: 44 | class Solution { 45 | public: 46 | int missingNumber(vector& nums) { 47 | int res =0; 48 | int n = nums.size(); 49 | int sum_num = 0; 50 | int Sum = 0; 51 | for (int i=0;i& nums) { 68 | int n = nums.size(); 69 | int res = n; 70 | for (int i = 0; i < n; i++) 71 | { 72 | res ^= nums[i]; 73 | res ^= i; 74 | // 异或满足交换律,i和nums[i]是肯定有重复的,剩下的只有一个那就是nums中缺失的 75 | } 76 | return res; 77 | } 78 | }; 79 | // C++ Solution 3: 80 | class Solution { 81 | public: 82 | int missingNumber(vector& nums) { 83 | sort(nums.begin(),nums.end()); 84 | int n = nums.size(); 85 | int res = 0; 86 | if (nums[n-1]!=n) 87 | { 88 | return n; 89 | } 90 | for (int i=0;i=rows or j<0 or j>=cols or matrix[index]!=path[k] or visited[i][j]==1: 16 | return False 17 | if k==len(path)-1: 18 | return True 19 | visited[i][j]=1 20 | if self.dfs(matrix, rows, cols, i-1, j, path, k+1, visited): 21 | return True 22 | if self.dfs(matrix, rows, cols, i+1, j, path, k+1, visited): 23 | return True 24 | if self.dfs(matrix, rows, cols, i, j-1, path, k+1, visited): 25 | return True 26 | if self.dfs(matrix, rows, cols, i, j+1, path, k+1, visited): 27 | return True 28 | visited[i][j]=0 29 | return False 30 | ## Solution 2: 31 | class Solution: 32 | def exist(self, board: List[List[str]], word: str) -> bool: 33 | if board == None: 34 | return False 35 | rows = len(board) 36 | cols = len(board[0]) 37 | visited = [[0 for x in range(cols)] for y in range(rows)] 38 | for i in range(rows): 39 | for j in range(cols): 40 | if self.dfs(board, rows, cols, i, j, word, 0, visited): 41 | return True 42 | return False 43 | def dfs(self, board, rows, cols, i, j, word, k, visited): 44 | if i<0 or i>=rows or j<0 or j>=cols or board[i][j]!=word[k] or visited[i][j]==1: 45 | return False 46 | if k==len(word)-1: 47 | return True 48 | visited[i][j]=1 49 | if self.dfs(board, rows, cols, i-1, j, word, k+1, visited): 50 | return True 51 | if self.dfs(board, rows, cols, i+1, j, word, k+1, visited): 52 | return True 53 | if self.dfs(board, rows, cols, i, j-1, word, k+1, visited): 54 | return True 55 | if self.dfs(board, rows, cols, i, j+1, word, k+1, visited): 56 | return True 57 | visited[i][j]=0 58 | return False 59 | -------------------------------------------------------------------------------- /ContinousCards/README.md: -------------------------------------------------------------------------------- 1 | # 题目描述:扑克牌顺子 2 | ## 题目: 3 | LL今天心情特别好,因为他去买了一副扑克牌,发现里面居然有2个大王,2个小王(一副牌原本是54张)... 他随机从中抽出了5张牌,想测测自己的手气,看看能不能抽到顺子,如果抽到的话,他决定去买体育彩票,嘿嘿!!“红心A,黑桃3,小王,大王,方片5”,“Oh My God!”不是顺子.....LL不高兴了,他想了想,决定大\小 王可以看成任何数字,并且A看作1,J为11,Q为12,K为13。上面的5张牌就可以变成“1,2,3,4,5”(大小王分别看作2和4),“So Lucky!”。LL决定去买体育彩票啦。 现在,要求你使用这幅牌模拟上面的过程,然后告诉我们LL的运气如何, 如果牌能组成顺子就输出true,否则就输出false。为了方便起见,你可以认为大小王是0。 4 | # 本题考点: 5 | 6 | 1). 双指针 7 | 8 | # 解题思路: 9 | 10 | 1.) 注意理解题意,输入为5个数字的数组,判断是否是一个顺子序列。以大小王为0,0可以代替任何数字。先对序列进行排序,然后算数组中0的个数,然后计算差值,如果后面一个数比前面一个数大于1以上,那么中间的差值就必须用0来补了,计算数组空缺总数,如果空缺总数大于0的个数,不是顺子,否则是顺子。注意如果5张牌发现有 对子,肯定不是顺子 11 | 时间复杂度:O(n),空间复杂度:O(n) 12 | 13 | # 代码 14 | 15 | [C++](./ContinousCards.cpp) 16 | 17 | [Python](./ContinousCards.py) 18 | 19 | # C++: 20 | ```c++ 21 | #include 22 | #include 23 | #include 24 | using namespace std; 25 | 26 | class Solution { 27 | public: 28 | bool IsContinuous( vector nums ) { 29 | int n = nums.size(); 30 | if (nums.empty()|| n!=5) 31 | return false; 32 | sort(nums.begin(),nums.end()); 33 | int numZero = 0; 34 | int gap = 0; 35 | for (int i=0;i nums = {1,3,0,7,0}; 53 | bool res; 54 | res = Solution().IsContinuous(nums); 55 | cout << res << endl; 56 | system("pause"); 57 | return 0; 58 | } 59 | ``` 60 | 61 | # Python: 62 | ```python 63 | # -*- coding:utf-8 -*- 64 | class Solution: 65 | def IsContinuous(self, nums): 66 | # write code here 67 | n = len(nums) 68 | if nums is None or n!=5: 69 | return False 70 | nums = sorted(nums) 71 | numZero = 0 72 | gap = 0 73 | for num in nums: 74 | if num ==0: 75 | numZero+=1 76 | for i in range(numZero,n-1): 77 | j=i+1 78 | if nums[j]==nums[i]: 79 | return False 80 | gap += nums[j]-nums[i]-1 81 | if gap > numZero: 82 | return False 83 | return True 84 | 85 | if __name__ == '_ main__': 86 | nums = [1,3,0,7,0] 87 | res = Solution().IsContinuous(nums) 88 | print(res) 89 | ``` 90 | -------------------------------------------------------------------------------- /StreamMedian/StreamMedian.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | import heapq 3 | class Solution: 4 | def __init__(self): 5 | self.count = 0 6 | self.max_heap = [] 7 | self.min_heap = [] 8 | def Insert(self, num): 9 | # write code here 10 | if self.count % 2 == 0: 11 | heapq.heappush(self.max_heap,-num) 12 | max_heap_top = heapq.heappop(self.max_heap) 13 | heapq.heappush(self.min_heap,-max_heap_top) 14 | else: 15 | heapq.heappush(self.min_heap,num) 16 | min_heap_top = heapq.heappop(self.min_heap) 17 | heapq.heappush(self.max_heap,-min_heap_top) 18 | self.count+=1 19 | def GetMedian(self, data): 20 | # write code here 21 | if self.count % 2 == 0: 22 | return(self.min_heap[0]-self.max_heap[0])/2.0 23 | else: 24 | return self.min_heap[0] 25 | 26 | if __name__ == '_ main__': 27 | nums = [4,5,1] 28 | 29 | Solution().Insert(num[0]) 30 | res = Solution().GetMedian() 31 | print(res) 32 | Solution().Insert(num[1]) 33 | res = Solution().GetMedian() 34 | print(res) 35 | Solution().Insert(num[2]) 36 | res = Solution().GetMedian() 37 | print(res) 38 | 39 | 40 | ### Solution 2: 41 | 42 | class Solution: 43 | def __init__(self): 44 | self.store=[] 45 | def Insert(self, num): 46 | # write code here 47 | self.store.append(num) 48 | def GetMedian(self, data): 49 | # write code here 50 | store=sorted(self.store) 51 | n = len(self.store) 52 | if n%2==0: 53 | return (self.store[n//2]+self.store[n//2-1])/2.0 54 | else: 55 | return self.store[n//2] 56 | 57 | ### Solution 3: 58 | 59 | 60 | class Solution: 61 | def __init__(self): 62 | self.store=[] 63 | def insertSort(self,arr): 64 | for i in range(1,len(arr)): 65 | j = i-1 66 | key = arr[i] 67 | while j >= 0: 68 | if arr[j] > key: 69 | arr[j+1] = arr[j] 70 | arr[j] = key 71 | j -= 1 72 | return arr 73 | def Insert(self, num): 74 | # write code here 75 | self.store.append(num) 76 | self.store = self.insertSort(self.store) 77 | def GetMedian(self, data): 78 | # write code here 79 | n = len(self.store) 80 | if n%2==0: 81 | return (self.store[n//2]+self.store[n//2-1])/2.0 82 | else: 83 | return self.store[n//2] 84 | -------------------------------------------------------------------------------- /StringToInt/StringToInt.py: -------------------------------------------------------------------------------- 1 | ## Solution 2 | # -*- coding:utf-8 -*- 3 | class Solution: 4 | def StrToInt(self, s): 5 | # write code here 6 | res = 0 7 | n = len(s) 8 | if n==0: 9 | return 0 10 | flag = 1 11 | if s[0]=='-': 12 | flag = -1 13 | for i in range(n): 14 | if s[i]=='+' or s[i]=='-' and i==0: 15 | continue 16 | if s[i]=='+' or s[i]=='-' and i!=0: 17 | return 0 18 | if s[i]>='0' and s[i]<='9': 19 | temp = int (ord(s[i])-ord('0')) 20 | res = res*10+temp 21 | else: 22 | return 0 23 | res *= flag 24 | if res > 2147483647 or res < -2147483648: 25 | return 0 26 | return res 27 | ## Solution 2: 28 | # -*- coding:utf-8 -*- 29 | class Solution: 30 | def StrToInt(self, s): 31 | # write code here 32 | res = 0 33 | n = len(s) 34 | flag = 1 35 | if n==0: 36 | return 0 37 | i = 0 38 | while i='0' and s[j]<='9'): 49 | temp = int(ord(s[j])-ord('0')) 50 | res = res*10 + temp 51 | else: 52 | return 0 53 | res*=flag 54 | if res > 2147483647 or res < -2147483648: 55 | return 0 56 | return res 57 | ## Solution 3: 58 | # -*- coding:utf-8 -*- 59 | class Solution: 60 | def StrToInt(self, s): 61 | # write code here 62 | numlist=['0','1','2','3','4','5','6','7','8','9','+','-'] 63 | res=0 64 | label=1#正负数标记 65 | if s=='': 66 | return 0 67 | for string in s: 68 | if string in numlist:#如果是合法字符 69 | if string=='+': 70 | label=1 71 | continue 72 | if string=='-': 73 | label=-1 74 | continue 75 | else: 76 | res=res*10+numlist.index(string) 77 | if string not in numlist:#非合法字符 78 | res=0 79 | break#跳出循环 80 | res*=label 81 | if res > 2147483647 or res < -2147483648: 82 | return 0 83 | return res 84 | -------------------------------------------------------------------------------- /MirrorOfBinaryTree/README.md: -------------------------------------------------------------------------------- 1 | 2 | # 题目: 二叉树的镜像 3 | ## 题目描述: 4 | 请完成一个函数,输入一个二叉树,该函数输出它的镜像。 5 | 6 | 例如输入: 7 | ``` 8 | 8 9 | / \ 10 | 6 10 11 | / \ / \ 12 | 5 7 9 11 13 | ``` 14 | 镜像输出: 15 | ``` 16 | 8 17 | / \ 18 | 10 9 19 | / \ / \ 20 | 11 9 7 5 21 | ``` 22 | # 本题考点: 23 | 24 | 二叉树的遍历算法和递归编程能力,代码的鲁棒性。 25 | 26 | # 解题思路: 27 | 此题与LeetCode226题翻转二叉树类似。 28 | 29 | 思路:先交换根节点的两个子结点之后,我们注意到值为10、6的结点的子结点仍然保持不变,因此我们还需要交换这两个结点的左右子结点。做完这两次交换之后,我们已经遍历完所有的非叶结点。此时变换之后的树刚好就是原始树的镜像。交换示意图如下所示: 30 | 31 | ![1](https://github.com/bryceustc/CodingInterviews/blob/master/MirrorOfBinaryTree/Images/1.png) 32 | # 代码 33 | 34 | [C++](./MirrorOfBinaryTree.cpp) 35 | 36 | [Python](./MirrorOfBinaryTree.py) 37 | 38 | # C++: 39 | ### 40 | ```c++ 41 | /* 42 | struct TreeNode { 43 | int val; 44 | struct TreeNode *left; 45 | struct TreeNode *right; 46 | TreeNode(int x) : 47 | val(x), left(NULL), right(NULL) { 48 | } 49 | };*/ 50 | class Solution { 51 | public: 52 | void Mirror(TreeNode *root) { 53 | if (root ==NULL) 54 | return; 55 | //交换根节点的左右结点 56 | TreeNode* temp = root->left; 57 | root->left = root->right; 58 | root->right =temp; 59 | 60 | //递归左子树 61 | if (root->left) 62 | Mirror(root->left); 63 | 64 | //递归右子树 65 | if (root->right) 66 | Mirror(root->right); 67 | } 68 | }; 69 | 70 | class Solution { 71 | public: 72 | TreeNode* mirrorTree(TreeNode* root) { 73 | if (root==NULL) 74 | return root; 75 | TreeNode* temp = root->left; 76 | root->left = mirrorTree(root->right); 77 | root->right = mirrorTree(temp); 78 | return root; 79 | } 80 | }; 81 | ``` 82 | 83 | # Python: 84 | ### 85 | ```python 86 | # -*- coding:utf-8 -*- 87 | # class TreeNode: 88 | # def __init__(self, x): 89 | # self.val = x 90 | # self.left = None 91 | # self.right = None 92 | class Solution: 93 | # 返回镜像树的根节点 94 | def Mirror(self, root): 95 | # write code here 96 | if root == None: 97 | return 98 | temp = root.left 99 | root.left = root.right 100 | root.right = temp 101 | if root.left: 102 | self.Mirror(root.left) 103 | if root.right: 104 | self.Mirror(root.right) 105 | ``` 106 | ## 参考 107 | - [LeetCode-226-翻转二叉树](https://github.com/bryceustc/LeetCode_Note/blob/master/cpp/Invert-Binary-Tree/README.md) 108 | 109 | -------------------------------------------------------------------------------- /PrintListInReversedOrder/PrintListInReversedOrder.cpp: -------------------------------------------------------------------------------- 1 | // Solution 1: 2 | /** 3 | * struct ListNode { 4 | * int val; 5 | * struct ListNode *next; 6 | * ListNode(int x) : 7 | * val(x), next(NULL) { 8 | * } 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | vector printListFromTailToHead(ListNode* head) { 14 | vector res; 15 | ListNode* p = head; 16 | if (p==NULL) return res; 17 | while(p!=NULL) 18 | { 19 | res.push_back(p->val); 20 | p = p->next; 21 | } 22 | // 逆序方法1:利用c++自带的库函数reverse 23 | reverse(res.begin(),res.end()); 24 | 25 | // 逆序方法2:利用for循环 26 | // vector temp; 27 | // for (int i=res.size()-1;i>=0;i--) 28 | //{ 29 | // temp.push_back(res[i]); 30 | //} 31 | // return temp; 32 | 33 | // 逆序方法3:vector迭代器 34 | //for (vector::reverse_iterator it = res.rbegin(); it!= res.rend(); it++) 35 | { 36 | // temp.push_back(*it); 37 | //} 38 | // return temp; 39 | 40 | // 逆序方法4:栈 41 | //std::stack nodes; 42 | //ListNode *pNode = head; 43 | //while(pNode!=NULL) 44 | //{ 45 | // nodes.push(pNode); 46 | // pNode = pNode->next; 47 | //} 48 | //while(!nodes.empty()) 49 | //{ 50 | // pNode = nodes.top(); 51 | // temp.push_back(pNode->val); 52 | // nodes.pop(); 53 | //} 54 | // return temp; 55 | return res; 56 | } 57 | }; 58 | 59 | // Solution 2: 60 | /** 61 | * struct ListNode { 62 | * int val; 63 | * struct ListNode *next; 64 | * ListNode(int x) : 65 | * val(x), next(NULL) { 66 | * } 67 | * }; 68 | */ 69 | class Solution { 70 | public: 71 | vector printListFromTailToHead(ListNode* head) { 72 | vector res; 73 | if (head==NULL) 74 | return res; 75 | ListNode* prev = head; 76 | ListNode* cur = head->next; 77 | ListNode* temp = head->next->next; 78 | while(cur) 79 | { 80 | temp = cur->next;//temp作为中间节点,记录当前结点的下一个节点的位置 81 | cur->next = prev;//当前结点指向前一个节点 82 | prev = cur;//指针后移 83 | cur = temp;// 指针后移,处理下一个节点 84 | } 85 | head->next = NULL; //while结束后,将翻转后的最后一个节点(即翻转前的第一个结点head)的链域置为NULL 86 | while(prev) 87 | { 88 | res.push_back(prev->val); 89 | prev = prev->next; 90 | } 91 | return res; 92 | } 93 | }; 94 | -------------------------------------------------------------------------------- /UglyNumber/UglyNumber.cpp: -------------------------------------------------------------------------------- 1 | // C++ Solution 1: 2 | class Solution { 3 | public: 4 | bool isUgly(int num) 5 | { 6 | if (num < 1) 7 | return false; 8 | while (num % 5 == 0) 9 | { 10 | num /= 5; 11 | } 12 | while (num % 3 == 0) 13 | { 14 | num /= 3; 15 | } 16 | while (num % 2 == 0) 17 | { 18 | num /= 2; 19 | } 20 | return num == 1; 21 | } 22 | int GetUglyNumber_Solution(int index) { 23 | if (index < 0) 24 | return 0; 25 | int i = 0; 26 | int number = 0; 27 | while (idp (n,0); 46 | dp[0]=1; 47 | int l_2 = 0; 48 | int l_3 = 0; 49 | int l_5 = 0; 50 | for (int i=1;i,greater> min; 81 | //priority_queueType为数据类型,Container为保存数据的容器,Functional为元素比较方式。 如果不写后两个 // 参数,那么容器默认用的是vector,比较方式默认用operator< 82 | min.push(1); 83 | long long int res = 0; 84 | long long int num = 0; 85 | for (int i=0;i res; 4 | vector printNumbers(int n) { 5 | if (n<=0) return res; 6 | //创建一个能容纳最大值的字符数组 初始全部设置为0 7 | string number(n+1, '0'); 8 | while(!Increment(number)) 9 | { 10 | saveNumber(number); 11 | } 12 | return res; 13 | } 14 | bool Increment(string &number) 15 | { 16 | int carry = 0; 17 | int m = number.size(); 18 | for (int i=m- 1; i>=0;i--) 19 | { 20 | int temp = number[i] - '0' + carry; 21 | if (i==m-1) 22 | { 23 | temp++; 24 | } 25 | carry = temp/10; 26 | temp %=10; 27 | number[i] = temp+ '0'; 28 | } 29 | return number[0]=='1';// 判断是否溢出 30 | } 31 | void saveNumber (string number) //由于此处输出,不需要修改number,因此不需要加引用 32 | { 33 | string s = ""; 34 | int index = 0; 35 | // 找到第一不为'0'的位数 36 | for (;index res; 60 | vector printNumbers(int n) { 61 | if (n<=0) return res; 62 | string number(n, '0'); 63 | helper(0, n, number); 64 | return res; 65 | } 66 | void helper(int index, int n, string &number) 67 | { 68 | if (index == n) 69 | { 70 | saveNumber(number); 71 | return; 72 | } 73 | for (int i=0;i<=9;i++) 74 | { 75 | number[index] = i +'0'; 76 | helper(index+1, n, number); 77 | } 78 | } 79 | void saveNumber (string number) //由于此处输出,不需要修改number,因此不需要加引用 80 | { 81 | string s = ""; 82 | int index = 0; 83 | // 找到第一不为'0'的位数 84 | for (;index m;``,Insert函数是插入一个ch字符,那么对应就是string操作就是``s+=ch;``,然后再用哈希表进行操作,``m[ch]++;``,再遍历字符串s,判断第一个只出现一次的字符。 16 | 17 | 时间复杂度为O(n),空间复杂度O(n)。 18 | # 代码 19 | 20 | [C++](./FirstCharacterInStream.cpp) 21 | 22 | [Python](./FirstCharacterInStream.py) 23 | 24 | # C++: 25 | ### 方法一:哈希表,时间复杂度O(n) 26 | ```c++ 27 | class Solution 28 | { 29 | public: 30 | //Insert one char from stringstream 31 | unordered_map m; 32 | string s; 33 | void Insert(char ch) 34 | { 35 | s += ch; 36 | m[ch]++; 37 | } 38 | //return the first appearence once char in current stringstream 39 | char FirstAppearingOnce() 40 | { 41 | char res = '#'; 42 | int n = s.size(); 43 | for (int i=0;inext != NULL) 39 | { 40 | ListNode* p = ToBeDeleted->next; 41 | ToBeDeleted->val = p->val; 42 | ToBeDeleted->next = p->next; 43 | delete p; 44 | p = NULL; 45 | } 46 | // 链表只有一个节点,既是头结点,又是尾节点 47 | if (head == ToBeDeleted) 48 | { 49 | delete ToBeDeleted; 50 | ToBeDeleted = NULL; 51 | head = NULL; 52 | } 53 | // 链表中有多个节点,删除尾节点 54 | else 55 | { 56 | ListNode* p = head; 57 | while(p->next) 58 | { 59 | if (p->next != ToBeDeleted) 60 | { 61 | p = p->next; 62 | } 63 | p->next = NULL; 64 | delete ToBeDeleted; 65 | ToBeDeleted = NULL; 66 | } 67 | } 68 | } 69 | ``` 70 | # Python: 71 | ### 方法一:直接法 72 | ```python 73 | # -*- coding:utf-8 -*- 74 | # class ListNode: 75 | # def __init__(self, x): 76 | # self.val = x 77 | # self.next = None 78 | class Solution: 79 | def DeleteNode(self, head,tobedeleted): 80 | # write code here 81 | if head==None or tobedeleted == None: 82 | return 83 | ### 非尾节点 84 | if tobedeleted.next!= None: 85 | tobedeleted.val = tobedeleted.next.val 86 | tobedeleted.next = tobedeleted.next.next 87 | ## 链表只有一个节点,既是头结点,又是尾节点 88 | if head == tobedeleted: 89 | tobedeleted = None 90 | head = None 91 | p = head 92 | while p.next: 93 | if p.next!=None: 94 | p=p.next 95 | p.next = None 96 | ``` 97 | ## 参考 98 | - [LeetCode—203题—移除链表元素](https://github.com/bryceustc/LeetCode_Note/tree/master/cpp/Remove-Linked-List-Elements) 99 | -------------------------------------------------------------------------------- /MaxInSlidingWindow/README.md: -------------------------------------------------------------------------------- 1 | # 题目:滑动窗口的最大值 2 | 3 | ## 题目描述: 4 | 给定一个数组 nums 和滑动窗口的大小 k,请找出所有滑动窗口里的最大值。 5 | 6 | **示例:** 7 | ``` 8 | 输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3 9 | 输出: [3,3,5,5,6,7] 10 | 解释: 11 | 12 | 滑动窗口的位置 最大值 13 | --------------- ----- 14 | [1 3 -1] -3 5 3 6 7 3 15 | 1 [3 -1 -3] 5 3 6 7 3 16 | 1 3 [-1 -3 5] 3 6 7 5 17 | 1 3 -1 [-3 5 3] 6 7 5 18 | 1 3 -1 -3 [5 3 6] 7 6 19 | 1 3 -1 -3 5 [3 6 7] 7 20 | ``` 21 | 22 | # 解题思路: 23 | 我们可以使用一个双端队列deque。 24 | 25 | 我们可以用STL中的deque来实现,接下来我们以数组{2,3,4,2,6,2,5,1}为例,来细说整体思路。 26 | 27 | 数组的第一个数字是2,把它存入队列中。第二个数字是3,比2大,所以2不可能是滑动窗口中的最大值,因此把2从队列里删除,再把3存入队列中。第三个数字是4,比3大,同样的删3存4。此时滑动窗口中已经有3个数字,而它的最大值4位于队列的头部。 28 | 29 | 第四个数字2比4小,但是当4滑出之后它还是有可能成为最大值的,所以我们把2存入队列的尾部。下一个数字是6,比4和2都大,删4和2,存6。就这样依次进行,最大值永远位于队列的头部。 30 | 31 | 但是我们怎样判断滑动窗口是否包括一个数字?应该在队列里存入数字在数组里的下标,而不是数值。当一个数字的下标与当前处理的数字的下标之差大于或者相等于滑动窗口大小时,这个数字已经从窗口中滑出,可以从队列中删除。 32 | 33 | 整体过程示意图: 34 | 35 | ![](https://cuijiahua.com/wp-content/uploads/2018/02/basis_64_2.png) 36 | 37 | # 时间复杂度: 38 | O(n) 39 | # 空间复杂度 40 | O(1) 41 | # 代码 42 | 43 | [C++](./MaxInSlidingWindow.cpp) 44 | 45 | [Python](./MaxInSlidingWindow.py) 46 | 47 | # C++: 48 | ### 49 | ```c++ 50 | class Solution { 51 | public: 52 | vector maxSlidingWindow(vector& nums, int k) { 53 | vector res; 54 | if (nums.empty()) 55 | return res; 56 | int n = nums.size(); 57 | //deque q中存储的是num的下标 58 | deque q; 59 | for(int i=0;inums[q.back()]) // 因为q中存的是下标,如果当前nums[i]更大,就从后面弹出队列中比num[i]小的元素 62 | { 63 | q.pop_back(); 64 | } 65 | // 队列首部的下标超出滑动窗口范畴时就无效了 弹出 66 | while(!q.empty() && i-q.front()+1>k) 67 | { 68 | q.pop_front(); 69 | } 70 | // 压入下标 71 | q.push_back(i); 72 | // 当下标大于滑动窗口的时候 才会滑动 压入结果 73 | if(i>=k-1) 74 | { 75 | res.push_back(nums[q.front()]); 76 | } 77 | } 78 | return res; 79 | } 80 | }; 81 | ``` 82 | # Python: 83 | ### 84 | ```python 85 | class Solution: 86 | def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: 87 | res = [] 88 | if nums is None: 89 | return res 90 | q = collections.deque() 91 | n = len(nums) 92 | for i in range(n): 93 | while q and nums[i] > nums[q[-1]]: 94 | q.pop() 95 | while q and i-q[0]+1 > k: 96 | q.popleft() 97 | q.append(i) 98 | if i>=k-1: 99 | res.append(nums[q[0]]) 100 | return res 101 | ``` 102 | 103 | 104 | -------------------------------------------------------------------------------- /NumberOf1InBinary/README.md: -------------------------------------------------------------------------------- 1 | # 题目: 二进制中1的个数 2 | ## 题目描述: 3 | 请实现一个函数,输入一个整数,输出该数二进制表示中 1 的个数。例如,把 9 表示成二进制是 1001,有 2 位是 1。因此,如果输入 9,则该函数输出 2。 4 | # 本题考点: 5 | 6 | 二进制与位运算的理解。 7 | 8 | # 解题思路: 9 | 10 | 根据 与运算 定义,设二进制数字 n ,则有: 11 | - 若 n&1=0 ,则 n 二进制 最右一位 为 0 12 | - 若 n&1=1 ,则 n 二进制 最右一位 为 1 13 | 14 | 如果一个整数不为0,那么这个整数至少有一位是1。如果我们把这个整数减1,那么原来处在整数最右边的1就会变为0,原来在1后面的所有的0都会变成1(如果最右边的1后面还有0的话)。其余所有位将不会受到影响。 15 | 16 | 举个例子:一个二进制数1100,从右边数起第三位是处于最右边的一个1。减去1后,第三位变成0,它后面的两位0变成了1,而前面的1保持不变,因此得到的结果是1011.我们发现减1的结果是把最右边的一个1开始的所有位都取反了。这个时候如果我们再把原来的整数和减去1之后的结果做与运算,从原来整数最右边一个1那一位开始所有位都会变成0。如1100&1011=1000.也就是说,把一个整数减去1,再和原整数做与运算,会把该整数最右边一个1变成0.那么一个整数的二进制有多少个1,就可以进行多少次这样的操作。 17 | 18 | 如图所示: 19 | ![](https://pic.leetcode-cn.com/abfd6109e7482d70d20cb8fc1d632f90eacf1b5e89dfecb2e523da1bcb562f66-image.png) 20 | 21 | # 代码 22 | 23 | [C++](./NumberOf1InBinary.cpp) 24 | 25 | [Python](./NumberOf1InBinary.py) 26 | 27 | # C++: 28 | ### 尝试一:只能通过正数情况,负数右移不是除以2,未通过OJ 29 | ```c++ 30 | class Solution { 31 | public: 32 | int NumberOf1(int n) { 33 | int count = 0; 34 | while(n!=0) 35 | { 36 | if (n&1==1) 37 | count++; 38 | n = n>>1; 39 | } 40 | return count; 41 | } 42 | }; 43 | ``` 44 | ### 数字右移不行,换个思路,1左移 45 | ```c++ 46 | class Solution { 47 | public: 48 | int NumberOf1(int n) { 49 | int count = 0; 50 | unsigned int flag = 1; 51 | // 循环次数等于二进制整数的位数 52 | while(flag) 53 | { 54 | if (n&flag) 55 | count++; 56 | flag = flag << 1; 57 | } 58 | return count; 59 | } 60 | }; 61 | ``` 62 | ### 最优解法 63 | ```c++ 64 | class Solution { 65 | public: 66 | int NumberOf1(int n) { 67 | int count = 0; 68 | while(n) 69 | { 70 | count++; 71 | n = (n-1)&n; 72 | } 73 | return count; 74 | } 75 | }; 76 | ``` 77 | 在Python中,由于负数使用补码表示的,对于负数,最高位为1,而负数在计算机是以补码存在的,往右移,符号位不变,符号位1往右移,最终可能会出现全1的情况,导致死循环。与0xffffffff相与,去掉负数前面的负号,就可以消除负数的影响。[Python 对于负数的存储方式和 c++/c/java 不一样](https://www.runoob.com/w3cnote/python-negative-storage.html) 78 | # Python: 79 | ```python 80 | # -*- coding:utf-8 -*- 81 | class Solution: 82 | def NumberOf1(self, n): 83 | # write code here 84 | count = 0 85 | if n<0: 86 | n = n & 0xffffffff 87 | while n: 88 | count += 1 89 | n = n & (n-1) 90 | return count 91 | ``` 92 | ```python 93 | Python 94 | # -*- coding:utf-8 -*- 95 | class Solution: 96 | def NumberOf1(self, n): 97 | # write code here 98 | return sum([(n >> i & 1) for i in range(0,32)]) 99 | ``` 100 | ## 参考 101 | - [LeetCode-191题-位1的个数](https://github.com/bryceustc/LeetCode_Note/blob/master/cpp/Number-Of-1-Bits/README.md) 102 | -------------------------------------------------------------------------------- /MaxQueue/README.md: -------------------------------------------------------------------------------- 1 | # 题目:队列的最大值 2 | 3 | ## 题目描述: 4 | 请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的时间复杂度都是O(1)。 5 | 6 | 若队列为空,pop_front 和 max_value 需要返回 -1 7 | 8 | **示例:** 9 | ``` 10 | 输入: 11 | ["MaxQueue","push_back","push_back","max_value","pop_front","max_value"] 12 | [[],[1],[2],[],[],[]] 13 | 输出: [null,null,null,2,1,2] 14 | ``` 15 | 16 | # 解题思路: 17 | 用一个队列,一个双端队列来实现 18 | 19 | 用一个队列保存正常元素,另一个双向队列保存单调递减的元素 20 | 21 | 入栈时,第一个队列正常入栈;第二个队列是递减队列,所以需要与之前的比较,从尾部把小于当前value的全部删除(因为用不到了) 22 | 23 | 出栈时,第一个队列正常出栈;第二个队列的头部与出栈的值作比较,如果相同,那么一起出栈 24 | 25 | # 时间复杂度: 26 | O(1) 27 | # 空间复杂度 28 | O(n) 29 | # 代码 30 | 31 | [C++](./MaxQueue.cpp) 32 | 33 | [Python](./MaxQueue.py) 34 | 35 | # C++: 36 | ### 37 | ```c++ 38 | class MaxQueue { 39 | public: 40 | queue q1; 41 | deque q2; 42 | MaxQueue() { 43 | 44 | } 45 | 46 | int max_value() { 47 | int res = -1; 48 | if (!q2.empty()) 49 | { 50 | res = q2.front(); 51 | } 52 | return res; 53 | } 54 | 55 | void push_back(int value) { 56 | q1.push(value); 57 | while (!q2.empty() && q2.back()max_value(); 81 | * obj->push_back(value); 82 | * int param_3 = obj->pop_front(); 83 | */ 84 | ``` 85 | # Python: 86 | ### 87 | ```python 88 | class MaxQueue: 89 | 90 | def __init__(self): 91 | self.queue=[] 92 | self.max_queue=[] 93 | 94 | def max_value(self) -> int: 95 | if not self.queue: 96 | return -1 97 | return self.max_queue[0] 98 | 99 | 100 | def push_back(self, value: int) -> None: 101 | self.queue.append(value) 102 | while self.max_queue and value > self.max_queue[-1]: 103 | self.max_queue.pop(-1) 104 | self.max_queue.append(value) 105 | 106 | def pop_front(self) -> int: 107 | if not self.queue: 108 | return -1 109 | if self.queue[0]==self.max_queue[0]: 110 | self.max_queue.pop(0) 111 | return self.queue.pop(0) 112 | 113 | 114 | 115 | # Your MaxQueue object will be instantiated and called as such: 116 | # obj = MaxQueue() 117 | # param_1 = obj.max_value() 118 | # obj.push_back(value) 119 | # param_3 = obj.pop_front() 120 | ``` 121 | 122 | 123 | 124 | -------------------------------------------------------------------------------- /FindInPartiallySortedMatrix/FindInPartiallySortedMatrix.cpp: -------------------------------------------------------------------------------- 1 | // C++ Solution 1: 2 | class Solution{ 3 | public: 4 | bool Find(vector> &nums,int target) 5 | { 6 | if (nums.empty()) return false; 7 | int m = nums.size(); 8 | int n = nums[0].size(); 9 | for (int i=0;i> &nums,int target) 26 | { 27 | if (nums.empty()) return false; 28 | int n = nums.size(); 29 | int m = nums[0].size(); 30 | for (int i=0;i=start) 35 | { 36 | int mid = start + (end-start)/2; 37 | if (nums[i][mid]==target) 38 | return true; 39 | if (nums[i][mid]target) 42 | end = mid-1; 43 | } 44 | } 45 | return false; 46 | } 47 | }; 48 | // C++ Solution 3: 49 | // 右上角开始查找 50 | class Solution{ 51 | public: 52 | bool Find(vector> &nums,int target) 53 | { 54 | if (nums.empty()) return false; 55 | int m = nums.size(); 56 | int n = nums[0].size(); 57 | int i=0,j=n-1; 58 | while (i=0) 59 | { 60 | if (nums[i][j]==target) 61 | return true; 62 | else if (nums[i][j]>target) 63 | j--;//左移 64 | else 65 | i++;//下移 66 | } 67 | 68 | return false; 69 | } 70 | }; 71 | // C++ Solution 4: 72 | class Solution{ 73 | public: 74 | bool Find(vector> &nums,int target) 75 | { 76 | if (nums.empty()) return false; 77 | int m = nums.size(); 78 | int n = nums[0].size(); 79 | int i=m-1,j=0; 80 | while (i>=0 && jtarget) 85 | i--;//上移 86 | else 87 | j++;//右移 88 | } 89 | 90 | return false; 91 | } 92 | }; 93 | -------------------------------------------------------------------------------- /SymmetricalBinaryTree/README.md: -------------------------------------------------------------------------------- 1 | # 题目: 对称的二叉树 2 | ## 题目描述: 3 | 请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。 4 | 5 | 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。 6 | ``` 7 | 1 8 | / \ 9 | 2 2 10 | / \ / \ 11 | 3 4 4 3 12 | ``` 13 | 但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的: 14 | ``` 15 | 1 16 | / \ 17 | 2 2 18 | \ \ 19 | 3 3 20 | ``` 21 | # 本题考点: 22 | 23 | 二叉树的遍历算法和递归编程能力,代码的鲁棒性。 24 | 25 | # 解题思路: 26 | 此题与LeetCode101题对称二叉树类似。 27 | 28 | 思路:**递归** 29 | 30 | 1.怎么判断一棵树是不是对称二叉树? 答案:如果所给根节点,为空,那么是对称。如果不为空的话,当他的左子树与右子树对称时,他对称 31 | 32 | 2.那么怎么知道左子树与右子树对不对称呢?在这我直接叫为左树和右树 答案:如果左树的左孩子与右树的右孩子对称,左树的右孩子与右树的左孩子对称,那么这个左树和右树就对称。 33 | 34 | 那用递归分别比较左右子树 35 | 36 | 递归结束条件: 37 | - 都为空指针则返回 true 38 | - 只有一个为空则返回 false 39 | - 两个指针当前节点值不相等 返回false 40 | 41 | 递归过程: 42 | - 判断 A 的右子树与 B 的左子树是否对称 43 | - 判断 A 的左子树与 B 的右子树是否对称 44 | 45 | # 代码 46 | 47 | [C++](./SymmetricalBinaryTree.cpp) 48 | 49 | [Python](./SymmetricalBinaryTree.py) 50 | 51 | # C++: 52 | ### 53 | ```c++ 54 | /* 55 | struct TreeNode { 56 | int val; 57 | struct TreeNode *left; 58 | struct TreeNode *right; 59 | TreeNode(int x) : 60 | val(x), left(NULL), right(NULL) { 61 | } 62 | }; 63 | */ 64 | class Solution { 65 | public: 66 | bool isSymmetrical(TreeNode* pRoot) 67 | { 68 | bool res = true; 69 | if (pRoot!=NULL) 70 | { 71 | res = helper(pRoot->left,pRoot->right); 72 | } 73 | return res; 74 | } 75 | bool helper(TreeNode* A, TreeNode* B) 76 | { 77 | // 先写递归终止条件 78 | if (A==NULL && B==NULL) 79 | return true; 80 | // 如果其中之一为空,也不是对称的 81 | if (A==NULL || B==NULL) 82 | return false; 83 | // 走到这里二者一定不为空 84 | if (A->val != B->val) 85 | return false; 86 | // 前序遍历 87 | return helper(A->left,B->right) && helper(A->right,B->left); 88 | } 89 | }; 90 | ``` 91 | 92 | # Python: 93 | ### 94 | ```python 95 | # -*- coding:utf-8 -*- 96 | # class TreeNode: 97 | # def __init__(self, x): 98 | # self.val = x 99 | # self.left = None 100 | # self.right = None 101 | class Solution: 102 | def isSymmetrical(self, pRoot): 103 | # write code here 104 | res = True 105 | if pRoot: 106 | res = self.helper(pRoot.left, pRoot.right) 107 | return res 108 | def helper(self, A, B): 109 | if A is None and B is None: 110 | return True 111 | if A is None or B is None: 112 | return False 113 | if A.val != B.val: 114 | return False 115 | return self.helper(A.left, B.right) and self.helper(A.right,B.left) 116 | ``` 117 | ## 参考 118 | - [LeetCode-101-对称二叉树](https://github.com/bryceustc/LeetCode_Note/blob/master/cpp/Symmetric-Tree/README.md) 119 | --------------------------------------------------------------------------------