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

Missing Ranges

时间:2016-08-03 08:59:25      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

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

 1 public List<String> findMissingRanges(int[] nums, int lower, int upper) {
 2     List<String> list = new ArrayList<String>();
 3     if (nums == null)
 4         return list;
 5 
 6     if (nums.length == 0) {
 7         list.add(String.valueOf(lower) + "->" + String.valueOf(upper));
 8     }
 9 
10     for (int i = 0; i < nums.length - 1; i++) {
11         if (nums[i] + 2 < nums[i + 1]) {
12             list.add(String.valueOf(nums[i] + 1) + "->" + String.valueOf(nums[i + 1] - 1));
13         } else if (nums[i] + 2 == nums[i + 1]) {
14             list.add(String.valueOf(nums[i] + 1));
15         }
16     }
17 
18     if (lower + 1 == nums[0]) {
19         list.add(0, String.valueOf(lower + 1));
20     } else if (lower + 1 < nums[0]) {
21         list.add(0, String.valueOf(lower) + "->" + String.valueOf(nums[0] - 1));
22     }
23 
24     if (nums[nums.length - 1] + 1 == upper) {
25         list.add(String.valueOf(upper - 1));
26     } else if (nums[nums.length - 1] + 1 < upper) {
27         list.add(String.valueOf(nums[nums.length - 1] + 1) + "->" + String.valueOf(upper));
28     }
29     return list;
30 }

 

Missing Ranges

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5731418.html

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