16 - 3Sum Closest

 JAVA

  • class Solution {
        public int threeSumClosest(int[] nums, int target) {
            Arrays.sort(nums);
            int ans = 1 << 30;
            int n = nums.length;
            for (int i = 0; i < n; ++i) {
                int j = i + 1, k = n - 1;
                while (j < k) {
                    int t = nums[i] + nums[j] + nums[k];
                    if (t == target) {
                        return t;
                    }
                    if (Math.abs(t - target) < Math.abs(ans - target)) {
                        ans = t;
                    }
                    if (t > target) {
                        --k;
                    } else {
                        ++j;
                    }
                }
            }
            return ans;
        }
    }
C++
  • class Solution {
    public:
        int threeSumClosest(vector<int>& nums, int target) {
            sort(nums.begin(), nums.end());
            int ans = 1 << 30;
            int n = nums.size();
            for (int i = 0; i < n; ++i) {
                int j = i + 1, k = n - 1;
                while (j < k) {
                    int t = nums[i] + nums[j] + nums[k];
                    if (t == target) return t;
                    if (abs(t - target) < abs(ans - target)) ans = t;
                    if (t > target)
                        --k;
                    else
                        ++j;
                }
            }
            return ans;
        }
    };

Comments