难度中等1379
给你一个整数数组 nums
和一个整数 k
,请你返回其中出现频率前 k
高的元素。你可以按 任意顺序 返回答案。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2 输出: [1,2]
class Solution {
public int[] topKFrequent(int[] nums, int k) {
int[] res = new int[k];
Map<Integer,Integer> map = new HashMap<>();
for(int i : nums){
map.put(i,map.getOrDefault(i,0)+1);
}
PriorityQueue<int[]> q = new PriorityQueue<>((o1,o2)->o1[1]-o2[1]);
for(int i : map.keySet()){
int num = i;
int count = map.get(i);
int[] tmp = {num,count};
if(q.size() < k){
q.offer(tmp);
}else{
int[] top = q.peek();
if(top[1] <= count){
q.poll();
q.offer(tmp);
}
}
}
for(int i=0;i < k;i++){
res[i] = q.poll()[0];
}
return res;
}
}
难度困难1968
给你一个整数数组 nums
,有一个大小为 k
的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k
个数字。滑动窗口每次只向右移动一位。
返回 滑动窗口中的最大值 。
示例 1:
输入:nums = [1,3,-1,-3,5,3,6,7], k = 3 输出:[3,3,5,5,6,7] 解释: 滑动窗口的位置 最大值 --------------- ----- [1 3 -1] -3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
//单调队列,队头放最大值,保存索引
//如果比队头大,则队头出队,直到队头比i大
//队尾入队
int n = nums.length;
int[] res = new int[n-k+1];
Deque<Integer> s = new LinkedList<>();
int m = 0;
for(int i =0;i < n;i++){
while(!s.isEmpty() && s.peekFirst() <= i - k ){
s.pollFirst();
}
while(!s.isEmpty() && nums[i] > nums[s.peekLast()]){
s.pollLast();
}
s.offerLast(i);
if(i >= k-1){
res[m++] = nums[s.peek()];
}
}
return res;
}
}