题目:
Given a sorted integer array where the range of elements are [0, 99] inclusive, return its
missing ranges.
For example, given [0, 1, 3, 50, 75], return [“2”, “4->49”, “51->74”, “76->99”]
解答:
1 public class Solution { 2 3 public static void main(String[] args) { 4 int[] arr = {0,1,3,50,75}; 5 int start = 0; 6 int end = 99; 7 8 List<String> results = findMissingRanges(arr, start, end); 9 } 10 11 public List<String> findMissingRanges(int[] vals, int start, int end) { 12 List<String> ranges = new ArrayList<>(); 13 int prev = start - 1; 14 for(int i = 0; i <= vals.length; i++) { 15 int curr = (i == vals.length)?end+1:vals[i]; 16 if(curr - prev >= 2) { 17 ranges.add(getRange(prev+1, curr-1)); 18 } 19 20 prev = curr; 21 } 22 23 return ranges; 24 } 25 26 private String getRange(int from, int to) { 27 return (from == to)?String.valueOf(from):from+"->" + to; 28 } 29 }