My code:
public class Solution {
public List<String> findMissingRanges(int[] nums, int lower, int upper) {
List<String> ret = new ArrayList<String>();
if (nums == null) {
return ret;
}
else if (nums.length == 0) {
if (upper == lower) {
ret.add("" + lower);
return ret;
}
else {
ret.add(lower + "->" + upper);
return ret;
}
}
int pre = lower;
for (int i = 0; i < nums.length; i++) {
if (i == 0) {
if (nums[i] == pre + 1) {
ret.add("" + pre);
}
else if (nums[i] > pre + 1) {
ret.add(pre + "->" + (nums[i] - 1));
}
pre = nums[i];
}
else {
if (nums[i] == pre + 2) {
ret.add("" + (pre + 1));
}
else if (nums[i] > pre + 2) {
ret.add((pre + 1) + "->" + (nums[i] - 1));
}
pre = nums[i];
}
}
if (upper == pre + 1) {
ret.add("" + upper);
}
else if (upper > pre + 1) {
ret.add((pre + 1) + "->" + upper);
}
return ret;
}
}
个人感觉这道题目没什么意思。。
Anyway, Good luck, Richardo! — 09/04/2016
My code:
import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<String> findMissingRanges(int[] nums, int lower, int upper) {
List<String> ret = new ArrayList<String>();
long prev = (long) lower - 1;
for (int i = 0; i <= nums.length; i++) {
long curr = (i == nums.length ? upper + 1 : nums[i]);
if (curr - prev >= 2) {
ret.add(getRange(prev + 1, curr - 1));
}
prev = curr;
}
return ret;
}
private String getRange(long i, long j) {
if (i == j) {
return "" + i;
}
else {
return i + "->" + j;
}
}
}
reference:
https://tonycao.gitbooks.io/leetcode-locked/content/LeetCode%20Locked/c1.8.html
这种解法更简洁高效。
Anyway, Good luck, Richardo! — 10/16/2016