算法打卡:第4周

问题一

队列的最大值: https://leetcode-cn.com/problems/dui-lie-de-zui-da-zhi-lcof/

思路:其实本题需要实现的是一个优先队列,可以用作第二题的解答。

class MaxQueue {
    private List<Integer> list;

    public MaxQueue() {
        list = new LinkedList<>();
    }

    public int max_value() {
        int maxVal = -1;
        for (int i : list) {
            if (i > maxVal) {
                maxVal = i;
            }
        }
        return maxVal;
    }

    public void push_back(int value) {
        list.add(value);
    }

    public int pop_front() {
        if (list.size() > 0) {
            return list.remove(0);
        }
        return -1;
    }
}

问题二

滑动窗口的最大值:https://leetcode-cn.com/problems/hua-dong-chuang-kou-de-zui-da-zhi-lcof/

思路:可以利用上题的结构来解决此题。也可以利用treeMap来实现,需要注意的是最大值可能有多个。还有一种比较好的思路是使用有线队列来实现。

思路一:使用TreeMap实现。

public int[] maxSlidingWindow(int[] nums, int k) {
    if (nums.length == 0) {
        return new int[]{0};
    }
    TreeMap<Integer, Integer> treeMap = new TreeMap<>(Comparator.naturalOrder());
    int[] result = new int[nums.length - k + 1];
    int firstNum = nums[0], lastNum, currentNum, times;
    for (int i = 0; i < k; i++) {
        currentNum = nums[i];
        times = 1;
        if (treeMap.containsKey(currentNum)) {
            times = treeMap.get(currentNum) + 1;
        }
        treeMap.put(currentNum, times);
    }
    result[0] = treeMap.lastKey();
    // 从第二个开始
    for (int i = k; i < nums.length; i++) {
        // 移除第一个数
        times = treeMap.get(firstNum);
        if (times > 1) {
            treeMap.put(firstNum, times - 1);
        } else {
            treeMap.remove(firstNum);
        }
        // 重新设置最后一个数与第一个数
        firstNum = nums[i - k + 1];
        lastNum = nums[i];
        // 放入最后一个数
        times = 1;
        if (treeMap.containsKey(lastNum)) {
            times = treeMap.get(lastNum) + 1;
        }
        treeMap.put(lastNum, times);
        result[i - k + 1] = treeMap.lastKey();
    }
    return result;
}

思路二:使用有线队列

public int[] maxSlidingWindow(int[] nums, int k) {
    int n = nums.length;
    PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>() {
        public int compare(int[] pair1, int[] pair2) {
            return pair1[0] != pair2[0] ? pair2[0] - pair1[0] : pair2[1] - pair1[1];
        }
    });
    for (int i = 0; i < k; ++i) {
        pq.offer(new int[]{nums[i], i});
    }
    int[] ans = new int[n - k + 1];
    ans[0] = pq.peek()[0];
    for (int i = k; i < n; ++i) {
        pq.offer(new int[]{nums[i], i});
        while (pq.peek()[1] <= i - k) {
            pq.poll();
        }
        ans[i - k + 1] = pq.peek()[0];
    }
    return ans;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值