228. Summary Ranges

问题:

给出给定数组的描述:

Example 1:
Input:  [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.

Example 2:
Input:  [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range.

  

解决方法:

1.记录每组开头数字为pre,每移动一位j++(用j来记录相对pre的距离)

2.逐次判断当前数字是否为pre+j

  如果是,则轮询下一个

  否则,则输出字符串pre~i-1

tip:

注意最后一组输出,需要在循环外再做一次

 

参考代码:

 1 class Solution {
 2 public:
 3     vector<string> summaryRanges(vector<int>& nums) {
 4         vector<string> res;
 5         if(nums.size()<=0) return res;
 6         int i=0, j=1, pre=0;
 7         string tmp;
 8         for(i=1; i<nums.size(); i++){
 9             if(nums[i]==nums[pre]+j){
10                 j++;
11             }else{
12                 if(j>1) tmp=to_string(nums[pre])+"->"+to_string(nums[i-1]);
13                 else tmp=to_string(nums[pre]);
14                 res.push_back(tmp);
15                 pre=i;
16                 j=1;
17             }
18         }
19         if(j>1) tmp=to_string(nums[pre])+"->"+to_string(nums[i-1]);
20         else tmp=to_string(nums[pre]);
21         res.push_back(tmp);
22         return res;
23     }
24 };

 

posted @ 2020-03-15 14:41  habibah_chang  阅读(108)  评论(0编辑  收藏  举报