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

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

依旧先来题目:

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).

 

     个人觉得这个是比较简单的一道题哈,我比较擅长这种。唯一比较难的就是最后代码的那个while loop的运用。

     对我来说如果没有想到这个while的话可能就会复杂很多了。主要是不要一直觉得要从头开始3个数字或者从后面开始3个数字这样比较固化的思维。

     而且对于这种杂乱的数列,先sorting整理是很有必要的。

     同样的就是设定初始比较值那个min的时候,想不到怎么设索性就来个最大的不就对了嘛。

public class Solution {    public int threeSumClosest(int[] nums, int target) {       if(nums==null||nums.length==0){           return -1;       }       int result=0;       int min=Integer.MAX_VALUE;       Arrays.sort(nums);       for(int i=0;i

 

转载于:https://www.cnblogs.com/orangeme404/p/4718860.html

你可能感兴趣的文章
java set集合与List集合练习
查看>>
简短总结一下C#里跨线程更新UI
查看>>
201612-2 工资计算
查看>>
DevExpress下拉多选框 CheckComboboxEdit、CheckedListBoxControl
查看>>
HashMap实现缓存
查看>>
javax.persistence.TransactionRequiredException: Executing an update/delete query
查看>>
Gym 100733G No Negations
查看>>
C++ 编写的DLL导出的函数名乱码含义解析
查看>>
python的setup.py文件及其常用命令
查看>>
JavaScript中的事件循环
查看>>
花花的礼物 (huahua)
查看>>
AssetBundle
查看>>
JS对象 字符串分割 split() 方法将字符串分割为字符串数组,并返回此数组。 语法: stringObject.split(separator,limit)...
查看>>
PHP加密解密函数之Base64
查看>>
PHP加密解密函数之Crypt
查看>>
BZOJ2259 [Oibh]新型计算机
查看>>
java step1:基础知识1
查看>>
PHP设置时区
查看>>
[ZJOI2008]骑士
查看>>
SPFA求最短路——Bellman-Ford算法的优化
查看>>