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"].
Idea: Using the double-pointer start and end
Time complexity: O (N)
Code:
PublicList<string> Summaryranges (int[] nums) {List<String> list=NewArraylist<string>(); intStart=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; } } returnlist; }
Continue optimization:
Will judge whether the last statement is consolidated
PublicList<string> Summaryranges (int[] nums) {List<String> list=NewArraylist<string>(); intStart=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; } } returnlist; }
Extension: What if there are duplicate numbers?
PublicList<string> Summaryranges (int[] nums) {List<String> list=NewArraylist<string>(); intStart=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; } } returnlist; }
[Leetcode] Summary Ranges