Homework (2018-04-23, Monday of the eighth week)

16. 3Sum Closest

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

Problem solving ideas:

Since we need to find three such numbers, we maintain three subscripts i, j, k, and we can sort this list first. The first subscript i moves from 0 to n-1. For each subscript i, the initial value of j is set to i+1, and the initial value of k is n-1. The movement of j and k follows the following rules : If the sum of the three numbers is greater than the target value target, then j increases by 1, otherwise k decreases by 1, until j and k are equal. This is correct since the list is already sorted. For each group of i, j, k, the sum value with the smallest difference from the target value target can be found, and its time complexity is O(n^2), which is O(n^3) than the time complexity of the brute force solution. to be low.

code

class Solution:
    def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        nums.sort()
        closest_sum = nums[0]+nums[1]+nums[2]
        distance = abs(closest_sum-target)
        n = len(nums)
        for i in range(0,len(nums)-2):
        	j = i+1;
        	k = n-1;
        	while(j<k):
        		if abs(nums[i]+nums[j]+nums[k]-target)<distance:
        			distance = abs(nums[i]+nums[j]+nums[k]-target)
        			closest_sum = nums[i]+nums[j]+nums[k]
        		if (nums[i]+nums[j]+nums[k]) < target:
        			j+=1
        		else:
        			k-=1
        return closest_sum

16. 3Sum Closest


16. 3Sum Closest

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324787167&siteId=291194637
Recommended