C++ solution the loops, but how to use two pointers to solve ?


  • 0
    H

    The three loop problem is quite simple, how to use two pointers to solve this problem ?

    int threeSumSmaller(vector<int>& nums, int target) {

        int n = nums.size();
        
        sort(nums.begin(),nums.end());
    
        int count = 0;
        
        for(int i=0; i<n-2; i++){
            for(int j = i+1; j<n-1; j++){
                for(int p = j+1; p<n; p++){
                    
                    int sum = nums[i] + nums[j] + nums[p];
                    if(sum < target){
                        count++;
                    }else{
                        break;
                    }
                }
            }
        }
        
        return count;
        
    }

Log in to reply
 

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