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

 


题目标签:Array

  题目给了我们一个nums array, 让我们找出它的区间总结。

  这题可以用two pointers 来做, 设一个left 和 right 起初都等于0。遍历nums array,如果遇到了 当前数字 等于 前一个数字+1, 那么就把right = i,扩大这个sliding window 的范围;如果遇到的 当前数字 不等于 前一个数字+1,意味着此时需要把前面的区间left 到 right加入list,因为这里已经断点了。而且还需要更新left 和 right 都等于 目前的 i, 让sliding window 重新开始。

  还需要注意的是,遍历完nums 之后,还需要把最后的区间 加入 list。

 

 

Java Solution:

Runtime beats 51.99% 

完成日期:09/06/2017

关键词:Array, Two Pointers

关键点:利用left 和 right 来控制sliding window 的大小(区间)

 

 1 class Solution 
 2 {
 3     public List<String> summaryRanges(int[] nums) 
 4     {
 5         List<String> res = new ArrayList<>();
 6         
 7         if(nums == null || nums.length == 0)
 8             return res;
 9         
10         int left = 0, right = 0;
11         
12         for(int i=1; i<nums.length; i++)
13         {
14             // if current number is not equal to previous number + 1, add the range into list
15             if(nums[i] != nums[i-1] + 1)
16             {
17                 // if just one number
18                 if(left == right)
19                     res.add("" + nums[left]);
20                 else// if more than one number
21                     res.add("" + nums[left] + "->" + nums[right]);
22                 
23                 // if find the gap, update the left and right
24                 left = i;
25                 right = i;
26             }
27             else if(nums[i] == nums[i-1] + 1) // if find the correct number, increase right
28                 right = i;
29             
30         }
31         
32         // add the last range
33         if(left == right)
34             res.add("" + nums[left]);
35         else // if more than one number
36             res.add("" + nums[left] + "->" + nums[right]);
37         
38         return res;
39     }
40 }

参考资料:N/A

 

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

 

转载于:https://www.cnblogs.com/jimmycheng/p/7488181.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值