代码实现:
方法一:哈希表
#define fmax(a, b) ((a) > (b) ? (a) : (b))int numberOfPoints(int **nums, int numsSize, int *numsColSize) {int hash[101] = {0};int max = 0;for (int i = 0; i < numsSize; i++) {max = fmax(max, nums[i][1]);for (int j = nums[i][0]; j <= nums[i][1]; j++) {if (hash[j] == 0) {hash[j] = 1;}}}int cnt = 0;for (int i = 0; i <= max; i++) {if (hash[i]) {cnt++;}}return cnt; }
方法二:排序 + 合并
// 交换 void swap(int *m, int *n) {int temp = *m;*m = *n;*n = temp; }// 快排 void sort(int **nums, int l, int r) { // 左闭右开if (r - l <= 2) {if (r - l <= 1) { // 剩余个数:<= 1return;} if (nums[r - 1][0] < nums[l][0]) { // 剩余个数:= 2 且后者小于前者 交换swap(&nums[r - 1][0], &nums[l][0]);swap(&nums[r - 1][1], &nums[l][1]);}return;}int x = nums[l][0];int y = nums[l][1];int i = l, j = r - 1;while (i < j) {while (i < j && nums[j][0] >= x) {j--;}if (i < j) {nums[i][0] = nums[j][0];nums[i][1] = nums[j][1];i++;}while (i < j && nums[i][0] <= x) {i++;}if (i < j) {nums[j][0] = nums[i][0];nums[j][1] = nums[i][1];j--;}}nums[i][0] = x, nums[i][1] = y;sort(nums, l, i);sort(nums, i + 1, r); }int numberOfPoints(int **nums, int numsSize, int *numsColSize) {// 排序sort(nums, 0, numsSize);// 合并int res[numsSize][2];int resSize = 0;int l = nums[0][0];int r = nums[0][1];for (int i = 1; i < numsSize; i++) {if (r >= nums[i][0]) {r = r > nums[i][1] ? r : nums[i][1];} else {res[resSize][0] = l;res[resSize++][1] = r;l = nums[i][0];r = nums[i][1];}}// 记录合并的最后一个区间res[resSize][0] = l;res[resSize++][1] = r;int cnt = 0;for (int i = 0; i < resSize; i++) {cnt += res[i][1] - res[i][0] + 1;}return cnt; }