Given an integer array nums and an integer k, return the number of good subarrays of nums.
A subarray arr is good if it there are at least k pairs of indices (i, j) such that i < j and arr[i] == arr[j].
A subarray is a contiguous non-empty sequence of elements within an array.
題目會給我們一組整數陣列nums和一個整數k,我們要找出「好的子陣列」並返回數量。
好的子陣列其中至少有k對(i,j),使得i小於j而且arr[i]==arr[j]。
我的解題思路:
class Solution {
public long countGood(int[] nums, int k) {
int n = nums.length;
int countGood = 0;
// 遍歷所有子陣列
for (int start = 0; start<n ; start++) {
int pair = 0; // 每個子陣列配對數獨立計算!!
for (int end =start; end<n ; end++) {
for (int i = start; i < end; i++) {
if (nums[i] == nums[end]) {
pair++;
}
}
if (pair >= k) {
countGood++;
}
}
}
return countGood;
}
}
我一開始的‘int pair = 0’放在第二層for迴圈裡,這導致它只考慮目前end的配對,放在start那層才會包含整個子陣列,總之修正後成功過關!