classSolution: defremoveElement(self, nums: List[int], val: int) -> int: n = len(nums) -1 left, right = 0, n while left <= right: if nums[left] == val: while left<= right <= n: if nums[right] !=val: nums[left], nums[right] = nums[right], nums[left] print(left, right, nums) break else: nums.pop() right -= 1 left += 1
方法二:快慢指针
1 2 3 4 5 6 7 8 9 10 11 12
classSolution: defremoveElement(self, nums: List[int], val: int) -> int: n = len(nums) left, right = 0, 0 while right<n: if nums[right] != val: nums[left] = nums[right] left += 1 right += 1 return left
left, right ,top, bottom = 0, n-1, 0, n-1 result = list() board = [["-"] * n for _ inrange(n)] start = 1 while left <= right and top<= bottom: for col inrange(left, right+1): print(col) # result.append(start) board[top][col] = start start += 1 for row inrange(top+1, bottom): # result.append(start) board[row][right] = start start += 1
if left < right: for col inrange(right, left, -1): # result.append(start) board[bottom][col] = start start += 1 if top < bottom: for row inrange(bottom, top, -1): # result.append(start) board[row][left] = start start += 1 left += 1 right -= 1 top += 1 bottom -= 1 return board
left, right = 0, 0 min_len = n+1 total = 0 while left <= right< n: total += nums[right] while left <= right and total>= target: min_len = min(right- left +1, min_len) print(min_len, right, left) total -= nums[left] left += 1 right +=1 return0if min_len == n+1else min_len
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]:
# 分情况讨论 neg = [] non_neg = [] for num in nums: if num < 0: neg.append(num * num) else: non_neg.append(num * num) neg.reverse()
# 合并有序列表 m, n = len(neg), len(non_neg) i = j = 0 ans = [] while i < m and j < n: if neg[i] < non_neg[j]: ans.append(neg[i]) i += 1 else: ans.append(non_neg[j]) j += 1 ans += neg[i:] ans += non_neg[j:] return ans
dummary = ListNode(0, head) length = 0 while head: head = head.next length += 1 cur = dummary for i inrange(1, length - n +1): cur = cur.next cur.next = cur.next.next return dummary.next
while head: if head in viewed: returnTrue viewed.add(head) head = head.next returnFalse # 快慢指针 defhasCycle(self, head: Optional[ListNode]) -> bool: ifnot head: returnFalse slow = fast = head while fast.nextand fast.next.next: slow = slow.next fast = fast.next.next if slow is fast: returnTrue returnFalse
设链表的总长度为a+b ,其中a为头节点到入口处的距离,b为环形的长度 现在假设有两个人开始跑步,一个人的速度是另一个人的两倍,他们们在相遇点相遇,此时我们看看他们走过的距离关系 第一次相遇 1. 令slow的走过的距离为slow = s --->fast = 2s 2. 由于是在环内相遇,可知fast一定是套圈slow了,且快的人比慢的人在圈里多跑了n圈,即nb, 由于慢的人走了s, 所有快的人走了fast = s + nb (具体n是几未知) 3. 有1式 减2可得s = nb 4. 可以再看, 每次经过入口点得距离k = a + nb 5. 由于s已经搜了nb步, 所以只需要再走a步就是入口点,如何得到a步呢 第二次相遇 1. 由上面推导我们可得slow 再走a步就是入口点, 1. 此时让快得人去起始点,保持和慢得人一致得速度,当两人相遇时,恰好走了a步
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution: defdetectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: fast = slow = head ifnot head: returnNone while fast.nextand fast.next.next: fast = fast.next.next# 走两步 slow = slow.next if fast is slow: # 首次相遇: fast = head while fast isnot slow: fast = fast.next slow = slow.next #if fast is slow: # return slow return fast returnNone
classSolution(object): defreorderList(self, head): """ :type head: ListNode :rtype: None Do not return anything, modify head in-place instead. """ ifnot head: returnNone stack = [] cur = head while cur: stack.append(cur) cur = cur.next
n = len(stack)
middle = (n-1) //2 cur = head while middle: tmp = stack.pop()
classSolution(object): defreorderList(self, head): """ :type head: ListNode :rtype: None Do not return anything, modify head in-place instead. """ ifnot head ornot head.next: return head defmiddle_node(head): slow = fast = head while fast.nextand fast.next.next: slow = slow.next fast = fast.next.next return slow
defreverse_link(head): """ 原地逆置法 初始化两个三个指针,一个指向头节点,一个指向第一个节点,一个指向第二个节点 """ beg= head end = head.next while end: beg.next = end.next end.next = head head = end end = beg.next return head
defmergeList(l1, l2): while l1 and l2: l1_next = l1.next l2_next = l2.next
l1.next = l2 l1 = l1_next
l2.next = l1 l2 = l2_next
node = middle_node(head) right = node.next#右半部链表 node.next = None# 注意一定要断链
# 逆置链表 right = reverse_link(right) # 合并两个链表 mergeList(head, right)
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution: defreverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
""" 原地逆置法 """ ifnot head ornot head.next: return head # 初始化两个指针 beg = head end = head.next while end: #beg = head #end = head.next beg.next = end.next end.next = head head = end end = beg.next return head
classSolution: defspiralOrder(self, matrix: List[List[int]]) -> List[int]: ifnot matrix: return [] m = len(matrix) n = len(matrix[0]) result = list() left, right, top, bottom = 0, n-1, 0, m-1 while left <= right and top <= bottom: for col inrange(left, right+1): result.append(matrix[top][col])
for row inrange(top+1, bottom+1): result.append(matrix[row][right])
if left < right and top < bottom: for col inrange(right-1, left, -1): result.append(matrix[bottom][col]) for row inrange(bottom, top, -1): result.append(matrix[row][left]) left += 1 right -= 1 top += 1 bottom -= 1 return result
defpush(self, val: int) -> None: #self.min = val if not self.min else min(self.min, val) ifnotself.min: self.min.append(val) else: ifself.min[-1] >= val: self.min.append(val) self.stack.append(val)
defpop(self) -> None: num = self.stack.pop() ifself.minandself.min[-1] == num: self.min.pop() return num
deftop(self) -> int: returnself.stack[-1]
defgetMin(self) -> int: returnself.min[-1]
# Your MinStack object will be instantiated and called as such: # obj = MinStack() # obj.push(val) # obj.pop() # param_3 = obj.top() # param_4 = obj.getMin()
for ss in s: if ss in dict1: if stack and stack[-1] == dict1.get(ss): stack.pop() else: returnFalse else: stack.append(ss) returnTrueifnot stack elseFalse
# 方法一:会超时 # result = list() # for ss in s: # # 不足k-1个直接加入 # if len(result) < k-1: # result.append(ss) # else: # # 检测后k-1各元素是否相同并且同为ss # is_valid = False # result.append(ss) # for i in range(-1, -k-1, -1): # if result[i] != ss: # is_valid = True # break # if not is_valid: # result = result[:len(result)-k] # return "".join(result)
# 方法二 利用栈 stack = list() for ss in s: if stack: if ss == stack[-1][0] and stack[-1][1]+1 < k: stack[-1][1] += 1 elif ss == stack[-1][0] and stack[-1][1]+1 >=k: stack.pop()
else: stack.append([ss, 1]) else: stack.append([ss, 1]) result = list() forchr, num in stack: result.append(chr*num) return"".join(result)
ifnot nums: return0 max_len = 0 nums_set = set(nums) for num in nums_set: pre_num = num -1
if pre_num notin nums_set: temp_len = 1 cur = num
while cur+ 1in nums_set: cur +=1 temp_len += 1 max_len = max(temp_len, max_len) return max_len
动态规划解法
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution: deflongestConsecutive(self, nums: List[int]) -> int: res = 0 hash_dict = dict() for num in nums: if num notin hash_dict: left = hash_dict.get(num-1, 0) right = hash_dict.get(num+1, 0) cur_lenght = left + right +1 res = max(cur_lenght, res) hash_dict[num] = cur_lenght hash_dict[num-left]= cur_lenght hash_dict[num+right] = cur_lenght return res
classSolution: defsetZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """
need_zero_raw = set() need_zero_col = set() for i inrange(len(matrix)): for j inrange(len(matrix[0])): if matrix[i][j] == 0: need_zero_raw.add(i) need_zero_col.add(j) for row in need_zero_raw: for j inrange(len(matrix[0])): matrix[row][j] = 0
for col in need_zero_col: for i inrange(len(matrix)): matrix[i][col] = 0
defbubble(nums): n = len(nums) for i inrange(n-1): for j inrange(n-1-i): if num[i] < nums[j]: nums[i], nums[j] = nums[j], nums[i] return nums
defbubble_sort2(nums): n = len(nums) for i inrange(n-1): exchange = False for i inrange(n-1-i): if nums[i] < nums[j]: nums[i], nums[j] = nums[j], nums[i] exchange = True ifnot exchange: break return nums
选择排序
设定第一个元素得坐标为基准下标,然后用这个元素与无序数组中得元素做比较,找出此时得最小下标
每一轮循环,都会将无序中得最小元素交换至有序数组得末尾
1 2 3 4 5 6 7 8
defselect_sort(nums): n = len(nums-1) for i inrange(n): basic = nums[i] for j inrange(i+1, n):
left, right = 0, len(nums) -1# left 代表最左边,right最右边 while left <= right: mid = (left+right)//2 if nums[mid]== target: left = right = mid while left>=0and nums[left] == target: left -=1 while right <= len(nums)-1and nums[right] == target: right += 1 return [left+1, right-1] elif nums[mid] > target: right = mid -1 else: left = mid +1 return [-1, -1]
left, right = 0, x while left <=right: mid = (left + right)//2 if (mid+1) * (mid+1) > x and mid * mid <= x : return mid elif mid * mid < x: left = mid +1 else: right = mid -1
classSolution: defisPalindrome(self, s: str) -> bool: ss = re.findall(r'[a-zA-Z0-9]', s) left, right = 0, len(ss) - 1 while left < right: if ss[left].lower() == ss[right].lower(): left += 1 right -= 1 else: returnFalse returnTrue