C++ case runtime error, but pass on my PC?


  • 0
    D

    class Solution {
    public:
    int removeDuplicates(vector<int>& nums) {
    if (nums.size()==0) return 0;
    if (nums.size()==1) return 1;

        int last = nums[0];
        int len = 1;
        int scan = 0;
        while(scan < nums.size() && len < nums.size()) {
            scan++;
            if (nums[scan] != last) {
                last = nums[scan];
                // swap(scan, len)
                int tmp = nums[scan];
                nums[scan] = nums[len];
                nums[len] = tmp;
                len++;                
            }
        }
        return len;
    }
    

    };

    [-3,-3,-2,-1,-1,0,0,0,0,0]

    ======================== My test on PC ===================

    #include <iostream>
    

    #include <vector>
    using namespace std;

    class Solution {
    public:
    int removeDuplicates(vector<int>& nums) {
    if (nums.size()==0) return 0;
    if (nums.size()==1) return 1;

        int last = nums[0];
        int len = 1;
        int scan = 0;
        while(scan < nums.size() && len < nums.size()) {
            scan++;
            if (nums[scan] != last) {
                last = nums[scan];
                // swap(scan, len)
                int tmp = nums[scan];
                nums[scan] = nums[len];
                nums[len] = tmp;
                
                len++;                
            }
        }
        return len;
    }
    

    };
    void printv(vector<int> v){
    for (std::vector<int>::iterator i = v.begin(); i != v.end(); ++i)
    {
    cout<< *i <<" ";
    }cout<<endl;
    }
    void test() {
    int arr[] = {-3,-3,-2,-1,-1,0,0,0,0,0};
    vector<int> input(arr, arr+sizeof(arr)/sizeof(arr[0]));
    vector<int> inputRef = input;
    Solution s;
    cout<<"len:"<<s.removeDuplicates(inputRef)<<endl;
    printv(inputRef);

    }

    int main(int argc, char const *argv[])
    {
    test();
    return 0;
    }


  • -1
    D
       when scan=nums.size()-1
           after scan++
            scan will eqauls nums.size()
               nums[scan] //access violent
    

Log in to reply
 

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