给定一个数组 nums,有一个大小为k的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口 k 内的数字。滑动窗口每次只向右移动一位。返回滑动窗口最大值。
示例:
输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
输出: [3,3,5,5,6,7]
class Solution(object):
def maxSlidingWindow(self, nums, k):
queue,res = [],[]
for i in range(len(nums)):
#当前元素比队尾元素大时 弹出
while queue and nums[i] > nums[queue[-1]]:
queue.pop()
# i - queue[0] == k 意味着已经被加入结果列表中
if queue and i - queue[0] == k:
queue.pop(0)
queue.append(i)
if i >= k-1:
res.append(nums[queue[0]])
return res
编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:
- 每行的元素从左到右升序排列。
- 每列的元素从上到下升序排列。
class Solution(object):
def searchMatrix(self, matrix, target):
if not matrix:
return False
row,col = 0,len(matrix[0])-1
while row < len(matrix) and col > -1:
if target > matrix[row][col]:
row +=1
elif target < matrix[row][col]:
col -=1
else:
return True
return False
序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。请设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列/反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。
class Codec:
def serialize(self, root):
if root == None:
return '*!'
pre_str = ''
pre_str +=str(root.val)+'!'
pre_str +=self.serialize(root.left)
pre_str +=self.serialize(root.right)
return pre_str
def deserialize(self, data):
values = data.split('!')
return self.deserialize_pre_str(values)
def deserialize_pre_str(self,values):
value = values.pop(0)
if value == '*':
return None
root = TreeNode(value)
root.left = self.deserialize_pre_str(values)
root.right = self.deserialize_pre_str(values)
return root
给定不同面额的硬币 coins和一个总金额amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。
示例 1:
输入: coins = [1, 2, 5], amount = 11
输出: 3
解释: 11 = 5 + 5 + 1
示例 2:
输入: coins = [2], amount = 3
输出: -1
备注:
dp[i]表示金额为i需要最少的金额多少,
对于任意金额i,dp[i] = min(dp[i],dp[i-coin]+1),i-coin>=0.
class Solution(object):
def coinChange(self, coins, amount):
dp = [0] * (amount+1)
for i in range(1,amount+1):
dp[i] = float('inf')
for coin in coins:
if i-coin >=0 and dp[i-coin] !=-1:
dp[i] = min(dp[i],dp[i-coin]+1)
#代表不可兑换
if(dp[i] == float('inf')):
dp[i] = -1
return dp[-1]
给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例 2:
输入: nums = [1], k = 1
输出: [1]
public static List<Integer> topKFrequent(int[] nums, int k) {
HashMap<Integer, Integer> map = new HashMap<>();
// 用map统计各个元素都有多少个
for (int num : nums) {
if (map.containsKey(num)) {
map.put(num, map.get(num) + 1);
} else {
map.put(num, 1);
}
}
// 用优先队列获得最多的前K个
PriorityQueue<Integer> queue = new PriorityQueue<>((a, b) -> map.get(b) - map.get(a));
for (int key : map.keySet()) {
if (queue.size() < k) {
queue.add(key);
} else if (map.get(key) > map.get(queue.peek())) {
queue.remove();
queue.add(key);
}
}
LinkedList<Integer> res = new LinkedList<>();
while (!queue.isEmpty()) {
res.add(queue.poll());
}
return res;
}
Python
class Solution(object):
def topKFrequent(self, nums, k):
count = {}
for num in nums:
count[num] = count.get(num,0)+1
heap = []
for key,v in count.items():
heap.append((-v,key))
heapq.heapify(heap)
res = []
for i in range(k):
#必须用heappop函数,底层用的是列表存的堆结构
res.append(heapq.heappop(heap)[1])
return res
class Solution(object):
def topKFrequent(self, nums, k):
from collections import Counter
c = Counter(nums)
listRes = c.most_common(k)
res = []
for item in listRes:
res.append(item[0])
return res