N^2 solution using pointer technique


  • 0
    A

    int threeSumClosest(int* arr, int numsSize, int target) {
    int n= numsSize;
    for(int i1=0; i1<(n-1); i1++)
    {
    for(int j1=0; j1<(n-i1-1); j1++)
    {
    if(arr[j1]>arr[j1+1])
    {
    int temp=arr[j1];
    arr[j1]=arr[j1+1];
    arr[j1+1]=temp;
    }
    }
    }
    int diff=99999,m;
    int i,j,k,f=1;

     for(i=n-1;i>=2;i--)
     { k=i-1;
        j=0;
      while(j<k)
      { int sum= arr[i]+arr[j]+arr[k];
       if(sum==target)
       { m=target; f=0; break;}
       else if(sum>target)
       { if(sum-target<diff)
       { diff=sum-target; m=sum;} k--;
        }
       else if(sum<target)
       {if(target-sum<diff)
       { diff= (sum-target)*-1; m=sum;}
           j++;
       }
          
      }
      if(f==0)
          break;
     }
    return m;
    

    }


Log in to reply
 

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