classSolution: defcontinuousSubarrays(self, nums: List[int]) -> int: ans = left = 0 cnt = Counter() for right, x inenumerate(nums): cnt[x] += 1 whilemax(cnt) - min(cnt) > 2: y = nums[left] cnt[y] -= 1 if cnt[y] == 0: del cnt[y] left += 1 ans += right - left + 1 return ans
[sol-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { publiclongcontinuousSubarrays(int[] nums) { longans=0; vart=newTreeMap<Integer, Integer>(); intleft=0; for (intright=0; right < nums.length; right++) { t.merge(nums[right], 1, Integer::sum); while (t.lastKey() - t.firstKey() > 2) { inty= nums[left++]; if (t.get(y) == 1) t.remove(y); else t.merge(y, -1, Integer::sum); } ans += right - left + 1; } return ans; } }
[sol-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { public: longlongcontinuousSubarrays(vector<int> &nums){ longlong ans = 0; multiset<int> s; int left = 0, n = nums.size(); for (int right = 0; right < n; right++) { s.insert(nums[right]); while (*s.rbegin() - *s.begin() > 2) s.erase(s.find(nums[left++])); ans += right - left + 1; } return ans; } };
funccontinuousSubarrays(a []int) (ans int64) { cnt := map[int]int{} left := 0 for right, x := range a { cnt[x]++ for { mx, mn := x, x for k := range cnt { mx = max(mx, k) mn = min(mn, k) } if mx-mn <= 2 { break } y := a[left] if cnt[y]--; cnt[y] == 0 { delete(cnt, y) } left++ } ans += int64(right - left + 1) } return }
funcmax(a, b int)int { if b > a { return b }; return a } funcmin(a, b int)int { if b < a { return b }; return a }