Google - 1

Question

Given an array of integers and a list of intervals with no over overlap between any two intervals, find a list integers from above array, which is in one of interval in above list of intervals

Algorithm

  • Sort intervals according their start time in increasing order
  • use binary search to check if the integer in one of intervals
    • set start point 0 and end point length of list minus 1
    • get mid point and check if the integer in midth interval
      • if the integer in midth interval, add the integer to output list of integer
      • if the integer is less than the start time of midth interval, set end mid - 1
      • if the integer is greater than the end time of midth interval, set start mid + 1
      • loops until start is greater than end

Complexity

  • time complexity: O(NlgN)
    • sort: O(NlgN)
    • find: O(lgN)
    • loops: O(N)
  • space complexity: O(N)
    • space of output list

Code

/**
 * Definition for an interval.
 * public class Interval {
 *     int start;
 *     int end;
 *     Interval() { start = 0; end = 0; }
 *     Interval(int s, int e) { start = s; end = e; }
 * }
 */
public List<Integer> findNum(List<Interval> intervals, int[] nums) {
    List<Integer> result = new ArrayList<Integer>();
    if (nums == null || intervals == null) {        
        return result;
    }
    for (int num: nums) {
        if (checkInterval(intervals, num)) {
            result.add(num);
        }
    }
    return result;
}
private boolean checkInterval(List<Interval> intervals, int num) {
    int start = 0;
    int end = intervals.size() - 1;
    while (start <= end) {
        int mid = start + (end - start) / 2;
        int check = checkBelong(intervals.get(mid), num);
        if (check == 0) {
            return true;
        } else if (check == -1) {
            end = mid - 1;
        } else {
            start = mid + 1;
        }
    }
    return false;
}
private int checkBelong(Interval interval, int num) {
    if (num >= interval.start && num <= interval.end) {
        return 0;
    } else if (num < interval.start) {
        return -1;
    } else {        
        return 1;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,935評論 0 33
  • 前言 轉(zhuǎn)眼已經(jīng)到5月,可是我還沒訂17年的計劃,真是悲傷的故事。今年還是想花點時間,玩玩題目。題目不會太簡單,也不...
    落影l(fā)oyinglin閱讀 1,025評論 0 3
  • 1. 從 http://www.jetbrains.com/upsource/download/ 下載upsour...
    胡一道閱讀 9,574評論 2 4
  • 【餐廳。楊媽燒好飯菜,喊兒子媳婦來吃飯?!?兒子:媽,你不吃? 楊媽:(搬了板凳去一邊坐下)你們吃,我不餓的。 媳...
    東邊木木閱讀 587評論 0 2
  • 昨晚逛了西溪濕地,原本朋友們也是計劃住悅榕莊或者喜來登,可我感覺這些地方?jīng)]什么特別意思了。還貴! 想起這期民宿同學(xué)...
    藍朵格格閱讀 336評論 0 8

友情鏈接更多精彩內(nèi)容