classSolution: defnumberOfPoints(self, nums: List[List[int]]) -> int: max_end = max(end for _, end in nums) diff = [0] * (max_end + 2) for start, end in nums: diff[start] += 1 diff[end + 1] -= 1 returnsum(s > 0for s in accumulate(diff))
[sol-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { publicintnumberOfPoints(List<List<Integer>> nums) { vardiff=newint[102]; for (var p : nums) { diff[p.get(0)]++; diff[p.get(1) + 1]--; } intans=0, s = 0; for (int d : diff) { s += d; if (s > 0) { ans++; } } return ans; } }
[sol-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public: intnumberOfPoints(vector<vector<int>> &nums){ int diff[102]{}; for (auto &p: nums) { diff[p[0]]++; diff[p[1] + 1]--; } int ans = 0, s = 0; for (int d: diff) { s += d; ans += s > 0; } return ans; } };
[sol-Go]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
funcnumberOfPoints(nums [][]int) (ans int) { diff := [102]int{} for _, p := range nums { diff[p[0]]++ diff[p[1]+1]-- } s := 0 for _, d := range diff { s += d if s > 0 { ans++ } } return }
[sol-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13
var numberOfPoints = function(nums) { const diff = newArray(102).fill(0); for (const p of nums) { diff[p[0]]++; diff[p[1] + 1]--; } let ans = 0, s = 0; for (const d of diff) { s += d; ans += s > 0; } return ans; };
复杂度分析
时间复杂度:\mathcal{O}(n+\max{\textit{end}_i})。其中 n 为 nums 的长度。