详细讲解:点击跳转
给你一个整数数组 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
示例 2:
输入:nums = [1], k = 1 输出:[1]
提示:
1 <= nums.length <= 105
-104 <= nums[i] <= 104
1 <= k <= nums.length
我们维护一个单调队列,队列的第一个元素是窗口的最大值,队列中只装有可能是最大值的数,同时保证队列里的元素数值是由大到小的。
思路:
维护一个单调队列 (队头到队尾依次减小),
push(int x): 将队列中小于x的全部弹出
pop(int x):x==队头元素,弹出x
peek():队头元素,也就是窗口最大值
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
//先将K个元素加入
int[] result = new int[nums.length+1-k];
int n=0;
myQueue myQueue1= new myQueue();
for(int i=0;i<k;i++){
myQueue1.push(nums[i]);
}
result[n++]=myQueue1.peek();
//移动窗口,i是窗口右部,
for(int i=k;i<nums.length;i++){
myQueue1.pop(nums[i-k]);
myQueue1.push(nums[i]);
result[n++]=myQueue1.peek();
}
return result;
}
}
class myQueue{
List<Integer> list;
public myQueue(){
list = new LinkedList<>();
}
public void push(int x){
while(list.size()>0&&list.get(list.size()-1)<x){
list.remove(list.size()-1);
}
list.add(x);
}
public void pop(int x){
if(x==list.get(0)){
list.remove(0);
}
}
public int peek(){
return list.get(0);
}
}
给你一个整数数组 nums
和一个整数 k
,请你返回其中出现频率前 k
高的元素。你可以按 任意顺序 返回答案。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2 输出: [1,2]
示例 2:
输入: nums = [1], k = 1 输出: [1]
提示:
1 <= nums.length <= 105
k
的取值范围是[1, 数组中不相同的元素的个数]
- 题目数据保证答案唯一,换句话说,数组中前
k
个高频元素的集合是唯一的
进阶:你所设计算法的时间复杂度 必须 优于 O(n log n)
,其中 n
是数组大小。
思路:
本题与上一题不同,上一题只需要维护一个单调队列,不要求单调队列的长度,本题不仅需要维持单调,还要维持长度=k
- 要统计元素出现频率:使用map来进行统计
- 对频率排序:用一个size为k的优先级队列,用小顶堆实现,个数大于K时弹出最小值
- 找出前K个高频元素
class Solution {
public int[] topKFrequent(int[] nums, int k) {
//记录每个数出现的对应次数
Map<Integer,Integer> map=new HashMap<>();
for(int i=0;i<nums.length;i++){
map.put(nums[i],map.getOrDefault(nums[i],0)+1);
}
//建立小顶堆
PriorityQueue<int[]> priorityQueue = new PriorityQueue<>((a1, a2) -> a1[1] - a2[1]);
//遍历map
for (Map.Entry<Integer, Integer> entry : map.entrySet()){
if(priorityQueue.size()<k){
priorityQueue.add( new int[]{entry.getKey(), entry.getValue()});
}else{
if(priorityQueue.peek()[1]<entry.getValue()){
priorityQueue.poll();//弹出队头,也就是最小值
priorityQueue.add(new int[]{entry.getKey(), entry.getValue()});
}
}
}
//结果按照次数多的排在前面
int result[] = new int[priorityQueue.size()];
int i=priorityQueue.size()-1;
while(priorityQueue.size()>0){
int temp = priorityQueue.poll()[0];
result[i--] = temp;
}
return result;
}
}