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"].
Solution:
We keep two pointers.
One pointer points to the start of the range.
We move the other pointer forward and checks if it is the end of the range.
If we find the end of the range, we simply add this range, and update the start pointer.
The time complexity is O(n) and the space complexity is O(1).
Code:
public class Solution { public List<String> summaryRanges(int[] nums) { List<String> result = new ArrayList<>(); if (nums == null || nums.length == 0) { return result; } int i = 0; for (int j = 0; j < nums.length; j++) { if (j + 1 < nums.length && nums[j + 1] - nums[j] == 1) { continue; } if (j == i) { result.add(nums[i] + ""); } else { result.add(nums[i] + "->" + nums[j]); } i = j + 1; } return result; } }