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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,768评论 0 33
  • 前言 转眼已经到5月,可是我还没订17年的计划,真是悲伤的故事。今年还是想花点时间,玩玩题目。题目不会太简单,也不...
    落影loyinglin阅读 892评论 0 3
  • 1. 从 http://www.jetbrains.com/upsource/download/ 下载upsour...
    胡一道阅读 9,387评论 2 4
  • 【餐厅。杨妈烧好饭菜,喊儿子媳妇来吃饭。】 儿子:妈,你不吃? 杨妈:(搬了板凳去一边坐下)你们吃,我不饿的。 媳...
    东边木木阅读 502评论 0 2
  • 昨晚逛了西溪湿地,原本朋友们也是计划住悦榕庄或者喜来登,可我感觉这些地方没什么特别意思了。还贵! 想起这期民宿同学...
    蓝朵格格阅读 313评论 0 8