Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

16. 3Sum Closest #16

Open
yunshuipiao opened this issue May 16, 2019 · 0 comments
Open

16. 3Sum Closest #16

yunshuipiao opened this issue May 16, 2019 · 0 comments

Comments

@yunshuipiao
Copy link
Owner

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).

解法

与上一题的方法相同,不过这题判断更为简单,绝对值为0 就返回。

特别注意下标合法性的判断

import org.testng.annotations.Test

fun threeSumClosest(nums: IntArray, target: Int): Int {
    var result = 0
    if (nums.size < 3) {
        return 0
    }
    var tempNums = nums
    tempNums.sort()
    result += tempNums[0] + tempNums[1] + tempNums[2]
    for (index in 0..tempNums.size - 3) {
        var l = index + 1
        var r = tempNums.size - 1
        while (l < r) {
            val tempResult = tempNums[index] + tempNums[l] + tempNums[r]
            if (tempResult > target) {
                r -= 1
            } else if (tempResult < target) {
                l += 1
            } else {
                return tempResult
            }
            if (Math.abs(tempResult - target) <= Math.abs(result - target)) {
                result = tempResult
            }
        }
    }
    return result
}


@Test
fun _0016() {
    arrayListOf(intArrayOf(1, 1, -1, -1, 3)).forEach {
        println(threeSumClosest(it, 1))
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant