复制代码
1
2
3
4
5
6给定一个整数数组 nums 和一个目标值 target,在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。 例子: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
1.遍历:
思路:内外循环,取出一个数,与列表剩余数进行判定。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14from typing import List class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: for i in range(nums.__len__()): #外循环,遍历列表 for j in range(i+1, nums.__len__()): #内循环,遍历列表第i个之后的值 if nums[i] + nums[j] == target: #判断两数之和是否等于目标数 return [i, j] #满足,以列表形式返回结果 if __name__ == '__main__': nums = [3,2,4] target = 6 myfun = Solution() dst = myfun.twoSum(nums, target) print(dst)
2.哈希表(字典):
思路:初始化一个字典,遍历列表,判断字典中是否含有满足target-num[i]的键,若无,将值与索引(按键值)存入字典中;若有,输出target-num[i]键的值与当前id。
复制代码
1
2
3
4
5
6
7
8
9class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: dict = {} #初始化字典 for i in range(nums.__len__()): #遍历列表 if target - nums[i] in dict: #查看字典中是否含有与 target-num[i]的匹配项 return [dict[target - nums[i]], i] #存在,则找到和为目标值的两个数 dict[nums[i]] = i #不存在,将当前值与索引按照键值存储到字典中
最后
以上就是轻松秀发最近收集整理的关于编程练习系列-twoSum实现的全部内容,更多相关编程练习系列-twoSum实现内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复