[leedcode 228] 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 List<String> summaryRanges(int[] nums) { //注意从0开始遍历,使用一个temp标记当前遍历到的下标值,然后比较nums[i+1]-nums[i]==1, //比较是否range只有一个值,然后保存结果,需要注意的是:内层while循环需要判断i的范围!! ArrayList<String> res=new ArrayList<String>(); if(nums==null||nums.length<=0) return res; StringBuilder seq; for(int i=0;i<nums.length;i++){ int temp=nums[i]; while(i<nums.length-1&&nums[i+1]-nums[i]==1){ i++; } if(nums[i]!=temp){ res.add(temp+"->"+nums[i]); }else{ res.add(temp+""); } } return res; } }