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