Leetcode 16. 3Sum Closest

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.csdn.net/Quincuntial/article/details/80940476

文章作者: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/
阅读更多

扫码向博主提问

SnailTyan

博客专家

非学,无以致疑;非问,无以广识
  • 擅长领域:
  • 深度学习
  • PyTorch
  • OCR
  • Docker
  • Caffe
去开通我的Chat快问
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页