zoukankan      html  css  js  c++  java
  • [leetcode]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).

    c代码:

    #define INT_MAX      2147483647L   /* maximum (signed) long value */
    int Partition(int a[], int low, int high){
      int pivotkey = a[low];
      while(low < high){
        while( low < high && a[high] >= pivotkey) --high;
        a[low]= a[high];
        while(low < high && a[low] <= pivotkey) ++low;
        a[high] = a[low]; 
      }
      a[low] = pivotkey;
      return low;
    }
    void Qsort(int a[], int low, int high){
      int pivotloc;
      if(low < high){
        pivotloc = Partition(a, low, high);
        Qsort(a, low, pivotloc - 1);
        Qsort(a, pivotloc + 1, high);
      }
    }
    void QuikSort(int a[], int size){
      Qsort(a, 0 ,size-1);
    }
    int threeSumClosest(int *num, int n, int target) {
        int min = INT_MAX,record,i;
        QuikSort(num, n);
        for(i = 0; i < n - 2; i++){
            int l = i + 1;
            int r = n - 1;
            while(l < r){
                int sum = num[i] + num[l] + num[r];
                if(sum == target){
                    return sum;
                }else if(sum < target){
                    if(target - sum < min){
                        record = sum;
                        min = target - sum;
                    }
                    l++;
                }else{
                    if(sum - target < min){
                        record = sum;
                        min = sum - target;
                    }
                    r--;
                }
            }
            while(i+1<n-2 && num[i+1] == num[i])i++;
        }
    	return record;
    }
    

      

  • 相关阅读:
    Linux外部设备的使用
    Linux硬件信息查询
    Linux中swap分区设置
    状态检测型防火墙
    CentOS更换源,亲测可用
    Linux文件权限序列简述
    Linux终端打印文本色彩
    Linux 系统命令之netstat
    Linux配置DNS服务器
    水题一枚
  • 原文地址:https://www.cnblogs.com/zhutianpeng/p/4304577.html
Copyright © 2011-2022 走看看