classSolution: deflengthOfLongestSubstring(self, s: str) -> int: ifnot s: return0 iflen(s)==1: return1 left=right=0 ans = float(-inf) while right !=len(s)-1: # right+=1 # 收缩 while s[right] in s[left:right]: left+=1 ans =max(ans,right-left+1) return ans
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution: deflengthOfLongestSubstring(self, s: str) -> int: ifnot s:return0 iflen(s)==1:return1 left=right =0 ret = 0 window={} while right!=len(s): c=s[right] right+=1 window[c]=window.get(c,0)+1 while window[c]>1: d = s[left] left+=1 window[d]-=1
classSolution: defthreeSum(self, nums: [int]) -> [[int]]: nums.sort() res, k = [], 0 # 操作都在循环里面 for i inrange(0, len(nums) - 2): if nums[i] > 0: break if i > 0and nums[i] == nums[i - 1]: continue j, k = i + 1, len(nums) - 1 while j < k: s = nums[i] + nums[j] + nums[k] if s < 0: j += 1 while j < k and nums[j] == nums[j - 1]: j += 1 elif s > 0: k -= 1 while j < k and nums[k] == nums[k + 1]: k -= 1 else: res.append([nums[k], nums[i], nums[j]]) j += 1 k -= 1 while j < k and nums[j] == nums[j - 1]: j += 1 while j < k and nums[k] == nums[k + 1]: k -= 1 return res
LEETCODE15.三数之和
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
classSolution: defthreeSum(self, nums: [int]) -> [[int]]: nums.sort() res, k = [], 0 # 操作都在循环里面 for i inrange(0, len(nums) - 2): if nums[i] > 0: break if i > 0and nums[i] == nums[i - 1]: continue j, k = i + 1, len(nums) - 1 while j < k: s = nums[i] + nums[j] + nums[k] if s < 0: j += 1 while j < k and nums[j] == nums[j - 1]: j += 1 elif s > 0: k -= 1 while j < k and nums[k] == nums[k + 1]: k -= 1 else: res.append([nums[k], nums[i], nums[j]]) j += 1 k -= 1 while j < k and nums[j] == nums[j - 1]: j += 1 while j < k and nums[k] == nums[k + 1]: k -= 1 return res
classSolution: deftrap(self, height: List[int]) -> int: ans=0 for i inrange(1,len(height)-1): left_max=max(height[:i]) right_max=max(height[i+1:]) if left_max<height[i] or right_max<height[i]:continue ans += min(left_max,right_max) return ans
这么看这代码满打满算才10行
LEETCODE415.字符串相加
给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。
你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式
但是可以int()其中的字符..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution: defaddStrings(self, num1: str, num2: str) -> str: i=len(num1)-1 j=len(num2)-1 carry=0 ans='' while i>=0or j>=0: n1 = int(num1[i]) if i>=0else0 n2 = int(num2[j]) if j>=0else0 tmp = n1+n2+carry carry = tmp//10 ans = str(tmp%10)+ans i-=1 j-=1 return"1"+ ans if carry else ans
classSolution: def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: ans = [] ifnot root:return [] flag=1 temp = collections.deque() temp.append(root) whilelen(temp)!=0: n = len(temp) temp_list=collections.deque() for i in range(n): node = temp.popleft() //就记住这个flag就行 // if flag==1: temp_list.append(node.val) else: temp_list.appendleft(node.val)
if node.left!=None:temp.append(node.left) if node.right!=None:temp.append(node.right)
flag=(-1)*flag ans.append(list(temp_list)) return ans
LEETCODE.121 买卖股票的最佳时机
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
如果你最多只允许完成一笔交易(即买入和卖出一支股票一次),设计一个算法来计算你所能获取的最大利润。
注意:你不能在买入股票前卖出股票。
这题是真的经典 覃超这个讲的真的挺明白的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution: defmaxProfit(self, prices: List[int]) -> int: n = len(prices) if n==0:return0 dp=[[0for _ inrange(3)] for i inrange(n)] # 0代表手上没有股票 1代码手上有股票 2代码卖出股票 dp[0][0]=0 dp[0][1]=-price[0] dp[0][2]=0 ans =0 for i inrange(1,n): dp[i][0]=dp[i-1][0] dp[i][1]=max(dp[i-1][1],dp[i-1][0]-price[i]) dp[i][2]=dp[i-1][1]+price[i] ans = max(ans,dp[i][0],dp[i][1],dp[i][2]) return ans
classSolution: defreorderList(self, head: ListNode) -> None: """ Do not return anything, modify head in-place instead. """ ifnot head:return head vec=[] cur =head while cur: vec.append(cur) cur=cur.next i=0 j=len(vec)-1 while i<j: vec[i].next=vec[j] i+=1 if i==j: break vec[j].next=vec[i] j-=1 vec[j].next=None return head
classSolution: # key 是num value 是index deftwoSum(self, nums: List[int], target: int) -> List[int]: hashtable={} for index,value in emumerate(nums): if target-value in hashtable: return [index,hashtable[target-num]] hashtable[value]=index return []
LEETCODE199.二叉树的右视图
最近才写的应该
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution: defrightSideView(self, root: TreeNode) -> List[int]: #懒得写了... ifnot root:return [] ans=[] #ans.append(root.val) queue=[root] while queue: n = len(queue) ans.append(queue[-1].val) for i inrange(0,n): node = queue.pop() if root.left:queue.append(root.left) if root.right:queue.append(root.right) return ans
LEETCODE160.相交链表
编写一个程序,找到两个单链表相交的起始节点。
这题挺有意思的。题解太好玩了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution: defgetIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: l1 =headA L2 =headB while l1!=l2: # 相当于第一条路走到头了. if l1==None: l1=headB else: l1=l1.next if l2==None: l2=headA else: l2=l2.next return l1
LEETCODE215.数组中第K个最大元素 原来这就是topK
在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
voidswap(int arr[],int i,int j){ int temp= arr[i]; arr[i]=arr[j]; arr[j]=temp; }
voidheapify(int tree[],int n,int i){ if (i>=n){ return; } int c1 = 2*i +1; int c2 = 2*i +2; int maxIndex=i; if (c1< n && tree[c1]>tree[maxIndex]){ maxIndex =c1; } if (c2< n && tree[c2]>tree[maxIndex]){ maxIndex =c2; } if (maxIndex!=i){ swap(tree,maxIndex,i); heapify(tree,n,maxIndex); } } voidbuild_heap(int tree[],int n){ int last_node=n-1; int parent=(last_node-1)/2; int i; for (i=parent;i>=0;i--){ heapify(tree,n,i); } }
voidheap_sort(int tree[],int n){ build_heap(tree,n); int i; for(i=n-1;i>=0;i--){ swap(tree,i,0); heapify(tree,i,0); //大的被交换到尾巴去了 太有意思了堆排 } } intfindKthLargest(int* nums, int numsSize, int k){ heap_sort(nums,numsSize); return nums[numsSize-k]; }
publicstaticvoidsort(int[] arr, int left, int right){ if (left > right) { return ; } int i = left, j = right, temp = arr[left], t; while (i != j) { // 右边找到一个比base小的 while (arr[j] >= temp && i < j) { j--; } // 左边找到一个比base大的 while (arr[i] <= temp && i<j) { i++; } //交换 if (i < j) { t = arr[i]; arr[i] = arr[j]; arr[j] = t; } } //base交换 //然后递归下去 arr[left] = arr[i]; arr[i] = temp; sort(arr, left, i - 1); sort(arr, i+1, right); }
太骚了 这个快排
1 2 3 4 5 6 7 8 9 10 11
defquicksort(list): iflen(list)<2: returnlist else: midpivot = list[0] lessbeforemidpivot = [i for i inlist[1:] if i<=midpivot] biggerafterpivot = [i for i inlist[1:] if i > midpivot] finallylist = quicksort(lessbeforemidpivot)+[midpivot]+quicksort(biggerafterpivot) return finallylist
} voidappendTail(int value){ s1.push(value); } //# 思路没问题的 intdeleteHead() { //# s2非空 if(s2.size()!=0){ int temp= s2.top(); s2.pop(); return temp; } //# s2 s1 为空 if (s1.size()==0and s2.size()==0) return-1; //# # s1非空 s2为空 while (!s1.empty()){ s2.push(s1.top()); s1.pop(); } int ans =s2.top(); s2.pop(); return ans; } };
/** * Your CQueue object will be instantiated and called as such: * CQueue* obj = new CQueue(); * obj->appendTail(value); * int param_2 = obj->deleteHead(); */
classSolution: def maxSubArray(self, nums: List[int]) -> int: maxSum = nums[0] curSum =nums[0] for i in range(1,len(nums)): curSum = max(curSum+nums[i],nums[i]) maxSum=max(maxSum,curSum) return maxSum
classSolution: defisValid(self, s: str) -> bool: iflen(s) % 2 == 1: returnFalse pairs = { ")": "(", "]": "[", "}": "{", } stack = list() for ch in s: if ch in pairs: ifnot stack or stack[-1] != pairs[ch]: returnFalse stack.pop() else: stack.append(ch) returnnot stack
LEETCODE141.环形链表
大体思路:快慢指针就行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution: defhasCycle(self, head: ListNode) -> bool: ifnot head ornot head.next: returnFalse slow = fast =head while slow and fast and fast.next: slow = slow.next fast = fast.next.next if slow is fast: returnTrue returnFalse