力扣(leetcode)每日一题 3255 长度为 K 的子数组的能量值 II|滑动窗口

3255. Find the Power of K-Size Subarrays II

1.题干

You are given an array of integers nums of length n and a positive integer k.

The power of an array is defined as:

  • Its maximum element if all of its elements are consecutive and sorted in ascending order.
  • -1 otherwise.

You need to find the power of all

subarrays

of nums of size k.

Return an integer array results of size n - k + 1, where results[i] is the power of nums[i..(i + k - 1)].

Example 1:

Input: nums = [1,2,3,4,3,2,5], k = 3

Output: [3,4,-1,-1,-1]

Explanation:

There are 5 subarrays of nums of size 3:

  • [1, 2, 3] with the maximum element 3.
  • [2, 3, 4] with the maximum element 4.
  • [3, 4, 3] whose elements are not consecutive.
  • [4, 3, 2] whose elements are not sorted.
  • [3, 2, 5] whose elements are not consecutive.

Example 2:

Input: nums = [2,2,2,2,2], k = 4

Output: [-1,-1]

Example 3:

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

Output: [-1,3,-1,3,-1]

2.题解

滑动窗口,常规解法

java 复制代码
  
public static int[] resultsArray(int[] nums, int k) { //3  
    LinkedList<Integer> list = new LinkedList<>();  
    for (int i = 0; i < k - 1; i++) {  
        // 保证队列一次从小到大差值1排列  
        while (!list.isEmpty() && nums[list.getLast()] != (nums[i] - 1)) {  
            list.pollLast();  
        }  
        list.add(i);  
    }  
    int[] res = new int[nums.length - k + 1];  
    for (int i = k - 1; i < nums.length; i++) {  
        // 保证队列一次从小到大差值1排列  
        while (!list.isEmpty() && nums[list.getLast()] != (nums[i] - 1)) {  
            list.pollLast();  
        }  
        list.add(i);  
        // 如果队列数量和k相等,就是成立的  
        if (list.size() == k) {  
            res[i - k + 1] = nums[i];  
        } else {  
            res[i - k + 1] = -1;  
        }  
        // 加入当前为index 6,然后队列长度k为3,那么对于index 4的数据进行弹出,确保下个循环index 7进来之后,队列长度维持在k为3  
        if (list.getFirst() == i - k + 1) {  
            list.pollFirst();  
        }  
    }  
    return res;  
}

官方题解,属于技巧性

java 复制代码
public int[] resultsArray(int[] nums, int k) {  
    int n = nums.length;  
    int[] ans = new int[n - k + 1];  
    Arrays.fill(ans, -1);  
    int cnt = 0;  
    for (int i = 0; i < n; i++) {  
        cnt = i == 0 || nums[i] - nums[i - 1] != 1 ? 1 : cnt + 1;  
        // 当连续数的时候,累计加上1  
        if (cnt >= k) {  
            ans[i - k + 1] = nums[i];  
        }  
    }  
    return ans;  
}
3.总结

面试编程时候肯定思维紧张,往滑动窗口上靠就对了

相关推荐
海的诗篇_3 分钟前
移除元素-JavaScript【算法学习day.04】
javascript·学习·算法
自动驾驶小卡14 分钟前
A*算法实现原理以及实现步骤(C++)
算法
Unpredictable22215 分钟前
【VINS-Mono算法深度解析:边缘化策略、初始化与关键技术】
c++·笔记·算法·ubuntu·计算机视觉
编程绿豆侠16 分钟前
力扣HOT100之多维动态规划:1143. 最长公共子序列
算法·leetcode·动态规划
珂朵莉MM22 分钟前
2021 RoboCom 世界机器人开发者大赛-高职组(初赛)解题报告 | 珂学家
java·开发语言·人工智能·算法·职场和发展·机器人
fail_to_code1 小时前
递归法的递归函数何时需要返回值
算法
C137的本贾尼1 小时前
(每日一道算法题)二叉树剪枝
算法·机器学习·剪枝
BUG收容所所长3 小时前
栈的奇妙世界:从冰棒到算法的华丽转身
前端·javascript·算法
XRZaaa3 小时前
常见排序算法详解与C语言实现
c语言·算法·排序算法
@我漫长的孤独流浪3 小时前
数据结构测试模拟题(4)
数据结构·c++·算法