228. Summary Ranges

网友投稿 601 2022-09-04

228. Summary Ranges

228. Summary Ranges

Given a sorted integer array without duplicates, return the summary of its ranges.

Example 1:

Input: [0,1,2,4,5,7]Output: ["0->2","4->5","7"]

Example 2:

Input: [0,2,3,4,6,8,9]Output: ["0","2->4","6","8->9"]

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

class Solution { public List summaryRanges(int[] nums) { List result = new ArrayList<>(); if(nums.length == 0) return result; int start = 0; for(int i = 1; i < nums.length; i++){ if(nums[i] == nums[i-1]+1){ continue; }else { if(nums[start] == nums[i-1]){ result.add(Integer.toString(nums[start])); }else { result.add(Integer.toString(nums[start]) + "->" + Integer.toString(nums[i-1])); } start = i; } } if(nums[start] == nums[nums.length - 1]){ result.add(Integer.toString(nums[start])); }else { result.add(Integer.toString(nums[start]) + "->" + Integer.toString(nums[nums.length-1])); } return result; }}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Composer依赖管理 – PHP的利器(composer环境变量)
下一篇:你必须收藏的 GitHub 技巧(必须要收藏)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~