LC.P228[汇总区间]

方法一:双指针

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> ans = new ArrayList<>();
int n = nums.length;
for (int i = 0, j; i < n; i = j + 1) {
j = i;
while (j + 1 < n && nums[j + 1] == nums[j] + 1) ++j;
ans.add(i == j ? String.valueOf(nums[i]) : String.format("%d->%d", nums[i], nums[j]));
}
return ans;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(1)$