Please Check. Code runs perfect but why Wrong answer?


  • 0
    R
    class Solution {
    public:
        int threeSumClosest(vector<int>& nums, int target) {
            int j=0,k=0,diff=0,flag=0,min=INT_MAX,minf=0;
            int size = nums.size();
            if(size<3)
            {
                return {};
            }
            sort(nums.begin(),nums.end());
            for(int i=0;i<size-2;i++)
            {
                j=i+1;
                k=size-1;
                while(j<k)
                {
                    if(nums[i]+nums[j]+nums[k]>target)
                    {
                        diff = nums[i]+nums[j]+nums[k] - target;
                        flag=1;
                        k--;
                    }
                    else if(nums[i]+nums[j]+nums[k]<target)
                    {
                        diff = target - (nums[i]+nums[j]+nums[k]);
                        flag=0;
                        i++;
                    }
                    else
                    {
                        diff=0;
                        return target;
                    }
                    
                    if(diff<min)
                    {
                        min = diff;
                        minf = flag;
                    }
                }
            }
            if(minf==1)
            return min+target;
            else
            return target-min;
        }
    };

Log in to reply
 

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