码迷,mamicode.com
首页 > 其他好文 > 详细

Missing Ranges

时间:2016-08-06 13:04:03      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

Given a sorted integer array where the range of elements are [lowerupper] inclusive, 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"].

 

public class Solution {
   public List<String> findMissingRanges(int[] nums, int lower, int upper) {
        List<String> list = new ArrayList<String>();
        if(nums == null) return list;
        int n = nums.length;
        for(int i = 0; i <= n; i++) {
            int lt = (i == 0) ? lower : nums[i - 1] + 1;
            int gt = (i == n) ? upper : nums[i] - 1;
            addRange(list, lt, gt);
        }
        return list;
    }
    private void addRange(List<String> list, int lo, int hi) {
        if(lo > hi) return;
        else if(lo == hi) list.add(String.valueOf(lo));
        else list.add(lo + "->" + hi);
    }
}

reference: https://discuss.leetcode.com/topic/36991/simple-java-code

Missing Ranges

标签:

原文地址:http://www.cnblogs.com/hygeia/p/5743706.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!