zoukankan      html  css  js  c++  java
  • [LeetCode] 16

    Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

        For example, given array S = {-1 2 1 -4}, and target = 1.
    
        The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

    class Solution {
    public:
      int threeSumClosest(vector<int>& nums, int target) {
        int size = nums.size();
        if (size < 3) {
          return 0;
        }
        int sum = 0;
        unsigned int diff = 0xffffffff;

        std::sort(nums.begin(), nums.end());
        for (int i = 0; i < size - 2; ++i) {
          if (i > 0 && nums[i] == nums[i-1]) {
            continue;
          }
          int j = i + 1;
          int k = size - 1;
          for (; j < k; ) {
            int tmp = nums[i] + nums[j] + nums[k];
            int tmp0 = (tmp - target);
            if (tmp0 == 0) { return tmp; }
            if (abs(tmp0) < diff) {
              diff = abs(tmp0);
              sum = tmp;
            }
            if (tmp0 > 0) {
              --k;
            } else {
              ++j;
            }
          }
        }
        return sum;
      }
    };

  • 相关阅读:
    Linux基础知识[1]【ACL权限】
    docker 入门学习篇【基本命令与操作】
    centos7.1下 Docker环境搭建
    RHEL6.5下更新python至2.7版本
    Github初学者探索
    vmware下linux虚拟机传文件解决方案之 xftp
    mysql 常用操作命令
    常用DNS记录
    常见网络协议端口号整理
    DNS原理及其解析过程 精彩剖析
  • 原文地址:https://www.cnblogs.com/shoemaker/p/4769114.html
Copyright © 2011-2022 走看看