본문 바로가기
LeetCode/Sliding Window

[LeetCode][Kotlin] 992. Subarrays with K Different Integers

by jinwo_o 2024. 11. 22.

992. Subarrays with K Different Integers

Given an integer array nums and an integer k, return the number of good subarrays of nums.

good array is an array where the number of different integers in that array is exactly k.

  • For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3.

subarray is a contiguous part of an array.

정수 배열 nums와 정수 k가 주어지면 nums의 좋은 부분 배열의 개수를 반환합니다. 

좋은 배열은 해당 배열의 다른 정수의 개수가 정확히 k인 배열입니다. 
- 예를 들어, [1,2,3,1,2]에는 1, 2, 3의 세 가지 다른 정수가 있습니다. 

부분 배열은 배열의 연속된 부분입니다.

 

Example 1:

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

Output: 7

Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2]

 

Example 2:

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

Output: 3

Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].

 

Constraints:

  • 1 <= nums.length <= 2 * 10^4
  • 1 <= nums[i], k <= nums.length

코드

  • Example 1 : [1, 2] / [(1, 2), 1], [2, 1] / [(1, 2, 1), 2], [(2, 1), 2], [(1, 2)] / [2, 3]
class Solution {
    fun subarraysWithKDistinct(nums: IntArray, k: Int): Int {
        val count = HashMap<Int, Int>()
        var res = 0
        var l_far = 0
        var l_near = 0

        for (r in nums.indices) {
            count[nums[r]] = count.getOrDefault(nums[r], 0) + 1

            while (count.size > k) {
                count[nums[l_near]] = count[nums[l_near]]!! - 1
                if (count[nums[l_near]] == 0) {
                    count.remove(nums[l_near])
                }

                l_near++
                l_far = l_near
            }

            while (count[nums[l_near]]!! > 1) {
                count[nums[l_near]] = count[nums[l_near]]!! - 1
                l_near++
            }

            if (count.size == k) {
                res += l_near - l_far + 1
            }
        }

        return res
    }
}