赞
踩
两数之和问题是LeetCode上的一道经典算法题,也是面试中常见的问题。题目要求在一个整数数组中找到两个数,使它们的和等于一个特定的目标值,并返回这两个数的下标。
以下是多种解法:
- def twoSum(nums, target):
- n = len(nums)
- for i in range(n):
- for j in range(i+1, n):
- if nums[i] + nums[j] == target:
- return [i, j]
- return None
- def twoSum(nums, target):
- sorted_nums = sorted(nums)
- left, right = 0, len(nums)-1
- while left < right:
- curr_sum = sorted_nums[left] + sorted_nums[right]
- if curr_sum == target:
- break
- elif curr_sum < target:
- left += 1
- else:
- right -= 1
- if left < right:
- # 在原数组中查找对应的下标
- index1 = nums.index(sorted_nums[left])
- index2 = nums.index(sorted_nums[right], index1+1)
- return [index1, index2]
- return None
- def twoSum(nums, target):
- num_set = set()
- for num in nums:
- complement = target - num
- if complement in num_set:
- index1 = nums.index(complement)
- index2 = nums.index(num, index1+1)
- return [index1, index2]
- num_set.add(num)
- return None
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。