TOW_SUM
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. Example:
1
2
3
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
method 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
print("input the length:" )
n = int(input())
print("input elements:" )
s = []
for m in range(n):
data = int(input())
s.append(data)
print("input target:" )
target = int(input())
for i in range(0 , len(s)):
for j in range(i+1 ,len(s)):
sum = s[i]+s[j]
if sum == target:
print(i, j)
method 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import math
print("input the length:" )
n = int(input())
print("input elements:" )
s = []
for m in range(n):
data = int(input())
s.append(data)
print("input the target:" )
target = int(input())
len = int(math.ceil(n/2 ))
for i in range(0 ,len):
j=target-s[i]
if j in s:
print(i,s.index(j))
近期评论