3Sum Closest

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
 public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int sum = nums[0] + nums[1] + nums[2];
int diff = Math.abs(sum - target);
for (int i = 0; i < nums.length - 2; i++) {
if (i != 0 && nums[i] == nums[i - 1])
continue;
int j = i + 1;
int k = nums.length - 1;
while (k > j) {
int aa = nums[i] + nums[j] + nums[k];
int newDiff = Math.abs(aa - target);
if (newDiff < diff) {
diff = newDiff;
sum = aa;
}
if (aa < target) {
j++;
} else {
k--;
}
}
}
return sum;
}

LeetCode_16 3SumCloest的更多相关文章

随机推荐

  1. 蓝桥 ADV-232 算法提高 矩阵乘法 【区间DP】

      算法提高 矩阵乘法   时间限制:3.0s   内存限制:256.0MB      问题描述 有n个矩阵,大小分别为a0*a1, a1*a2, a2*a3, ..., a[n-1]*a[n],现要 ...

  2. UVA 213 Message Decoding 【模拟】

    题目链接: https://cn.vjudge.net/problem/UVA-213 https://uva.onlinejudge.org/index.php?option=com_onlinej ...

  3. ubuntu 截图工具 Shutter,设置快捷键 Ctrl+Alt+A

    系统设置 键盘 快捷键 自定义快捷键

  4. oracle游标的定义使用

    oracle游标的定义使用 2008-02-23 15:12:57|  分类: oracle|字号 订阅 游标中定义的参数只要定义类型,不用定义长度,精度等: 游标使用一: declarecursor ...

  5. ModuleNotFoundError: No module named 'cStringIO'

    这是2.x转3.x问题: 2.x写法: import cStringIO 3.x写法: from io import StringIO 问题解决.

  6. [Advance] How to debug a program (上)

    Tool GDB Examining Memory (data or in machine instructions) You can use the command x (for “examine” ...

  7. CodeForces 382C Arithmetic Progression (排序+分类讨论)

    题意:给出一个长度为n的序列,表示有n张卡片,上面的数字,现在还有一张卡片,上面没有数字,问说可以写几种数字在这张卡片上面, 使得n+1张卡片上的数字可以排列成一个等差数列,有无限多种时输出-1. 析 ...

  8. C#命名空间 using的用法

    using的用法: 1. using指令:引入命名空间 这是最常见的用法,例如: using System; using Namespace1.SubNameSpace; 2. using stati ...

  9. EditText(1)EditText的类型和回车键的行为

    1,常见类型 <EditText android:id="@+id/email_address" android:layout_width="fill_parent ...

  10. scala学习笔记2:面向对象编程部分基础

    以下主要记录的是看完scala in programming这本书Functional Objects(第六章)后的要点总结. 1,程序中可变对象(var)和不可变对象(val)使用的权衡问题 不可变 ...