Need help for a unique problem


  • 0
    S

    Here is my solution, when submitting it there is a failed case
    [40,-53,36,89,-38,-51,80,11,-10,76,-30,46,-39,-15,4,72,83,-25,33,-69,-73,-100,-23,-37,-13,-62,-26,-54,36,-84,-65,-51,11,98,-21,49,51,78,-58,-40,95,-81,41,-17,-70,83,-88,-14,-75,-10,-44,-21,6,68,-81,-1,41,-61,-82,-24,45,19,6,-98,11,9,-66,50,-97,-2,58,17,51,-13,88,-16,-77,31,35,98,-2,0,-70,6,-34,-8,78,22,-1,-93,-39,-88,-77,-65,80,91,35,-15,7,-37,-96,65,3,33,-22,60,1,76,-32,22]

    The problem is when I run this case in the Run Code mode, the answer is right but it failed when I tried to submit it. It's quite weird, any suggestions? Thanks.

    class Solution {
    public:
    int FindUpper(vector<int>&nums,int l,int target){
    int r = nums.size();
    while(l<r){
    int mid = l+((r-l)>>1);
    if(nums[mid]<target)
    l = mid+1;
    else r = mid;
    }
    return r;
    }
    int threeSumClosest(vector<int>& nums, int target) {
    sort(nums.begin(),nums.end());
    int m =nums.size();
    // int closest = nums[m-1]+nums[m-2]+nums[m-3];
    int diff = INT_MAX,closest=0;
    for(int i=0;i<nums.size()-2;++i){
    for(int j=i+1;j<nums.size()-1;++j){
    int tmp = target-nums[i]-nums[j];
    int l = j+1,lower,upper;
    int idx = FindUpper(nums,l,tmp);
    if(idx-1>j){
    lower = nums[idx-1];
    upper = nums[idx];
    }
    else{
    lower = nums[idx];
    upper = nums[idx];
    }
    int smaller = (abs(tmp-lower)<abs(tmp-upper))?lower:upper;
    if (abs(tmp-smaller)<diff){
    diff = abs(tmp-smaller);
    closest = smaller+nums[i]+nums[j];
    cout<<"diff "<<diff<<"; closest "<<closest<<endl;
    }
    }
    }
    return closest;
    }
    };


Log in to reply
 

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