[leetcode]summary ranges and missing ranges

题目描述

Given a sorted integer array without duplicates, return the summary of its ranges.

For example, given [0,1,2,4,5,7], return [“0->2”,”4->5”,”7”].

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Solution{

//使用for循环遍历数组,对每一个元素不断与右边的元素相比较,如果相差为1则还是同一个连续区间,
//下标i++,直到与右边元素之差不唯一则找到了一个连续区间
public List<String> summaryRanges(int[] nums) {
List<String> res = new ArrayList<>();
if(nums == null || nums.length == 0) return res;
for(int i = 0; i < nums.length; i++){
int temp = nums[i];
while(i+1 < nums.length && nums[i+1] - nums[i] == 1) i++;

if(nums[i] != temp){
res.add(temp + "->" + nums[i]);
}else{
res.add(temp+"");
}
}

return res;
}
}

题目描述

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”]

You should be able to extend the above cases not only for the range [0,99], but any arbitrary range [start, end].

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Solution{
public List<String> getMissingRanges(int[] nums, int start, int end){
List<String> ranges = new ArrayList<>();

int prev = start - 1;
for(int i = 0; i <= nums.length; i++){
int curr = (i == nums.length) ? end + 1 : nums[i];
if(curr - prev >= 2){
ranges.add(getRange(prev + 1, curr - 1));
}
prev = curr;
}
return ranges;
}

private String (int from, int to){
return from == to ? String.valueOf(from) : from + "->" + to;
}
}