Monday, May 11, 2015

163 Missing Ranges

来源:Leetcode

原帖:https://leetcode.com/problems/missing-ranges/

题目:
Given a sorted integer array where the range of elements are [lower, upper] inclusive, return its missing ranges.
For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99, return ["2", "4->49", "51->74", "76->99"].

代码:
 class Solution {  
 public:  
   vector<string> findMissingRanges(int A[], int n, int lower, int upper) {  
     vector<string> res;  
     // A is empty  
     if (n == 0) {  
       if (lower == upper) res.push_back(to_string(lower));  
       else res.push_back(to_string(lower) + "->" + to_string(upper));  
       return res;  
     }  
     if (A[0] == lower + 1) {  
       res.push_back(to_string(lower));  
     } else if (A[0] > lower + 1) {  
       res.push_back(to_string(lower) + "->" + to_string(A[0]-1));  
     }  
     for (int i = 1; i < n; ++i) {  
       if (A[i] - A[i-1] == 1) continue;  
       else if (A[i] - A[i-1] == 2) res.push_back(to_string(A[i]-1));  
       else res.push_back(to_string(A[i-1]+1) + "->" + to_string(A[i]-1));  
     }  
     if (A[n-1] == upper-1) res.push_back(to_string(upper));  
     else if (A[n-1] < upper-1) res.push_back(to_string(A[n-1]+1) + "->" + to_string(upper));  
     return res;  
   }  
 };  

No comments:

Post a Comment