LeetCode刷题 Day13

96 阅读2分钟

LeetCode刷题 Day13

239. Sliding Window Maximum

You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.

Return the max sliding window.

Example 1:

Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Explanation: 
Window position                Max
---------------               -----
[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

Example 2:

Input: nums = [1], k = 1
Output: [1]

思路:

  • 用队列记录最大值的index,并确保队列长度 <= k
  • 队列的队首保持最大值 (desc队列),当nums[pos[pos.length - 1]] < nums[i]时,pos.pop
  • res开始记录的起点应该为 i >= k - 1的时候, 这个时候pos已经包含了nums前k个数组元素中的最大值index

代码:

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number[]}
 */
var maxSlidingWindow = function(nums, k) {
    let pos = [];
    let res = [];
    
    for (let i = 0; i < nums.length; i++) {
        while (pos.length > 0 && nums[pos[pos.length - 1]] < nums[i]) {
            pos.pop();
        }
        
        pos.push(i);
        
        while (pos[0] <= i - k) {
            pos.shift();
        }
        
        if (i >= k - 1) {
            res.push(nums[pos[0]]);
        }
    }
    
    return res;
};

时间复杂度: O(n), 空间复杂度: O(n)


347. Top K Frequent Elements

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

  Example 1:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Example 2:

Input: nums = [1], k = 1
Output: [1]

解法1:

解法2:

  • 用桶排序 + Set, Set是为了避免冲突
  • 用map存储frequency
  • 根据将frequency作为index, 对应数组值设置为Set()存入bucket数组: bucket[freq] = (bucket[freq] || new Set()).add(num)。
  • 存入res, 将bucket中的set解构, i为desc顺序. res.push(...bucket[i]), 当res.length === k. return 或break

代码:

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number[]}
 */
var topKFrequent = function(nums, k) {
    let map = new Map();
    let bucket = [];
    let res = [];
    
    for (let num of nums) {
        map.set(num, (map.get(num) || 0) + 1);
    }
    for (let [num, freq] of map) {
       bucket[freq] = (bucket[freq] || new Set()).add(num);
    }

    for (let i = bucket.length - 1; i >= 0; i--) {
        if (bucket[i]) res.push(...bucket[i]);
        if (res.length === k) return res;
    }
    
    return res;
};

时间复杂度: O(n)