编程题 第八周第二节课作业

本文介绍了一个LeetCode上的经典问题:寻找数组中三个整数的组合,使其和最接近给定的目标值,并返回这三个整数的和。通过使用Python实现,遍历数组并计算所有可能的三数组合,找到距离目标最近的和。

题目来自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)+')')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值