思路一为遍历:

public int thirdSolution(int[] nums, int target) {
int result = nums[0] + nums[1] + nums[2];
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
int start = i + 1, end = nums.length - 1;
while (start < end) {
int tmp = nums[i] + nums[start] + nums[end];
if (tmp < target) {
start++;
}
if (tmp > target) {
end--;
}
if (tmp == target) {
return tmp;
}
if (Math.abs(tmp - target) < Math.abs(result - target)) {
result = tmp;
}
}
}
return result;
}

整体思路二为将threeSum将为twoSum即可

public int solution(int[] nums, int target) {
if (nums.length == 3) {
return nums[0] + nums[1] + nums[2];
} else {
Arrays.sort(nums);
int r = 10000;//此两处10000为省事而设,如果严谨应该大致找到其中的一个较大距离
int distance = 10000;
for (int i = 0; i < nums.length; i++) {
int[] temarray = new int[nums.length - 1];
System.arraycopy(nums, 0, temarray, 0, i);
System.arraycopy(nums, i + 1, temarray, i, nums.length - i - 1);
int tem = twoSumClosest(temarray, target - nums[i]) + nums[i];
int temdistance = tem - target;
if (temdistance < 0) {
temdistance = -temdistance;
} else if (temdistance == 0) {
return tem;
}
if (temdistance < distance) {
r = tem;
distance = temdistance;
}
}
return r;
}
} private int twoSumClosest(int[] nums, int target) {
int l = 0, r = nums.length - 1;
int min = nums[r] + nums[l];
int distance;
if (min - target > 0) {
distance = min - target;
} else {
distance = target - min;
}
while (l < r) {
if (nums[l] + nums[r] == target)
return nums[l] + nums[r];
if (nums[l] + nums[r] < target) {
if (target - (nums[l] + nums[r]) < distance) {
min = nums[l] + nums[r];
distance = target - (nums[l] + nums[r]);
}
l++;
continue;
}
if (nums[l] + nums[r] > target) {
if ((nums[l] + nums[r]) - target < distance) {
min = nums[l] + nums[r];
distance = (nums[l] + nums[r]) - target;
}
r--;
continue;
}
}
return min;
}

本质上讲两种思路没有区别

最新文章

  1. GJM : 【技术干货】给The Lab Renderer for Unity中地形添加阴影
  2. linux命令学习(一)—— 文件和目录管理命令
  3. Genesis不能运行Perl编译后的脚本
  4. jQuery学习笔记(一):入门【转】
  5. win server 2008配置ftp无法登陆问题的解决办法
  6. php用jquery-ajax上传多张图片限制图片大小
  7. CUBRID学习笔记23 关键字列表
  8. python一个注意的地方
  9. Dynamically loading an external JavaScript or CSS file
  10. Struts2.x jsp页面无法使用jsp:forward跳转到action
  11. Entity Framework 杂碎
  12. Qt 图形特效(Graphics Effect)介绍
  13. margin的简单应用
  14. Android Annotations(2)
  15. redis 安装实战(10步完成安装)
  16. Docker学习(转)
  17. CentOS 7.4nginx配置SSL
  18. 同事在使用shiro后遇到的异常
  19. Mysql 性能优化7【重要】sql语句的优化 浅谈MySQL中优化sql语句查询常用的30种方法(转)
  20. python的动态性和_slot_

热门文章

  1. redmine设置
  2. 马哥教育视频笔记:01(Linux常用命令)
  3. wex5 教程 之 图文讲解 后台管理界面设计与技巧
  4. Xcode7编译打包后,iOS9设备无法打开http网址的问题
  5. HTTP中Get与Post的区别
  6. Reflection
  7. [四校联考P3] 区间颜色众数 (主席树)
  8. HDU1848 Fibonacci again and again SG函数
  9. SQL Server书籍整理
  10. 使用GIt向github上传代码