zoukankan      html  css  js  c++  java
  • leetcode: 3Sum Closest

    http://oj.leetcode.com/problems/3sum-closest/

    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).
     

    思路

    先排序,然后对任意a[i]取j = i + 1,k = S.size() - 1,比较abs(a[i] + a[j] + a[k] - target),当差小于等于0时,j往后走,反之k往前走。

     1 class Solution {
     2 public:
     3     int threeSumClosest(vector<int> &num, int target) {
     4         int closet_sum = 0, diff = INT_MAX, size = num.size();
     5         
     6         sort(num.begin(), num.end());
     7         
     8         for (int i = 0; i < size; ++i) {
     9             int j = i + 1, k = size - 1;
    10             
    11             while (j < k) {
    12                 int sum = num[i] + num[j] + num[k];
    13                 int d = abs(sum - target);
    14                 
    15                 if (d < diff) {
    16                     diff = d;
    17                     closet_sum = sum;
    18                 }
    19                 
    20                 if (d > 0) {
    21                     int tmp;
    22                     
    23                     if ((sum - target) < 0) {
    24                         tmp = j + 1;
    25                         
    26                         while ((tmp < k) && (num[j] == num[tmp])) {
    27                             ++tmp;
    28                         }
    29                         
    30                         j = tmp;
    31                     }
    32                     else {
    33                         tmp = k - 1;
    34                         
    35                         while ((tmp > j) && (num[tmp] == num[k])) {
    36                             --tmp;
    37                         }
    38                         
    39                         k = tmp;
    40                     }
    41                 }
    42                 else {
    43                     return closet_sum;
    44                 }
    45             }
    46         }
    47         
    48         return closet_sum;
    49     }
    50 };
  • 相关阅读:
    JQ 放大镜
    Jquery.tmpl
    Jquery Live方法
    Bootstrap之底层媒体查询
    Bootstrap 字体与图标
    工具提示
    模态框
    BootStrap格栅系统
    Tab选项卡
    弹出框
  • 原文地址:https://www.cnblogs.com/panda_lin/p/3sum_closest.html
Copyright © 2011-2022 走看看