1 题目描述
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"].
2 解题思路
1.通过+1判断是否为连续,如果连续则继续判断;如果不连续,则将前面连续的加入到List中。
2.最后将前一个添加进List中。
3 源代码
package com.larry.easy;
import java.util.ArrayList;
import java.util.List;
public class SummaryRanges {
public List<String> summaryRanges(int[] nums) {
List<String> ret = new ArrayList<String>();
int len = nums.length;
if(len == 0) ;
else if(len == 1) ret.add(String.valueOf(nums[0]));
else {
int first = nums[0], secd = nums[0];
for(int i = 1; i < len; i++){
//与前一个相邻
if(nums[i] == nums[i-1] + 1) secd = nums[i];
else{
//处理字符串
if(first == secd) ret.add(String.valueOf(first));
else ret.add(first + "->" + secd);
//处理两个标记
first = nums[i];
secd = nums[i];
}
}
//最后需要处理一次
if(first == secd) ret.add(String.valueOf(first));
else ret.add(first + "->" + secd);
}
return ret;
}
public static void main(String[] args) {
int[] arr = {0,1,2,4,5,7};
int[] nums = arr;
System.out.println(new SummaryRanges().summaryRanges(nums).toString());
}
}