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”].
题目比较easy直接上代码。解法较啰嗦。
package array;
import java.util.ArrayList;
import java.util.List;
public class SummaryRanges {
class Str {
private int pre;
private int aft;
private int temp;
public String toString() {
if(this.pre == this.aft){
return ""+this.pre;
}
return this.pre + "->" + this.aft;
}
}
public List<String> summaryRanges(int[] nums) {
List<String> res = new ArrayList<String>();
if (nums.length < 1) {
return res;
} else {
Str str = new Str();
str.pre=nums[0];
str.temp=nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] - str.temp == 1) {
str.temp = nums[i];
} else {
str.aft = str.temp;
res.add(str.toString());
str.pre = nums[i];
str.temp = nums[i];
}
}
str.aft = str.temp;
res.add(str.toString());
}
return res;
}
public static void main(String[] args) {
int[] arr = { 0, 1, 2, 4, 5, 7};
System.out.println(new SummaryRanges().summaryRanges(arr));
}
}