您的位置:首页 > 其它

C实现 LeetCode->3SumClosest

2015-06-15 10:10 330 查看
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).


 一个整形数组,找到3个数的总和 最接近 一个目标target值;返回3个整数的总和。



//
// 3SumClosest.c
// Algorithms
//
// Created by TTc on 15/6/15.
// Copyright (c) 2015年 TTc. All rights reserved.
//
/**
* 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.

给定的n个整数数组,找到三个整数的年代,总数接近给定目标数字。返回三个整数之和。你可能认为每个输入会完全一个解决方案。

EG: S = {-1 2 1 -4}, and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

*/
#include "3SumClosest.h"
#include <stdlib.h>
#include <string.h>

static int
cmp(const int*a,const int*b){
return (*a) - (*b);
}

int
threeSumClosest(int* nums, int numsSize, int target) {
int ans = 0;
int sum;
qsort(nums, numsSize, sizeof(int), (int(*)(const void *,const void *))cmp);

if(numsSize <= 3){
for (int i =0 ; i< numsSize; i++) {
ans += nums[i];
}
return ans;
}
//数组已经是排序好的
/*
1: 现在我们每一个数字V[i]:我们寻找一对数字 v[j] 和 v[k];
2: 这样绝对值(target -(v[i] + v[j] + v[k])) 最小化
3: 如果3个元素的 总和 > target ,我们需要减小sum的值,需要做k = k -1操作
4: 如果3个元素的 总和 < target ,我们需要增加sum的值,需要做j = j +1操作
*/
ans = nums[0] + nums[1] + nums[2];
for (int i = 0; i < numsSize - 2; i++) {
int j = i + 1;
int k = numsSize - 1;

while (j < k) {
sum = nums[i] + nums[j] + nums[k];
if(abs(target -ans) > abs(target - sum)){
ans = sum;
if(ans == target) return ans;
}
(sum > target) ? k-- : j++;
}
}
return ans;
}

void
test_threeSUmCLosest(){
int nums[10] = {-1,2,1,-4};
int result = threeSumClosest(nums, 4, 1);
printf("result===%d",result);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: