博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
3Sum Closest
阅读量:6909 次
发布时间:2019-06-27

本文共 1530 字,大约阅读时间需要 5 分钟。

每日算法——leetcode系列


3Sum Closest

Difficulty: Medium

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
& nums, int target) { }};

翻译

三数和

难度系数:中等

给定一个有n个整数的数组S, 找出数组S中三个数的和最接近一个指定的数。 返回这三个数的和。 你可以假定每个输入都有一个结果。

思路

思路跟很像, 不同的就是不用去重复, 要记录三和最接近target的和值。

代码

class Solution {public:    int threeSumClosest(vector
& nums, int target) { int result = 0; int minDiff = INT32_MAX; // 排序 sort(nums.begin(), nums.end()); int n = static_cast
(nums.size()); for (int i = 0; i < n - 2; ++i) { int j = i + 1; int k = n - 1; while (j < k) { int sum = nums[i] + nums[j] + nums[k]; int diff = abs(sum - target); // 记录三和最接近target的和值 if (minDiff > diff){ result = sum; minDiff = diff; } else if (sum < target){ j++; } else if (sum > target){ k--; } else{ return result; } } } return result; }};

转载地址:http://mrfcl.baihongyu.com/

你可能感兴趣的文章
基站定位接口说明文档
查看>>
java实现邮件定时发送
查看>>
差分约束 【bzoj2330】[SCOI2011]糖果
查看>>
ArrayList和LinkedList区别
查看>>
Error_GL_KeyflexfieldDefinitionFactory.getStructureNumber无法找到应用产品
查看>>
js作用域及闭包
查看>>
CSS overflow 属性
查看>>
通过改变uiview的layer的frame来实现进度条
查看>>
ADB am 命令详细参数
查看>>
NOIp 数学基础
查看>>
nginx支持ipv6
查看>>
点名器
查看>>
Codeforces Problems-122A. Lucky Division
查看>>
移动端适配代码
查看>>
Js设置所有连接是触发/swt/的代码
查看>>
JS高级程序设计2nd部分知识要点1
查看>>
mac10.8 更新系统出错
查看>>
'-[UITableViewController loadView] loaded the "XXX" nib but didn't get a UITableView.'
查看>>
ARM裸板开发:07_IIC 通过IIC总线接口读写时钟芯片时间参数实现的总结
查看>>
C# 笔记 如何调用一个有返回值的方法
查看>>