基础题数组-485、283、27
1 class Solution: 2 def findMaxConsecutiveOnes(self, nums: List[int]) -> int: 3 maxCount = count = 0 4 5 for i, num in enumerate(nums): 6 if num == 1: 7 count += 1 8 else: 9 maxCount = max(maxCount, count) 10 count = 0 11 12 maxCount = max(maxCount, count) 13 return maxCount
count = 0 ans = 0 for i in nums: if i == 1: count += 1 if ans < count: ans = count else: count = 0 return ans
#先化为str,再用split方法将其以"0"分隔,结果便是list中最长的item的长度 s = "" for i in nums: s += str(i) L2 = s.split("0") return max([len(i) for i in L2])
#快慢同向双指针(移动窗口法) slow = fast = 0 n = len(nums) max_count = 0 while slow < n: # 找出连续1中,第一个1的位置 if nums[slow] != 1: slow += 1 else: # fast指针从slow指针开始遍历,直至nums[fast]!=1 fast = slow while fast < n and nums[fast] == 1: fast += 1 # 局部最长fast-slow和全局最长max_count取最大值 max_count = max(max_count, fast - slow) # 更新slow指针的位置到fast指针处,继续循环,寻找下一个1 slow = fast return max_count
1 class Solution: 2 def moveZeroes(self, nums: List[int]) -> None: 3 """ 4 Do not return anything, modify nums in-place instead. 5 """ 6 #不交换,之间覆盖 7 index = 0 8 i = 0 9 n = len(nums) 10 while i < n : 11 if nums[i] != 0: 12 nums[index] = nums[i] 13 index += 1 14 i += 1 15 16 #python 在 for 里修改索引变量不会影响到下一个循环,使用 while 才行 17 while index < n: 18 nums[index] = 0 19 index += 1 20 21 return nums
1 class Solution: 2 def removeElement(self, nums: List[int], val: int) -> int: 3 #pop删除元素 4 n = len(nums) 5 i = 0 6 if n == 0: 7 return 0 8 9 while i < n: 10 if nums[i] == val: 11 nums.pop(i) 12 n -= 1 #数组长度发生变化 13 else: 14 i += 1 #不等于val值才往下走一位 15 16 return len(nums) 17 18 #双指针 更快 19 s = f = 0 20 21 while f < len(nums): 22 if nums[f] != val: 23 nums[s] = nums[f] 24 s += 1 25 f += 1 26 27 return s