Leetcode 16. 3Sum Closest

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

1. Description

Leetcode 16. 3Sum Closest_第1张图片
3Sum Closest

2. Solution

  • Brute Force
class Solution {
public:
    int threeSumClosest(vector& 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& 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 16. 3Sum Closest)