1. Title
Summary Ranges
2. Http address
https://leetcode.com/problems/summary-ranges/
3. The question
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"].
4 My code(AC)
1 // Accepted 2 public List<String> summaryRanges(int[] nums) { 3 4 List<String> result = new ArrayList<String>(); 5 if ( nums == null || nums.length <=0) 6 return result; 7 8 int len = nums.length; 9 10 if( len == 1) 11 { 12 result.add(nums[0]+""); 13 return result; 14 } 15 int beginIndex = 0; 16 for(int i = 1; i < len ; i++) 17 { 18 if( nums[i] != nums[i-1] + 1) 19 { 20 if(beginIndex != i-1) 21 { 22 result.add("" + nums[beginIndex] + "->" + nums[i-1]); 23 }else{ 24 result.add("" + nums[i-1]); 25 } 26 beginIndex = i; 27 } 28 } 29 30 if(beginIndex != len-1) 31 { 32 result.add("" + nums[beginIndex] + "->" + nums[len-1]); 33 }else{ 34 result.add("" + nums[len-1]); 35 } 36 return result; 37 }