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

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

这个题很简单,还是取一个值,然后另外两个值从两端向中间逼近

public class Solution {    public int threeSumClosest(int[] nums, int target) {        int length = nums.length;        List
numList = new ArrayList
(length); for (int num : nums) { numList.add(num); } Collections.sort(numList); int sum1 = numList.get(0) + numList.get(1) + numList.get(2); int sum2 = numList.get(length-1) + numList.get(length-2) + numList.get(length-3); int max1 = distance(sum1, target); int max2 = distance(sum2, target); int max = max1 < max2? max1:max2; int targetSum = max1 < max2? sum1: sum2; for (int i = 0; i < length - 2; i++) { int p = i+1; int q = length - 1; while (p < q) { int sum = numList.get(i) + numList.get(p) + numList.get(q); int dis = distance(sum, target); if (dis == 0) { return target; } if (dis < max) { targetSum = sum; max = dis; } if (sum < target) { p++; } else { q--; } } } return targetSum; } private int distance(int source, int target) { if (source > target) { return source - target; } else { return target - source; } }}

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

你可能感兴趣的文章
简述计算机从加电到启动系统时主板的工作流程
查看>>
用 Docker 来标准化开发、测试、生产环境
查看>>
centos6.2修改网卡名称
查看>>
我的友情链接
查看>>
django 数据库使用(sqlite3和mysql)
查看>>
长字符串,原始字符串和Unicode
查看>>
部署奥科AA导致Lync Server 2010无法下载拓扑案例处理
查看>>
java中生成30万的excel(采用多个excel,每个上面放6万数据,最后打包zip保存)...
查看>>
solr在windows下部署安装
查看>>
Linux终端概念及相关命令
查看>>
CentOS 6.6编译安装Nginx1.6.2+MySQL5.6.21+PHP5.6.3
查看>>
Java 引用类型变量和基本类型变量做参数时的区别
查看>>
各种查看TCP连接的命令
查看>>
实现web系统的权限控制
查看>>
android项目小模块
查看>>
我的友情链接
查看>>
js 实现日历效果
查看>>
我的友情链接
查看>>
Go笔记-Go命令
查看>>
Redis设计与实现笔记
查看>>