LeetCode:1. Two Sum
生活随笔
收集整理的這篇文章主要介紹了
LeetCode:1. Two Sum
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
https://leetcode.com/problems/two-sum
問題描述:
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].這里介紹一個時間復雜度為o(N)的方法:
首先暴力搜索時間復雜度較高,不推薦。非暴力搜索可以采用如下方法,但一定要避免一個陷阱。比如說,對于[3,2,4],target為6的話,target-num=3,返回的就是[0, 0]了,顯然并不是我們想要的。要避免這個問題就一定要先返回,else再添加。
這個代碼的巧妙之處在于只需要一次for遍歷就可以全部搞定。借用enumerate枚舉來確定num的位置。另一個通過字典鍵值對的辦法可以搜索到。
class Solution(object):def twoSum(self, nums, target):""":type nums: List[int]:type target: int:rtype: List[int]"""lookup = {}for i, num in enumerate(nums):if target - num in lookup:return [lookup[target-num], i]else:lookup[num] = i總結
以上是生活随笔為你收集整理的LeetCode:1. Two Sum的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Keras实现mode.fit和mode
- 下一篇: LeetCode:2. Add Two