Two sum(给定一个无重复数组和目标值,查找数组中和为目标值的两个数,并输出其下标)...
生活随笔
收集整理的这篇文章主要介绍了
Two sum(给定一个无重复数组和目标值,查找数组中和为目标值的两个数,并输出其下标)...
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
示例:
nums = [1,2,5,7] target = [6]
return [0,2]
Python解决方案1:
def twoSum(nums, target):""":type nums: List[int]:type target: int:rtype: List[int]"""for i in range(len(nums)):remain = target - nums[i]if remain in nums and nums.index(remain) != i:return [i,nums.index(remain)]
Python解决方案2(转载于leetcode用户Dirk41):
def twoSum(nums, target):""":type nums: List[int]:type target: int:rtype: List[int]"""data = { nums[i]: i for i,n in enumerate(nums)}for i in range(len(nums)):complement = target - nums[i]if complement in data and data.get(complement) != i:return [i, data.get(complement)]
方案2的运行速度快很多倍
转载于:https://www.cnblogs.com/wenqinchao/p/10523148.html
总结
以上是生活随笔为你收集整理的Two sum(给定一个无重复数组和目标值,查找数组中和为目标值的两个数,并输出其下标)...的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: C++使用socket实现进程通信
- 下一篇: tf.nn 和tf.layers以及tf