當前位置:
首頁 >
Two sum(给定一个无重复数组和目标值,查找数组中和为目标值的两个数,并输出其下标)...
發布時間:2025/3/15
24
豆豆
生活随笔
收集整理的這篇文章主要介紹了
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