classSolution: defnumberOfArithmeticSlices(self, nums: List[int]) -> int: ans = 0 f = [defaultdict(int) for _ in nums] for i, x inenumerate(nums): for j inrange(i): d = x - nums[j] cnt = f[j][d] ans += cnt f[i][d] += cnt + 1 return ans
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { public: intnumberOfArithmeticSlices(vector<int> &nums){ int ans = 0; int n = nums.size(); vector<unordered_map<longlong, int>> f(n); for (int i = 0; i < n; ++i) { for (int j = 0; j < i; ++j) { longlong d = 1LL * nums[i] - nums[j]; auto it = f[j].find(d); int cnt = it == f[j].end() ? 0 : it->second; ans += cnt; f[i][d] += cnt + 1; } } return ans; } };
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { publicintnumberOfArithmeticSlices(int[] nums) { intans=0; intn= nums.length; Map<Long, Integer>[] f = newMap[n]; for (inti=0; i < n; ++i) { f[i] = newHashMap<Long, Integer>(); } for (inti=0; i < n; ++i) { for (intj=0; j < i; ++j) { longd=1L * nums[i] - nums[j]; intcnt= f[j].getOrDefault(d, 0); ans += cnt; f[i].put(d, f[i].getOrDefault(d, 0) + cnt + 1); } } return ans; } }
publicclassSolution { publicintNumberOfArithmeticSlices(int[] nums) { int ans = 0; int n = nums.Length; Dictionary<long, int>[] f = new Dictionary<long, int>[n]; for (int i = 0; i < n; ++i) { f[i] = new Dictionary<long, int>(); } for (int i = 0; i < n; ++i) { for (int j = 0; j < i; ++j) { long d = 1L * nums[i] - nums[j]; int cnt = f[j].ContainsKey(d) ? f[j][d] : 0; ans += cnt; if (f[i].ContainsKey(d)) { f[i][d] += cnt + 1; } else { f[i].Add(d, cnt + 1); } } } return ans; } }
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13
funcnumberOfArithmeticSlices(nums []int) (ans int) { f := make([]map[int]int, len(nums)) for i, x := range nums { f[i] = map[int]int{} for j, y := range nums[:i] { d := x - y cnt := f[j][d] ans += cnt f[i][d] += cnt + 1 } } return }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
var numberOfArithmeticSlices = function(nums) { let ans = 0; const n = nums.length; const f = newMap(); for (let i = 0; i < n; ++i) { f[i] = newMap(); } for (let i = 0; i < n; ++i) { for (let j = 0; j < i; ++j) { const d = nums[i] - nums[j]; const cnt = f[j].get(d) || 0; ans += cnt; f[i].set(d, (f[i].get(d) || 0) + cnt + 1); } } return ans; };