zoukankan      html  css  js  c++  java
  • 6.最接近的三数之和

    题目:给一个包含 n 个整数的数组 S, 找到和与给定整数 target 最接近的三元组,返回这三个数的和。

     注意事项

    只需要返回三元组之和,无需返回三元组本身

    class Solution {
    public:
        /**
         * @param numbers: Give an array numbers of n integer
         * @param target: An integer
         * @return: return the sum of the three integers, the sum closest target.
         */
        int threeSumClosest(vector<int> nums, int target) {
            // write your code here
                 int min = 0x7f7f;
            sort(nums.begin(), nums.end());
            int size = nums.size();
            for (int i = 0; i < size; i++) {
                int j = i + 1, k = size - 1;
                while (j < k) {
                    int sum = nums[i] + nums[j] + nums[k];
                    if (abs(min - target) > abs(sum - target)) {
                        min = sum;
                    }
                    if (sum <= target) {
                        j++;
                    } else {
                        k--;
                    }
                }
            }
            return min;
        }
    };

  • 相关阅读:
    Vue项目搭建及原理三
    Vue项目搭建及原理一
    JS Cookie丢失问题
    1027 Colors in Mars
    1028 List Sorting
    1029 Median
    1030 Travel Plan
    1031 Hello World for U
    1032 Sharing
    1033 To Fill or Not to Fill
  • 原文地址:https://www.cnblogs.com/ALIMAI2002/p/7211085.html
Copyright © 2011-2022 走看看