导航
导航
文章目录
  1. 题目
  2. 翻译

LeetCode-228.Summary Ranges

题目

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”].

翻译

给出一个无重复元素的已排序整型数组,返回其连续范围的集合。
例如,给出[0,1,2,4,5,7],返回[“0->2”,”4->5”,”7”]。

每次循环设定起始和终止指针,终止指针不断向后扫描,直到不连续,输出range,更新起始指针,直到遍历完数组:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> rangesList = new ArrayList<String>();
int index = 0;
while (index < nums.length) {
int end = index + 1;
while (end < nums.length && nums[end] - nums[end - 1] == 1) end++;
if (end - index == 1) rangesList.add(String.valueOf(nums[index++]));
else {
rangesList.add(nums[index] + "->" + nums[end - 1]);
index = end;
}
}
return rangesList;
}
}