Share my solution (n^2)


  • 0
    L
    class Solution {
    public:
        int threeSumClosest(vector<int>& nums, int target) {
            int ans, n = nums.size();
            bool fst = true;
            sort(nums.begin(), nums.end());
            for(int a = 0; a < n; a++)
            {
                int b = a + 1, c = n - 1;
                while(b < c)
                {
                    while(b < c - 1 && nums[a] + nums[b] + nums[c-1] >= target) c--;
                    if(fst || abs(ans - target) > abs(nums[a] + nums[b] + nums[c] - target))
                    {
                        fst = false;
                        ans = nums[a] + nums[b] + nums[c];
                    }
                    b++;
                }
            }
            return ans;
        }
    };

Log in to reply
 

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