Tuesday, July 19, 2016

163. Missing Ranges

Keep track of previous node and the current node for the missing range. When output the missing range, we only need to output [prev+1, cur-1].

1:  class Solution {  
2:  public:  
3:    vector<string> findMissingRanges(vector<int>& nums, int lower, int upper) {  
4:      long long pre = lower - 1, cur = 0;  
5:      vector<string> res;  
6:      for (int i = 0; i <= nums.size(); i++) {  
7:        cur = (i == nums.size()) ? upper+1 : nums[i];  
8:        if (cur - pre > 1) res.push_back(getRange(nums, pre+1, cur-1));  
9:        pre = cur;  
10:      }  
11:      return res;  
12:    }  
13:    string getRange(vector<int> &nums, int pre, int cur) {  
14:      if (pre == cur) return to_string(pre);  
15:      else return to_string(pre) + "->" + to_string(cur);  
16:    }  
17:  };  

The above code will fail the case of nums = [2147483647], lower = 0 and upper = 2147483647 because of overflow. So the two variables of "pre" and "cur" should be type of "long long"

No comments:

Post a Comment