Summary Ranges
Total Accepted: 511 Total Submissions: 2271Given 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"].
[思路]
两个指针 start, end. 假设nums[end+1] = nums[end]+1, 就移动end指针, 否则, 插入字符串nums[start]->nums[end].
[CODE]
public class Solution { // [0,1,2,4,5,7], return ["0->2","4->5","7"]. public List<String> summaryRanges(int[] nums) { List<String> res = new ArrayList<>(); if(nums==null || nums.length<1) return res; int s=0, e=0; while(e<nums.length) { if(e+1<nums.length && nums[e+1]==nums[e]+1) { e++; } else { if(s==e) { res.add(Integer.toString(nums[s])); } else { String str = nums[s] + "->" + nums[e]; res.add(str); } ++e; s = e; } } return res; } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步