classSolution { public: inttotalFruit(vector<int>& fruits){ int n = fruits.size(); unordered_map<int, int> cnt;
int left = 0, ans = 0; for (int right = 0; right < n; ++right) { ++cnt[fruits[right]]; while (cnt.size() > 2) { auto it = cnt.find(fruits[left]); --it->second; if (it->second == 0) { cnt.erase(it); } ++left; } ans = max(ans, right - left + 1); } return ans; } };
publicclassSolution { publicintTotalFruit(int[] fruits) { int n = fruits.Length; IDictionary<int, int> cnt = new Dictionary<int, int>();
int left = 0, ans = 0; for (int right = 0; right < n; ++right) { cnt.TryAdd(fruits[right], 0); ++cnt[fruits[right]]; while (cnt.Count > 2) { --cnt[fruits[left]]; if (cnt[fruits[left]] == 0) { cnt.Remove(fruits[left]); } ++left; } ans = Math.Max(ans, right - left + 1); } return ans; } }
left = ans = 0 for right, x inenumerate(fruits): cnt[x] += 1 whilelen(cnt) > 2: cnt[fruits[left]] -= 1 if cnt[fruits[left]] == 0: cnt.pop(fruits[left]) left += 1 ans = max(ans, right - left + 1) return ans
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
var totalFruit = function(fruits) { const n = fruits.length; const cnt = newMap();
let left = 0, ans = 0; for (let right = 0; right < n; ++right) { cnt.set(fruits[right], (cnt.get(fruits[right]) || 0) + 1); while (cnt.size > 2) { cnt.set(fruits[left], cnt.get(fruits[left]) - 1); if (cnt.get(fruits[left]) == 0) { cnt.delete(fruits[left]); } ++left; } ans = Math.max(ans, right - left + 1); } return ans; };