3Sum Closest Leetcode
来源:互联网 发布:淘宝账期延长十五天 编辑:程序博客网 时间:2024/06/11 03:59
Given an array S of n integers, find three integers inS 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).
Seen this question in a real interview before?
Yes
N
My solution:
import java.util.Arrays;class Solution { public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int result = nums[0] + nums[1] + nums[2]; for(int i = 0; i < nums.length; i++) { int x = 0; int y = nums.length - 1; int twoNumAddTarget = target - nums[i]; while(x < y - 1) { if (nums[x] + nums[y] < twoNumAddTarget) { x ++; } else { y --; } if (x == i) { x ++; } else if (y == i) { y --; } if (x >= y) { break; } if (Math.abs(nums[i] + nums[x] + nums[y] - target) < Math.abs(target - result)) { result = nums[i] + nums[x] + nums[y]; } } } return result; }}
阅读全文
0 0
- LeetCode: 3 Sum Closest
- leetcode - 3 sum closest
- leetcode 3Sum Closest
- LeetCode: 3Sum Closest
- [Leetcode]3Sum Closest
- Leetcode: 3SUM Closest
- LeetCode 3Sum Closest
- [Leetcode] 3Sum Closest
- LeetCode : 3Sum Closest
- LeetCode 3Sum Closest
- [LeetCode] 3Sum Closest
- 【leetcode】3Sum Closest
- [LeetCode]3Sum Closest
- LeetCode-3Sum Closest
- LeetCode:3Sum Closest
- LeetCode | 3Sum Closest
- 【leetcode】3Sum Closest
- Leetcode: 3Sum Closest
- 使用selenium3.X启动firefox浏览器
- b进制运算之一--和
- The more, The Better (树形dp+背包)
- 445. Add Two Numbers II(JAVA)
- 【java多线程编程核心技术】3.线程间通信 -笔记总结
- 3Sum Closest Leetcode
- 前端学习知识要点整理
- Mybatis在控制台显示sql语句配置文件
- jq滚动到顶部
- 引用 欢迎使用CSDN-markdown编辑器
- 个人总结40
- ubuntu服务器基本安全配置
- Centos7安装Torque
- 我的Kotlin For Android之路开篇(一)