标签:
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"].
思路:采用双指针 start和end
时间复杂度:O(n)
代码:
public List<String> summaryRanges(int[] nums) { List<String> list=new ArrayList<String>(); int start=0,end=0; while(end++<nums.length) { if(end==nums.length) { if(start==end-1) list.add(""+nums[start]); else { String string=nums[start]+"->"+nums[end-1]; list.add(string); } break; } if(nums[end-1]+1==nums[end]) continue; else{ String string=((start!=end-1)?(nums[start]+"->"+nums[end-1]):""+nums[start]); list.add(string); start=end; } } return list; }
继续优化:
将判断是否最后一个的语句进行整合
public List<String> summaryRanges(int[] nums) { List<String> list=new ArrayList<String>(); int start=0,end=0; while(end++<nums.length) { if(end!=nums.length && nums[end-1]+1==nums[end]) continue; else{ String string=((start!=end-1)?(nums[start]+"->"+nums[end-1]):""+nums[start]); list.add(string); start=end; } } return list; }
扩展:假如存在重复的数呢?
public List<String> summaryRanges(int[] nums) { List<String> list=new ArrayList<String>(); int start=0,end=0; while(end++<nums.length) { if(end!=nums.length && (nums[end-1]+1==nums[end] || nums[end-1]==nums[end])) continue; else{ String string=((start!=end-1)?(nums[start]+"->"+nums[end-1]):""+nums[start]); list.add(string); start=end; } } return list; }
标签:
原文地址:http://www.cnblogs.com/maydow/p/4641134.html