A recursive solution in C++


  • 0
    H
    class Solution {
    public:
        vector<int> findDisappearedNumbers(vector<int>& nums) {
            vector<int> result;
            for(int i = 1; i <= nums.size();++i){
                if(nums[i - 1] != 0){
                    set_zero(nums, nums[i-1]);
                }
            }
            for(int i = 1; i <= nums.size();++i){
                if(nums[i-1]!=0){
                    result.push_back(i);
                }
            }
            return result;
        }
    
    private:
        void set_zero(vector<int>& nums, int idx){
            if(nums[idx-1] == 0){
                return;
            }
            else{
                int new_idx = nums[idx-1];
                nums[idx-1]=0;
                set_zero(nums, new_idx);
            }
        }
        
    };
    

Log in to reply
 

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