标签:ges private find add for builder void range return
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"].
遍历数组,如果arr[i] > arr[i-1] + 1则说明arr[i]与arr[i-1]中有missing range。注意考虑开头和结尾。
1 public class Solution { 2 public List<String> findMissingRanges(int[] nums, int lower, int upper) { 3 List<String> result = new ArrayList<>(); 4 if (nums == null || nums.length == 0) { 5 addRange(result, lower, upper); 6 return result; 7 } 8 int len = nums.length; 9 // process head 10 if (nums[0] > lower) { 11 addRange(result, lower, nums[0] - 1); 12 } 13 for (int i = 1; i < len; i++) { 14 if (nums[i] > nums[i - 1] + 1) { 15 addRange(result, nums[i - 1] + 1, nums[i] - 1); 16 } 17 } 18 // process tail 19 if (nums[len - 1] < upper) { 20 addRange(result, nums[len - 1] + 1, upper); 21 } 22 return result; 23 } 24 25 private void addRange(List<String> result, int low, int high) { 26 StringBuilder sb = new StringBuilder(); 27 sb.append(low); 28 if (high > low) { 29 sb.append("->"); 30 sb.append(high); 31 } 32 result.add(sb.toString()); 33 } 34 }
标签:ges private find add for builder void range return
原文地址:http://www.cnblogs.com/ireneyanglan/p/6018118.html