1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
public class MissingRanges { public List<String> findMissingRanges(int[] nums, int lower, int upper) { List<String> result = new ArrayList<String>(); int start = lower - 1; for (int i = 0; i <= nums.length; i++) { int end = (i == nums.length) ? upper + 1 : nums[i]; if (start + 2 <= end) { result.add(getItem(start + 1, end - 1)); } start = end; } return result; } private String getItem(int start, int end) { return (start == end) ? String.valueOf(start) : start + "->" + end; } @Test public void test() { int[] nums = new int[]{0, 1, 3, 50, 75}; List<String> result = findMissingRanges(nums, 0, 99); for (String s : result) { System.out.println(s); } } }
|