classSolution: deflongestEqualSubarray(self, nums: List[int], k: int) -> int: pos = [[] for _ inrange(len(nums) + 1)] for i, x inenumerate(nums): pos[x].append(i - len(pos[x])) ans = 0 for ps in pos: iflen(ps) <= ans: continue left = 0 for right, p inenumerate(ps): while p - ps[left] > k: # 要删除的数太多了 left += 1 ans = max(ans, right - left + 1) return ans
classSolution { publicintlongestEqualSubarray(List<Integer> nums, int k) { intn= nums.size(), ans = 0; List<Integer>[] pos = newArrayList[n + 1]; Arrays.setAll(pos, e -> newArrayList<>()); for (inti=0; i < n; i++) { intx= nums.get(i); pos[x].add(i - pos[x].size()); } for (var ps : pos) { if (ps.size() <= ans) continue; intleft=0; for (intright=0; right < ps.size(); right++) { while (ps.get(right) - ps.get(left) > k) // 要删除的数太多了 left++; ans = Math.max(ans, right - left + 1); } } return ans; } }
[sol-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { public: intlongestEqualSubarray(vector<int> &nums, int k){ int n = nums.size(), ans = 0; vector<vector<int>> pos(n + 1); for (int i = 0; i < n; i++) pos[nums[i]].push_back(i - pos[nums[i]].size()); for (auto &ps: pos) { if (ps.size() <= ans) continue; int left = 0; for (int right = 0; right < ps.size(); right++) { while (ps[right] - ps[left] > k) // 要删除的数太多了 left++; ans = max(ans, right - left + 1); } } return ans; } };
funclongestEqualSubarray(nums []int, k int) (ans int) { pos := make([][]int, len(nums)+1) for i, x := range nums { pos[x] = append(pos[x], i-len(pos[x])) } for _, ps := range pos { iflen(ps) <= ans { continue } left := 0 for right, p := range ps { for p-ps[left] > k { // 要删除的数太多了 left++ } ans = max(ans, right-left+1) } } return }
funcmax(a, b int)int { if b > a { return b }; return a }