【LeetCode】C# 16、3Sum Closest
来源:互联网 发布:卷积神经网络 算法 编辑:程序博客网 时间:2024/06/05 22:34
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).
给定一个数组,返回和最接近给定 target 的三个数。
这道题和上道一样,建立三个指针,遍历一遍nums作为第一个指针,后面通过与target对比决定start往右移还是end左移。
public class Solution { public int ThreeSumClosest(int[] nums, int target) { int res = nums[0] + nums[1] + nums[nums.Count() - 1]; Array.Sort(nums); for (int i = 0; i < nums.Count() - 2; i++) { int start = i + 1, end = nums.Count() - 1; while (start < end) { int temp = nums[i] + nums[start] + nums[end]; if (temp > target) { end--; } else { start++; } if (Math.Abs(temp - target) < Math.Abs(res - target)) { res = temp; } } } return res; }}
阅读全文
0 0
- 【LeetCode】C# 16、3Sum Closest
- LeetCode 16: 3Sum Closest
- LeetCode 16: 3Sum Closest
- leetcode 16 3Sum Closest
- [leetcode 16] 3Sum Closest
- Leetcode【16】:3Sum Closest
- [leetcode 16] 3Sum Closest
- [Leetcode] 16 - 3Sum Closest
- leetcode.16----------3Sum Closest
- leetcode 16 3Sum Closest
- leetcode-16 3Sum closest
- LeetCode---(16) 3 Sum Closest
- LeetCode 16 - 3Sum Closest
- leetcode 16 -- 3Sum Closest
- 3Sum Closest - LeetCode 16
- leetcode 16: 3Sum Closest
- Leetcode#16 3Sum Closest
- LeetCode(16) 3Sum Closest
- python 列表常用函数操作
- python学习笔记---对象赋值其实就是引用
- git的详细教程地址
- 新星Hcash超级现金矿池傻瓜版HSR挖矿指南-钱包流程,及1060 1070 1080 显卡速度对比
- JAVA提高篇(33)--Java线程常用的操作方法
- 【LeetCode】C# 16、3Sum Closest
- Unity调用系统窗口选择文件或文件路径
- 网页拖拽项目实践
- ubuntu安装最新版node和npm
- 正则表达式基本用法(二)——断言、分组
- 算法6 Same Tree
- Log4j2简单配置
- 看图说话排序算法之冒泡排序
- 关于Matlab编程的一些小总结