LeetCode - 3Sum Closest

LeetCode - 3Sum Closest

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

My Solution is as following:

class Solution:
    # @param {integer[]} nums
    # @param {integer} target
    # @return {integer}
    def threeSumClosest(self, nums, target):
        i, nums = 0, sorted(nums)
        dis = abs(nums[0] + nums[1] + nums[2] - target)
        result = nums[0] + nums[1] + nums[2]
        while i < len(nums)-2:
            j, k = i+1, len(nums)-1
            while j < k:
                if nums[i] + nums[j] + nums[k] == target:
                    return target
                elif nums[i] + nums[j] + nums[k] < target:
                    if target - (nums[i] + nums[j] + nums[k]) < dis:
                        dis = target - (nums[i] + nums[j] + nums[k])
                        result = nums[i] + nums[j] + nums[k]
                    j += 1
                else:
                    if nums[i] + nums[j] + nums[k] - target < dis:
                        dis = nums[i] + nums[j] + nums[k] - target
                        result = nums[i] + nums[j] + nums[k]
                    k -= 1
            i += 1

        return result

本题要求查找三个元素,使其之和与给定target最为接近。我们首先对原数组进行排序,然后根据和与target的关系进行下标的移动,这里至少要有保存当前与target最为接近的三个元素的和,我用了两个变量dis、result更为方便一些(dis可以省略)。

你可能感兴趣的:(LeetCode)