企業(yè)網(wǎng)站建設參考資料競價推廣賬戶競價托管
給你一個下標從?0?開始的二維整數(shù)數(shù)組?flowers
?,其中?flowers[i] = [starti, endi]
?表示第?i
?朵花的?花期?從?starti
?到?endi
?(都?包含)。同時給你一個下標從?0?開始大小為?n
?的整數(shù)數(shù)組?people
?,people[i]
?是第?i
?個人來看花的時間。
請你返回一個大小為?n
?的整數(shù)數(shù)組?answer
?,其中?answer[i]
是第?i
?個人到達時在花期內(nèi)花的?數(shù)目?。
示例 1:
輸入:flowers = [[1,6],[3,7],[9,12],[4,13]], people = [2,3,7,11] 輸出:[1,2,2,2] 解釋:上圖展示了每朵花的花期時間,和每個人的到達時間。 對每個人,我們返回他們到達時在花期內(nèi)花的數(shù)目。
示例 2:
輸入:flowers = [[1,10],[3,3]], people = [3,3,2] 輸出:[2,2,1] 解釋:上圖展示了每朵花的花期時間,和每個人的到達時間。 對每個人,我們返回他們到達時在花期內(nèi)花的數(shù)目。
提示:
1 <= flowers.length <= 5 * 104
flowers[i].length == 2
1 <= starti <= endi <= 109
1 <= people.length <= 5 * 104
1 <= people[i] <= 109
答:
import java.util.Arrays;public class Solution {public int[] numFlowersInBloom(int[][] flowers, int[] people) {Arrays.sort(flowers, (a, b) -> Integer.compare(a[1], b[1])); // 按結(jié)束時間排序int n = people.length;int[] answer = new int[n];int ptr = 0; // 指向當前未被看的花期for (int i = 0; i < n; i++) {int arriveTime = people[i];// 找到所有結(jié)束時間小于等于arriveTime的花期,并統(tǒng)計花的數(shù)量while (ptr < flowers.length && flowers[ptr][1] <= arriveTime) {if (flowers[ptr][0] <= arriveTime) { // 花期的開始時間小于等于arriveTimeanswer[i]++;}ptr++;}}return answer;}public static void main(String[] args) {Solution solution = new Solution();int[][] flowers = {{1,6},{3,7},{9,12},{4,13}};int[] people = {2,3,7,11};int[] result = solution.numFlowersInBloom(flowers, people);System.out.println(Arrays.toString(result)); // 輸出:[1, 2, 2, 2]}
}