Why did my code MLE?


  • 0
    L
    class Solution {
    public:
      vector<string> summaryRanges(vector<int>& nums) {
        vector<string> ans;
        if(nums.size()==0) return ans;
        int len=nums.size();
        int i=nums[0],j=0,a,b;
    
        while(i<=nums[len-1]){
            a=i;
            while(i==nums[j]){
                i++;
                j++;
            }
            b=nums[j-1];
            if(a!=b){
                ans.push_back(to_string(a)+"->"+to_string(b));
            }else{
                ans.push_back(to_string(a));
            }
            i=nums[j];
        }
        return ans;
    }
    };

  • 0
    L

    probably you use while { while { } } . it's O(n^2)!!!


  • 0
    L

    It's not O(n^2) : )


  • 0
    L

    I forgot to break the while loop

    class Solution {
    public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector<string> ans;
        if(nums.size()==0) return ans;
        int len=nums.size();
        int i=nums[0],j=0,a=nums[0],b=nums[0];
        while(i<=nums[len-1]){
            a=i;
            while(i==nums[j]&&j<len){
                i++;
                ++j;
            }
            b=nums[j-1];
            if(a!=b){
                ans.push_back(to_string(a)+"->"+to_string(b));
            }else{
                ans.push_back(to_string(a));
            }
            i=nums[j];
             if(j==len) break;    // here's the bug
        }
        return ans;
    }
    };

  • 0
    L

    oh, it's my fault


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.