描述:给定一个数组,找出数组中两元素之和等于目标值,返回两数的索引。
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:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
1、暴力枚举法:
比较简单,也很容易想到。先固定外层循环中的i,再到内层循环查找是否有target-n存在。
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
2、哈希函数
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
num2idx = dict()
for i, n in enumerate(nums):
if target - n in num2idx:
return num2idx[target - n], i
else:
num2idx[n] = i
3、双指针
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
tmp = []
for i in nums:
tmp.append(i) #对原数组备份
nums = sorted(nums)
left = 0
right = len(nums) - 1
while (left < right):
if nums[left] + nums[right] == target:
break
elif nums[left] + nums[right] < target:
left += 1
elif nums[left] + nums[right] > target:
right -= 1
res_a = nums[left]
res_b = nums[right]
###########################想想设置a、b有什么作用?假如没有会怎样?############################
left = -1
right = -1
for i in range(0, len(tmp)):
if tmp[i] == res_a and left == -1:
left = i
elif tmp[i] == res_b and right == -1:
right = i
############################################################################################
#########################################交换a、b############################################
if left > right:
left = left ^ right
right = left ^ right
left = left ^ right
return [left, right]
思路:1)首先需要对数组进行拷贝,在对数组进行排序后,原数组的顺序已经完全打乱。
2)设置指针分别从首尾进行取数判断,并根据判断的结果决定进行左加还是右减。之后就是找到原索引,在这个过程中分别设置left=-1和right=-1是为了索引的时候不会相互影响。以[3, 3]为例,如果没有tmp[i] == res_a and left == -1
的判断,最后的输出结果将是[1, 1]。当i=0时,left = i =0(不太科学,没想到怎么表示);当i=1时,虽然tmp[1] = res_a
但是left != -1
就会直接逃过而执行elif
。
参考:https://www.cnblogs.com/kirai/p/5597144.html