239. 滑动窗口最大值
力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
int n = nums.length;
Deque<Integer> deque = new LinkedList<Integer>();
for(int i = 0 ; i < k ; ++i){
while(!deque.isEmpty()&&nums[i]>=nums[deque.peekLast()]){
deque.pollLast();
}
deque.offerLast(i);
}
int[] ans = new int[n-k+1];
ans[0] = nums[deque.peekFirst()];
for(int i = k ; i < n ; ++i){
while (!deque.isEmpty() && nums[i] >= nums[deque.peekLast()]) {
deque.pollLast();
}
deque.offerLast(i);
while (deque.peekFirst() <= i - k) {
deque.pollFirst();
}
ans[i - k + 1] = nums[deque.peekFirst()];
}
return ans;
}
}
347.前 K 个高频元素
https://leetcode.cn/problems/top-k-frequent-elements/description/
class Solution {
public int[] topKFrequent(int[] nums, int k) {
int[] result = new int[k];
// key : 数字; value :出现到频次
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int curNum = nums[i];
map.put(curNum, map.getOrDefault(curNum, 0) + 1);
}
// 根据 value 进行排序
ArrayList<Map.Entry<Integer, Integer>> list = new ArrayList(map.entrySet());
Collections.sort(list, (a, b) -> {
return b.getValue() - a.getValue();
});
for (int i = 0; i < k; i++) {
result[i] = list.get(i).getKey();
}
return result;
}
}