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

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

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).
public int ThreeSumClosest(int[] nums, int target) {        Array.Sort(nums);        int size = nums.Count();        int res = Int32.MaxValue;        for(int i =0;i< size-1;i++)        {            int last = Int32.MaxValue;            int dif = target - nums[i];            int left = i+1;            int right = size-1;            while(left < right)            {                int a = nums[left] + nums[right] - dif;                if(a==0) return target;                if(Math.Abs(a)< last )                {                    res = Math.Abs(a)>Math.Abs(res) ?res :a;                    last = Math.Abs(a);                }                if(a<0) left++;                else right--;            }                    }        return res+target;    }

 

转载于:https://www.cnblogs.com/renyualbert/p/5904861.html

你可能感兴趣的文章
Linux企业运维高效技巧心得及分享
查看>>
fdisk分区和挂载
查看>>
2019春第八周作业
查看>>
AsyncTask和Handler两种异步方式的实现和区别比较
查看>>
wordpress搬迁后内页显示链接错误解决办法
查看>>
制造行业流程管理的“IPO”思维
查看>>
Android PhotoView基本功能实现
查看>>
类中的变量
查看>>
LeetCode 98. 验证二叉搜索树
查看>>
Kali Linux Web渗透测试手册(第二版) - 3.2 - 使用ZAP寻找敏感文件和目录
查看>>
Python入门 学习笔记 (一)
查看>>
ArrayList简单实现代码,欢迎大家指点
查看>>
Android开发手记(30) 触摸及手势操作
查看>>
Python------类的结构细分,异常处理,方法,属性
查看>>
41.内存函数实现(memcpy,memset,memmove,memicmp,memchr.memccpy)
查看>>
环形队列的c++实现
查看>>
扩展欧几里德算法求不定方程
查看>>
软件项目托管平台
查看>>
Oracle :多表更新多个字段
查看>>
Programming Languages - Coursera 整理
查看>>