欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

给定一个整数, 从里面找出两个数, 其和等于一个指定的整数.

程序员文章站 2024-03-16 09:14:04
...
'''
Given an array of integers, return indices of the two numbers such that they add up to a specific

target.You may assume that each input would have exactly one solution, and you may not use the same

element twice.

题意: 给定一个整数, 从里面找出两个数, 其和等于一个指定的整数.
程序返回这两个数在数组中的位置( 数组下标从1开始 ) , 且位置小的在前面. 
target = 20
[7,8,9,12] -> 20= 8+12 -> target_array[1,3]
'''



def test_time_complex(array,target):
	target_array = []
	for i in range(len(array)):
		# print("i",i)
		for j in range(i+1,len(array)):
			# print("j",j)
			if array[i] + array[j] == target:
				print(i,j)
				target_array.append(j)
				target_array.append(i)
					# print("target_array",target_array)
				if target_array[0] > target_array[1]:
					target_array[0],target_array[1] = target_array[1],target_array[0]

	return target_array

target = 9
array = [1,12,9,8]
print(test_time_complex(array,target))