16. 最接近的三数之和

作者: 花果山松鼠 | 来源:发表于2018-08-08 16:56 被阅读4次

    一、题目原型:

    给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
    例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.
    与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).

    二、题目意思剖析:

    最接近其实可以转化为,(三数之和 - target)的绝对值最小。
    result = |三数之和 - target|,只需要找出最小的result即可。
    result理论上最小值为0,即和target相等

    三、解题思路:

    最简单的是三层遍历。这里就不说了,复杂度太高。不过也通过了leetcode检测。耗时400ms,超过百分之11的提交记录。

    其实我们可以将其简化为 和 上一题15. 三数之和一样的模式上。
    也就是将最前面的数字抽出来,然后让left指针和right指针在该数字之后的数组里进行滑动。找出三数之和 - target的绝对值的最小值即可。判断会有点多。。。

    func threeSumClosest(_ nums: [Int], _ target: Int) -> Int {
        if(nums.count < 3){
            var result = 0
            for value in nums {
                result = result + value
            }
            return result;
        }
        var tempNums = nums.sorted{$0<$1}
        let count = tempNums.count
        var threeSum = tempNums[0] + tempNums[1] + tempNums[2]
        print(tempNums)
        for indexF in 0 ..< count {
            if (indexF != 0) && (tempNums[indexF] == tempNums[indexF - 1]){
                continue
            }
            let tempArray = self.aFunction(numbers: tempNums, begin: indexF + 1, end: count)
            print(tempArray)
            var left:Int = 0
            var right:Int = tempArray.count - 1
            while left < right {
                print(threeSum)
                let newOffsetValue = tempArray[left] + tempArray[right] + tempNums[indexF] - target
                if(newOffsetValue == 0){
                    return target;
                }
                
                let result = threeSum - target
                if(result < 0){
                    if(newOffsetValue < 0){
                        if(newOffsetValue > result){
                            threeSum = newOffsetValue + target
                        }
                        left = left + 1
                    }else{
                        if(newOffsetValue < abs(result)){
                            threeSum = newOffsetValue + target
                        }
                        right = right - 1
                    }
                }else{
                    if(newOffsetValue < 0){
                        if(abs(newOffsetValue) < result){
                            threeSum = newOffsetValue + target
                        }
                        left = left + 1
                    }else{
                        if(newOffsetValue < result){
                            threeSum = newOffsetValue + target
                        }
                        right = right - 1
                    }
                }
            }
        }
        return threeSum
    }
    

    四、小结

    总提交数
    提交结果

    有其他好的方法请极速留言,非常乐意一起探讨。😄!

    相关文章

      网友评论

        本文标题:16. 最接近的三数之和

        本文链接:https://www.haomeiwen.com/subject/mwexbftx.html