×
广告

Leetcode 16. 3Sum Closest

96
SnailTyan
2018.07.06 14:28* 字数 36

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

3Sum Closest

2. Solution

  • Brute Force
class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        int length = nums.size();
        int sum = nums[0] + nums[1] + nums[2];
        int min = abs(sum - target);
        for(int i = 0; i < length; i++) {
            for(int j = i + 1; j < length; j++) {
                for(int k = j + 1; k < length; k++) {
                    int temp = nums[i] + nums[j] + nums[k];
                    int diff = abs(temp - target);
                    if(min > diff) {
                        min = diff;
                        sum = temp;
                    }
                }
            }
        }
        return sum;
    }
};
  • sort and O(n^2)
class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        // sort vector
        sort(nums.begin(), nums.end());
        int length = nums.size();
        int sum = nums[0] + nums[1] + nums[2];
        int min = abs(sum - target);
        for(int i = 0; i < length - 2; i++) {
            int left = i + 1;
            int right = length - 1;
            while(left < right) {
                int temp = nums[i] + nums[left] + nums[right];
                int diff = abs(temp - target);
                if(min > diff) {
                    min = diff;
                    sum = temp;
                }
                if(temp < target) {
                    left++;
                } 
                else if(temp > target) {
                    right--;
                } 
                else {
                    return temp;
                }
            }
        }
        return sum;
    }
};

Reference

  1. https://leetcode.com/problems/3sum-closest/description/
Leetcode
Web note ad 1