Summary Ranges
题目链接:https://leetcode.com/problems...
loop两种写法:
public class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> result = new ArrayList();
if(nums.length == 0) return result;
/* loop invariant: nums[i] != nums[i-1] + 1
*/
for(int i = 0; i < nums.length; i++) {
int prev = nums[i];
while(i < nums.length - 1 && nums[i] + 1 == nums[i+1]) {
i++;
}
result.add(getRange(prev, nums[i]));
}
return result;
}
private String getRange(int i, int j) {
if(i == j) return "" + i;
return i + "->" + j;
}
}
public class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> result = new ArrayList();
if(nums.length == 0) return result;
int prev = nums[0];
for(int i = 0; i < nums.length; i++) {
if(i == nums.length - 1 || nums[i] + 1 != nums[i+1]) {
result.add(getRange(prev, nums[i]));
if(i != nums.length - 1) prev = nums[i+1];
}
}
return result;
}
private String getRange(int i, int j) {
if(i == j) return "" + i;
return i + "->" + j;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。