228. Summary Ranges java solutions
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"].
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
1 public class Solution { 2 public List<String> summaryRanges(int[] nums) { 3 List<String> ans = new ArrayList<String>(); 4 if(nums == null || nums.length == 0) return ans; 5 for(int i = 0; i < nums.length; i++){ 6 int n = nums[i]; 7 while(i+1 < nums.length && nums[i+1]-nums[i] == 1)i++; 8 if(n != nums[i]){ 9 ans.add(n + "->" + nums[i]); 10 } 11 else ans.add(""+n); 12 } 13 return ans; 14 } 15 }
主要是要注意下边界。