koenjazh-CNfresde
짬뽕얼큰하게의 맨땅에 헤딩 :: Find the Power of K-Size Subarrays I

Leetcode Problem:

Summary

  • This solution is used to find the power of all subarrays of size k in a given array of integers
  • The power of a subarray is defined as its maximum element if all its elements are consecutive and sorted in ascending order, otherwise -1.

Approach

  • This solution uses a sliding window approach with two nested loops to check for consecutive elements
  • It keeps track of the current window's start index, end index, and the count of consecutive elements
  • If the count of consecutive elements equals k, the maximum element in the current window is added to the result array
  • Otherwise, -1 is added.

Complexity

  • O(n*k) where n is the size of the input array, k is the size of the subarray

Solution Code:


class Solution {
public:
    vector resultsArray(vector& nums, int k) {
        vector ans;
        int acd_cnt = 1;
        int cmp_num = nums[0];
        for(int i = 1 ; i < k ;i++){
            if(cmp_num + 1 == nums[i]){
                acd_cnt++;
            } else {
                acd_cnt = 1;
            }
            cmp_num = nums[i];
        }
        if(acd_cnt == k){
            ans.push_back(cmp_num);
        } else {
            ans.push_back(-1);
        }
        for(int i = k ; i < nums.size(); i++){
            if(cmp_num + 1 == nums[i]){
                acd_cnt++;
            } else {
                acd_cnt = 1;
            }
            if(acd_cnt >= k){
                ans.push_back(nums[i]);
            } else {
                ans.push_back(-1);
            }
            cmp_num = nums[i];
        }
        return ans;
    }
};
블로그 이미지

짬뽕얼큰하게

,