leetcode-2251:花期内花的数目

 

void merge_sort(int** arr, int l, int r, int ind) {
	if (r - l <= 1) return;
	int mid = (r + l) / 2;
	merge_sort(arr, l, mid, ind);
	merge_sort(arr, mid, r, ind);
	int p1 = l, p2 = mid, k = 0;
	int* temp = (int*)malloc(sizeof(int) * (r - l));
	while (p1 < mid || p2 < r) {
		if (p2 == r || (p1 < mid && arr[p1][ind] < arr[p2][ind])) {
			temp[k++] = arr[p1++][ind];
		}
		else {
			temp[k++] = arr[p2++][ind];
		}
	}
	for (int i = l; i < r; i++) arr[i][ind] = temp[i - l];
	free(temp);
	return;
}

int binary_search(int** arr, int l, int r, int t, int ind) {
	if (t < arr[l][ind]) return 0;
	if (t >= arr[r][ind]) return r + 1;
	while (l < r) {
		int mid = (l + r + 1) / 2;
		if (t >= arr[mid][ind]) {
			l = mid;
		}
		else {
			r = mid - 1;
		}
	}
	return l + 1;
}

int* fullBloomFlowers(int** flowers, int flowersSize, int* flowersColSize, int* people, int peopleSize, int* returnSize) {
	merge_sort(flowers, 0, flowersSize, 0);
	merge_sort(flowers, 0, flowersSize, 1);
	for (int i = 0; i < peopleSize; i++) {
		int x = binary_search(flowers, 0, flowersSize - 1, people[i], 0);
		int l = binary_search(flowers, 0, flowersSize - 1, people[i] - 1, 1);
		people[i] = x - l;
	}
	*returnSize = peopleSize;
	return people;
}

你可能感兴趣的:(算法题,leetcode,算法)