LeetCode(16)-3Sum Closest

版权声明:XiangYida https://blog.csdn.net/qq_36781505/article/details/83388214

16. 3Sum Closest

Given an array nums of n integers and an integer target, find three >integers in nums such that the sum is closest to target. Return the >sum of the three integers. You may assume that each input would >have exactly one solution.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

题目的意思就是:给一个整形数组,然后找出里面的三个数字之和的结果与target最接近,并输出这个结果。嗯我的思路很简单,穷举出所有结果然后比较。这种思路有点low,有点耗时,不过还算通过测试了,先暂时贴上吧,后面再来研究大神的代码。

public int threeSumClosest(int[] nums, int target) {
       int min=Integer.MAX_VALUE;
       for (int i = 0; i <nums.length; i++) {
           for (int j =i+1; j <nums.length; j++) {
               for (int k = 0; k <nums.length; k++) {
                   int sum=nums[i]+nums[j]+nums[k];
                   min=Math.min(Math.abs(sum-target),min);
               }
           }
       }
       return min;
   }

猜你喜欢

转载自blog.csdn.net/qq_36781505/article/details/83388214