Why storing the iterator will get the wrong answer?


  • 0
    F

    Here is my code, but cannot pass the test case, seems that the begin() iterator is not correctly assigned.

    class Solution {
    private:
        vector<int>::iterator begin, end;
    public:
        Solution(vector<int> nums) {
            begin = nums.begin();
            end = nums.end();
        }
        
        int pick(int target) {
            int result = -1;
            int count = 1;
            vector<int>::iterator ptr = this->begin;
            cout<<*begin;
            int index = -1;
            while (ptr != end) {
                ++index;
                //cout<<*ptr;
                if (*ptr == target) {
                    
                    int tmp = rand() % count;
                    if (tmp == 0) result = index;
                    ++count;
                }
                ++ptr;
            }
            return result;
        }
    };
    

Log in to reply
 

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