标签:
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 }
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5731418.html