짬뽕얼큰하게의 맨땅에 헤딩 :: '2025/04/30 글 목록

'2025/04/30'에 해당되는 글 2건

Leetcode Problem:

Summary

  • Count numbers with even number of digits in an array

Approach

  • The approach used is to iterate through each number in the array and calculate the number of digits in each number using a helper function
  • If the number of digits is even, it increments the counter
  • Finally, it returns the count of numbers with even number of digits.

Complexity

  • O(n * log(max_num)) where n is the size of the array and max_num is the maximum number in the array

Explanation

  • The solution iterates through each number in the array
  • For each number, it calculates the number of digits using a helper function
  • If the number of digits is even, it increments the counter
  • The time complexity of the helper function is O(log(max_num)) and it is called for each number in the array
  • Therefore, the overall time complexity is O(n * log(max_num)) where n is the size of the array and max_num is the maximum number in the array.

Solution Code:


class Solution {
public:
    int getDigitNum(int num){
        int cnt = 0;
        while(num){
            num/=10;
            cnt++;
        }
        return cnt;
    }
    int findNumbers(vector& nums) {
        int ans = 0;
        for(int num : nums){
            if(getDigitNum(num) % 2){
                continue;
            }
            ans++;
        }
        return ans;
    }
};
블로그 이미지

짬뽕얼큰하게

,

Leetcode Problem:

Summary

  • The problem requires finding the number of subarrays in a given array where the maximum element appears at least k times.

Approach

  • The approach used is to first identify the maximum element and its corresponding subarray
  • Then, we iterate over the subarray and count the number of subarrays that contain the maximum element at least k times.

Complexity

  • O(n), where n is the size of the input array.

Explanation

  • The solution first creates a vector to store the indices of the maximum element in the subarray
  • It then iterates over the array to find the maximum element and its indices
  • After that, it calculates the number of subarrays that contain the maximum element at least k times by iterating over the vector and counting the subarrays.

Solution Code:


class Solution {
public:
    vector v;
    long long countSubarrays(vector& nums, int k) {
        int maxV = 0;
        for(int i = 0 ; i < nums.size(); i++){
            if(maxV < nums[i]){
                maxV = nums[i];
                v.clear();
                v.push_back(i);
            } else if (maxV == nums[i]){
                v.push_back(i);
            }
        }
        v.push_back(nums.size());
        
        long long ans = 0;
        for(int i = k-1; i < v.size()-1; i++){
            long long r = v[i];
            long long l = v[i - k+1];
            ans += (l+1) * (v[i+1]-r);
        }
        return ans;
    }
};
블로그 이미지

짬뽕얼큰하게

,