题目来自leetcode.com
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.
class Sol():
def __init__(self, a1=0,a2=0,a3=0):
self.a1 = a1
self.a2 = a2
self.a3 = a3
def update(self,a1,a2,a3):
self.a1 = a1
self.a2 = a2
self.a3 = a3
def _num(a1,a2,a3,arr,target):
sum = arr[a1]+arr[a2]+arr[a3]
sum -= target
if sum >=0:
return sum
else:
return -1*sum
ans = Sol()
target = input("input the target num ")
num = input("input the number of array ")
target = int(target)
num = int(num)
arr = []
a = 0
while a < num:
arr.append(int(input()))
a += 1
a = 0
cl = 100000
while a < num-2:
b = a+1
while b <num-1:
c = b+1
while c <num:
d = _num(a,b,c,arr,target)
print(d)
if cl > d:
cl = d
ans.update(a,b,c)
print(ans.a1)
c += 1
b += 1
a += 1
cl = arr[ans.a1]+arr[ans.a2]+arr[ans.a3]
print('the sum that is cloest to the target is '+str(cl)+'.('+str(arr[ans.a1])+'+'+str(arr[ans.a2])+'+'+str(arr[ans.a3])+'='+str(cl)+')')