Monday, June 27, 2016

228. Summary Ranges

Just be careful to handle the case where the range only contains one element.

1:  class Solution {  
2:  public:  
3:    vector<string> summaryRanges(vector<int>& nums) {  
4:      int i = 0, j = 0;  
5:      vector<string> res;  
6:      while (i < nums.size()) {  
7:        int count = 1;  
8:        string s = to_string(nums[i]);  
9:        for (++i; i < nums.size(); i++) {  
10:          if (nums[i] - nums[i-1] != 1) break;  
11:          count++;  
12:        }  
13:        if (count > 1) s += "->" + to_string(nums[i-1]);  
14:        res.push_back(s);  
15:      }  
16:      return res;  
17:    }  
18:  };  

Following is what I did when I revisited this problem. I made a mistake in line 8 in red.

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

No comments:

Post a Comment