Algorithm: 数组类细节题

提纲:

163. Missing Ranges

228. Summary Ranges

56. Merge Intervals

57. Insert Interval


163. Missing Ranges

Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], return its missing ranges.
For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99, return ["2", "4->49", "51->74", "76->99"].


思路:没什么特别的难度,注意几个corner cases: 当给的数组是0长度的时候返回的应该是整个[lower, upper],lower和upper应该包含进去。而数组的元素不该包含。给的upper或者lower是最大或者最小的integer的时候,用Long解决。


class Solution {
    private String constructStr(long prev, long cur) {
        if (cur == prev) {
            return Long.toString(cur);
        } else {
            StringBuilder sb = new StringBuilder();
            sb.append(Long.toString(prev));
            sb.append("->");
            sb.append(Long.toString(cur));
            return sb.toString();
        }
    }
    
    public List<String> findMissingRanges(int[] nums, int lower, int upper) {
        List<String> res = new ArrayList<>();
        if (lower > upper) {
            return res;
        }
        
        if (nums == null || nums.length == 0) {
            res.add(constructStr(lower, upper));
            return res;
        }
        
        int n = nums.length;
        long cur = 0;
        long prev = (long)lower;
        
        for (int i = 0; i < n; ++i) {
            cur = (long)(nums[i]) - 1;
            if (cur >= prev) {
                res.add(constructStr(prev, cur));
            }
            prev = (long)(nums[i]) + 1;
        }
        
        if (upper >= prev) {
            res.add(constructStr(prev, upper));
        }
        return res;
    }
}



228. Summary Ranges


Given a sorted integer array without duplicates, return the summary of its ranges.

Example 1:
Input: [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Example 2:
Input: [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]


思路:与前一题逻辑相反。找连续的元素。(确认range -> 双指针比较)


To summarize the ranges, we need to know how to separate them. The array is sorted and without duplicates. In such array, two adjacent elements have difference either 1 or larger than 1. If the difference is 1, they should be put in the same range; otherwise, separate ranges.


We also need to know the start index of a range so that we can put it in the result list. Thus, we keep two indices, representing the two boundaries of current range. For each new element, we check if it extends the current range. If not, we put the current range into the list. 然后更新startIndex指针。


Don't forget to put the last range into the list. One can do this by either a special condition in the loop or putting the last range in to the list after the loop.


class Solution {
    private String buildStr(int begin, int end) {
        if (begin == end) {
            return Integer.toString(begin);
        } else {
            StringBuilder sb = new StringBuilder();
            sb.append(Integer.toString(begin));
            sb.append("->");
            sb.append(Integer.toString(end));
            return sb.toString();
        }
    }
    
    public List<String> summaryRanges(int[] nums) {
        List<String> res = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return res;
        }
        
        for (int i = 0, j = 0; j < nums.length; ++j) {
            if (j + 1 < nums.length && nums[j + 1] == nums[j] + 1) {
                continue;
            }
            // reach the end or incresing trend end
            res.add(buildStr(nums[i], nums[j]));
            // update the start. 
            i = j + 1;
        }
        return res;
    }
}


56. Merge Intervals


Given a collection of intervals, merge all overlapping intervals.

For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].


/**
 * 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; }
 * }
 */
class Solution {
    private class MyComparator implements Comparator<Interval> {
        @Override
        public int compare(Interval i1, Interval i2) {
            if (i1.start != i2.start) {
                return (new Integer(i1.start).compareTo(i2.start));
            } else {
                return (new Integer(i1.end).compareTo(i2.end));
            }
        }
    }
    
    public List<Interval> merge(List<Interval> intervals) {
        if (intervals == null || intervals.size() <= 1) {
            return intervals;
        }
        
        Collections.sort(intervals, new MyComparator());
        int index = 0;
        while (index < intervals.size() - 1) {
            Interval i1 = intervals.get(index);
            Interval i2 = intervals.get(index + 1);
            if (i2.start <= i1.end) {
                int newStart = i1.start;
                int newEnd = Math.max(i1.end, i2.end);
                intervals.remove(index);
                intervals.remove(index);
                intervals.add(index, new Interval(newStart, newEnd));
            } else {
                ++index;
            }
        }
        return intervals;
    }
}

57. Insert Interval


Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

You may assume that the intervals were initially sorted according to their start times.

Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].

Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].

This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].


/**
 * 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; }
 * }
 */
class Solution {
    private Interval mergeTwo(Interval i1, Interval i2) {
        Interval res = new Interval(Math.min(i1.start, i2.start), Math.max(i1.end, i2.end));
        return res;
    }
    
    public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
        if (intervals == null) {
            return intervals;
        }
        
        if (intervals.isEmpty()) {
            intervals.add(newInterval);
            return intervals;
        }
        
        if (newInterval.start < intervals.get(0).start && newInterval.end > intervals.get(intervals.size() - 1).end) {
            intervals.clear();
            intervals.add(newInterval);
            return intervals;
        }
        
        int n = intervals.size();
        
        for (int i = 0; i < n; ++i) {
            if (intervals.get(i).end < newInterval.start) {
                continue;
            }
            
            if (newInterval.end < intervals.get(i).start) {
                intervals.add(i, newInterval);
                return intervals;
            } else {
                Interval deleted = intervals.remove(i);
                return insert(intervals, mergeTwo(newInterval, deleted));
            }
        }
        // add to the last and return
        intervals.add(newInterval);
        return intervals;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值