Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
LeetCode/3sum-closest
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
45 lines (37 sloc)
1.46 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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). | |
My code: | |
import numpy as np | |
class Solution: | |
def threeSumClosest(self, nums, target): | |
""" | |
:type nums: List[int] | |
:type target: int | |
:rtype: int | |
""" | |
#First Sort | |
index=np.argsort(nums) | |
close_value=100000000000 | |
for i in range(len(nums)): | |
value1=nums[index[i]] | |
lstart=i+1 | |
rstart=len(nums)-1 | |
while lstart<rstart: | |
#print('running lstart %d rstart %d'%(lstart,rstart)) | |
value2=nums[index[lstart]] | |
value3=nums[index[rstart]] | |
if abs(value1+value2+value3-target)<close_value: | |
close_value=abs(value1+value2+value3-target) | |
record=[] | |
record.append(value1) | |
record.append(value2) | |
record.append(value3) | |
if value1+value2+value3<target: | |
lstart+=1 | |
else: | |
rstart-=1 | |
return sum(record) | |
Solution: | |
https://leetcode.com/problems/3sum-closest/ |