给定一个整数数组 nums?和一个目标值 target,请你在该数组中找出和为目标值的那?两个?整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
class Solution:
def twoSum(self, nums: list, target: int) -> list:
for i in range(len(nums)):
find_num = target - nums[i]
for j in range(len(nums)):
if find_num == nums[j] and j != i:
return [i, j]
if __name__ == "__main__":
print(Solution().twoSum([2, 7, 11, 15], 9))
class Solution:
def twoSum(self, nums: list, target: int) -> list:
arr = sorted(nums)
for i in range(len(arr)):
key = target - nums[i]
find_num = self.binary_search(arr, key)
if find_num != None:
j = 0
find = True
while j < len(nums):
if j == i:
j += 1
if nums[j] != find_num:
if j == len(nums) - 1:
find = False
break
j += 1
else:
break
if find:
return [i, j]
def binary_search(self, nums: list, key: int) -> int:
start = 0
end = len(nums) - 1
while start <= end:
index = (start + end) // 2
if nums[index] == key:
return nums[index]
elif nums[index] > key:
end = index - 1
else:
start = index + 1
return None
原文:https://www.cnblogs.com/blogfyang/p/12203036.html