Doing something you intrinsically are enthusiastic with.

2016年8月23日 星期二

Leetcode--Summary Range

上午11:56 Posted by Unknown No comments
Given 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"].
Solution: 
We can use two pointers to record the start and the end of each range.
  1. class Solution {
  2. public:
  3.     vector<string> summaryRanges(vector<int>& nums) {
  4.        
  5.        
  6.         vector<string> result;
  7.        
  8.         int n = nums.size();
  9.         if(== 0)return result;
  10.         if(== 1){
  11.              result.push_back(to_string(nums[0]));
  12.              return result;
  13.         }
  14.        
  15.         int start=nums[0];
  16.         int end=nums[0];
  17.  
  18.        
  19.        for(int i = 0; i < n;){
  20.              
  21.             while( i+1 < n && nums[i+1] == end + 1){
  22.                 end++;
  23.                 i++;
  24.             }
  25.             if(start != end){
  26.                 result.push_back(to_string(start) + "->" + to_string(end));
  27.             }
  28.             else{
  29.                 result.push_back(to_string(start));
  30.             }
  31.            
  32.             i++;
  33.             start = end = nums[i];
  34.            
  35.         }
  36.        
  37.         return result;
  38.  
  39.     }
  40. };

0 意見:

張貼留言