题目链接:https://leetcode.com/problems/summary-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"].
示例代码:
public class Solution { public static void main(String[] args) { int nums[]=new int[]{1,2,4,5,7}; List<String> rList=new Solution().summaryRanges(nums); for(String str:rList) { System.out.println(str); } } public List<String> summaryRanges(int[] nums) { List<String> result=new ArrayList<String>(); int startLine=0; //起始位置 int endLine=0; //结束位置 int num=0; //扫描计数 for(int i=0;i<nums.length;i++) { int j=i; int k=j+1; if(k<nums.length) { //后面的数>当前数+1,且只扫描了一个数,就将该数放入result中 if(nums[k]>(nums[j]+1)&&num==0) { result.add(String.valueOf(nums[j])); startLine=k; endLine=k; num=0; } //后面的数>当前数+1,扫描了(endLine-start+1)个数,就将nums[startLine])+"->"+String.valueOf(nums[endLine])放入result中 else if(nums[k]>(nums[j]+1)&&num>0) { result.add(String.valueOf(nums[startLine])+"->"+String.valueOf(nums[endLine])); startLine=k; endLine=k; num=0; } //后面的数=当前数+1,移动endLine,num++即可 else if(nums[k]-nums[j]==1) { endLine=k; num++; } } //扫描最后一个数 else { if(num==0) result.add(String.valueOf(nums[k-1])); else { result.add(String.valueOf(nums[startLine])+"->"+String.valueOf(nums[endLine])); num=0; } } } return result; } }