# 485. 最大连续 1 的个数
class Solution(object):
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res = 0
final_res = 0
for num in nums:
if num==1:
res+=1
final_res = res if res>final_res else final_res
else:
res=0
return final_res
# 283. 移动零(把目标往前面移动)
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
idx = 0
for i in range(len(nums)):
if nums[i]!=0:
nums[idx]=nums[i]
idx+=1
for i in range(idx,len(nums)):
nums[i]=0
# 27. 移除元素(和移动0一样,把目标往前面移)
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
idx = 0
for i in range(len(nums)):
if nums[i]!=val:
nums[idx]=nums[i]
idx+=1
return idx
# 203. 移除链表元素
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
dummy_head = ListNode(next=head) #添加一个虚拟节点指向head
cur = dummy_head #当前节点
while(cur.next!=None):#如果当前节点不是null
if(cur.next.val == val):
cur.next = cur.next.next #删除cur.next节点(跳接后面节点)
else:
cur = cur.next # 当前节点后移
return dummy_head.next
#No.993 最近的请求次数
#python 队列一般用双端队列代替队列用,注意popleft和pop
from collections import deque
class RecentCounter(object):
def __init__(self):
self.qureytimes=0
self.requests=deque()
self.length = 0
def ping(self, t):
"""
:type t: int
:rtype: int
"""
self.requests.append(t)
self.length+=1
t_start = t-3000
t_end = t
while self.requests[0]<t_start:
self.requests.popleft()
return len(self.requests)
# No.20 有效括号
# 栈操作
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
for ss in s:
cur = stack[-1] if len(stack)>0 else ''
if cur+ss=='()':
stack.pop()
elif cur+ss=='[]':
stack.pop()
elif cur+ss=='{}':
stack.pop()
else:
stack.append(ss)
return len(stack)==0
# 496. 下一个更大元素
class Solution(object):
def nextGreaterElement(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
def _findbigger(num):
idx = nums2.index(num)
set_nums = nums2[idx:]
for item in set_nums:
if item>num:
return item
return -1
res=[]
for num in nums1:
res.append(_findbigger(num))
return res