480
题目描述:
中位数是有序序列最中间的那个数。如果序列的大小是偶数,则没有最中间的数;此时中位数是最中间的两个数的平均数。
例如:
[2,3,4],中位数是 3
[2,3],中位数是 (2 + 3) / 2 = 2.5
给你一个数组 nums,有一个大小为 k 的窗口从最左端滑动到最右端。窗口中有 k 个数,每次窗口向右移动 1 位。你的任务是找出每次窗口移动后得到的新窗口中元素的中位数,并输出由它们组成的数组。
示例:
解答:
class Solution:
def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:
n=len(nums)
window=[]
l=0
res=[]
for i in range(n):
bisect.insort(window,nums[i])
while len(window)>k:
window.pop(bisect.bisect_left(window,nums[l]))
l+=1
if(i>=k-1):
if k%2==1:
res.append(window[k//2])
else:
res.append((window[k//2]+window[k//2-1])/2)
return res
1004
题目描述:
给定一个由若干 0 和 1 组成的数组 A,我们最多可以将 K 个值从 0 变成 1 。
返回仅包含 1 的最长(连续)子数组的长度。
示例:
解答:
class Solution:
def longestOnes(self, A: List[int], K: int) -> int:
left,right,count = 0,0,0
for right in range(len(A)):
if A[right] == 0:
count += 1
if count > K:
if A[left] == 0:
count -= 1
left += 1
return right-left+1
剑指offer29
题目描述:
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例:
解答:
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix:
return []
l, r, t, b, res = 0, len(matrix[0]) - 1, 0, len(matrix) - 1, []
while True:
for i in range(l, r + 1): # left to right
res.append(matrix[t][i])
t += 1
if t > b:
break
for i in range(t, b + 1): # top to bottom
res.append(matrix[i][r])
r -= 1
if l > r:
break
for i in range(r, l - 1, -1): # right to left
res.append(matrix[b][i])
b -= 1
if t > b:
break
for i in range(b, t - 1, -1): # bottom to top
res.append(matrix[i][l])
l += 1
if l > r:
break
return res
剑指offer30
题目描述:
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
示例:
解答:
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack=[]
self.minstack=[]
def push(self, x: int) -> None:
self.stack.append(x)
if not self.minstack or x<=self.minstack[-1]:
self.minstack.append(x)
def pop(self) -> None:
if self.stack.pop()==self.minstack[-1]:
self.minstack.pop()
def top(self) -> int:
return self.stack[-1]
def min(self) -> int:
return self.minstack[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.min()
剑指offer31
题目描述:
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如,序列 {1,2,3,4,5} 是某栈的压栈序列,序列 {4,5,3,2,1} 是该压栈序列对应的一个弹出序列,但 {4,3,5,1,2} 就不可能是该压栈序列的弹出序列。
示例:
解答:
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
stack=[]
i=0
for num in pushed:
stack.append(num)
while stack and stack[-1]==popped[i]:
stack.pop()
i+=1
if not stack:
return True
else:
return False