考试结束,班级平均分只拿到了年级第二,班主任于是问道:大家都知道世界第一高峰珠穆朗玛峰,有人知道世界第二高峰是什么吗?正当班主任要继续发话,只听到角落默默想起来一个声音:”乔戈里峰”
前言
2018.11.18号打卡今天的题目leetcode15:
以下是昨天的题解
题目
每天一道leetcode16-最接近的三数之和
题目详述
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
题目详解
思路
先sort一下array,为啥要sort呢,因为要用到two pointers 来遍历找两数之和,只有在从小到大排序之后的结果上,才能根据情况移动left 和right。
首先是如果数组只有3个数字,那么直接返回这三个数字之和;(最少三个数)
当确定好了第一个数字后,就在剩下的array里找两数之和,在加上第一个数字,用这个tempSum减去target 来得到tempCha;(tempCha就是临时的一个差值)
比较tempCha与之前保留的cha的值大小,如果比cha小,那么说明此刻的tempCha就有可能是最小的差,记录下来这个时候的tempCha和这个时候的可能是最后返回结果的三数之和
利用two pointers 特性, 如果tempSum 比target 小的话,说明我们需要更大的sum,所以要让left++以便得到更大的sum。 如果tempSum 比target 大的话,我们就需要更小的sum,所以right--。如果相等的话,直接return 就可以了。因为都相等了,那么差值就等于0,不会有差值再小的了。
代码
1class Solution {
2 public int threeSumClosest(int[] nums, int target) {
3 if(nums.length == 3)
4 return nums[0] + nums[1] + nums[2];
5 Arrays.sort(nums);
6 int result = 0;
7 int cha = Integer.MAX_VALUE;
8 int tempCha = 0 ;
9 for(int one=0;one < nums.length-2;one++)
10 {
11 int left = one + 1;
12 int right = nums.length - 1;
13 while(left < right)
14 {
15 int tempSum = nums[one] + nums[left] + nums[right];
16 tempCha = Math.abs(tempSum - target);
17 if(tempCha < cha)
18 {
19 cha = tempCha;
20 result = tempSum;
21 }
22 if(tempSum == target)
23 {
24 return target;
25 }
26 if(tempSum < target)
27 {
28 left++;
29 }else{
30 right--;
31 }
32
33 }
34 }
35 return result;
36 }
37}
代码讲解
3-4行 三个数直接返回这三个数之和
9行的意思是固定下来一个数,然后从剩下的数组中进行双指针操作
11-12行,每次都是从9行固定的数开始,从数组末尾,这两个端点进行双指针逼近
15-21行就是如果和tempSum与target的差值tempCha比之前的cha还要小,那么说明是可能的最小的cha,也就是可能的最接近target的和,把这些中结果保留下来
22-31行就是 利用two pointers 特性, 如果tempSum 比target 小的话,说明我们需要更大的sum,所以要让left++以便得到更大的sum。 如果tempSum 比target 大的话,我们就需要更小的sum,所以right--。如果相等的话,直接return 就可以了。因为都相等了,那么差值就等于0,不会有差值再小的了。
经验教训
见注释
1class Solution {
2 public int threeSumClosest(int[] nums, int target) {
3 if(nums.length == 3)
4 return nums[0] + nums[1] + nums[2];
5 Arrays.sort(nums);
6 int result = 0;
7 int one = 0;
8 int tempSum = nums[one] + nums[1] + nums[nums.length-1];
9 int cha = Integer.MAX_VALUE;
10 int left = 1;
11 int right = nums.length - 1;
12 int tempCha = 0 ;
13 for(one=0;one < nums.length-2;one++)
14 {
15 left = one + 1;
16 right = nums.length - 1;
17 while(left < right)
18 {
19 tempSum = nums[one] + nums[left] + nums[right];
20 tempCha = Math.abs(tempSum - target);
21 if(tempCha <= cha)
22 {
23 cha = tempCha;
24 result = tempSum;//这里的潜在的最后的正确结果没注意保存
25 }else{
26 break;//这里使用了一个break,我以为tempCha大于cha这一层循环就不用了,但是没准往中间逼近的时候和还更小了呢,这里想当然了
27 }
28 if(tempSum == target)
29 {
30 return target;
31 }
32 if(tempSum < target)
33 {
34 left++;
35 }else{
36 right--;
37 }
38
39 }
40 }
41 return result;
42 }
43}
结束语
2018.11.18号打卡
关于本号
作者乔戈里亲历2019秋招,哈工大计算机本硕,百度java工程师,欢迎大家关注我的微信公众号:程序员乔戈里,公众号有3T编程资源,以及我和我朋友(百度C++工程师)在秋招期间整理的近200M的面试必考的java与C++面经,并有每天一道leetcode打卡群与技术交流群,欢迎关注。
3T编程资料等你来拿