Java [Leetcode 228]Summary Ranges

时间:2021-09-29 06:21:00

题目描述:

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

解题思路:

相邻的两个数字若差距为1,则继续向后读,直到不满足条件为止,则把起始到终点的结果表示出来。如此,直到读到数组的最后位置为止。

代码如下:

public class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> result = new ArrayList<String>();
int length = nums.length;
for(int i = 0; i < nums.length; i++){
int front = nums[i];
while(i + 1 < nums.length && nums[i + 1] - nums[i] == 1)
i++;
int end = nums[i];
if(front == end)
result.add(front + "");
else
result.add(front + "->" + end);
}
return result;
}
}