Interview Questions

Google - 1

2016-03-22  本文已影响9人  宋翰要长肉

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

Complexity

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;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读