Summary Ranges
给一个数组, 让返回其中的range. 用i和j两个指针, j在前边扫. i记录后边的位置. 当j = i+1的时候, 就是最后的一个元素.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class Solution { public List<String> summaryRanges(int[] nums) { List<String> res = new ArrayList<String>() ; int i = 0; int j = i+1; while(j<=nums.length){ while(j < nums.length && nums[j] - nums[j-1] == 1) j++; if(j == i+1) res.add(""+nums[i]); else res.add(nums[i] + "->" + nums[j-1]); j++; i = j-1; } return res; } } |