LeetCode 3254. Find the Power of K-Size Subarrays I

38 阅读1分钟

🔗 leetcode.com/problems/fi…

题目

  • 定义数组的 power 值

    • 若数组是连续升序,power 值为数组的最大值,也就是最后一位;
    • 否则为 -1
  • 给定一个数组 nums,给定子数组长度 k,返回 nums 所有的长度为 k 的子数组的 power 值

思路

  • 记录以当前元素 nums[i] 为结尾,连续升序数组的最大长度
  • 若该长度大于 k,以当前元素 nums[i] 为结尾的子数组的 power 值就为当前元素 nums[i] ,否则为 -1
  • solution1 是朴素实现,solution 2 优化时间和空间使用,打败 100%

代码

class Solution {
public:
    vector<int> solution1(vector<int>& nums, int k) {
        int size = nums.size();
        vector<int> power(size);
        power[0] = 1;
        for (int i = 1; i < nums.size(); i++) {
            if (nums[i] - nums[i-1] != 1) power[i] = 1;
            else power[i] = power[i-1]+1;
        }
        vector<int> ans;
        for (int i = k-1; i < size; i++) {
            if (power[i] >= k) ans.push_back(nums[i]);
            else ans.push_back(-1);
        }
        return ans;
    }

    vector<int> solution2(vector<int>& nums, int k) {
        int size = nums.size();
        int power = 1;
        vector<int> ans;
        if (k == 1) ans.push_back(nums[0]);
        for (int i = 1; i < nums.size(); i++) {
            if (nums[i] - nums[i-1] != 1) power = 1;
            else power++;
            if (i >= k -1) {
                if (power >= k) ans.push_back(nums[i]);
                else ans.push_back(-1);
            }
        }
        return ans;
    }
    vector<int> resultsArray(vector<int>& nums, int k) {
        //return solution1(nums, k);
        return solution2(nums, k);
    }
};