[LeetCode&Python] Problem1: Two Sum
Posted chiyeung
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode&Python] Problem1: Two Sum相关的知识,希望对你有一定的参考价值。
Problem Description:
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].
Approach 1: Brute Force
At the beginning, I want to use the Brute Froce method to use this problem. Then I write this code:
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ n=len(nums) for j in range(n): for i in range(j+1,n): if nums[j]+nums[i]==target: return j,i
However, this method wastes too much time.
Solution:
A better method to solve this problem is to use a dictionary to store all the pairs‘ indices.
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ n=len(nums) d={} for x in range(n): a = target-nums[x] if nums[x] in d: return d[nums[x]],x else: d[a]=x
以上是关于[LeetCode&Python] Problem1: Two Sum的主要内容,如果未能解决你的问题,请参考以下文章
C++&Python描述 LeetCode C++&Python描述 LeetCode 剑指 Offer 22. 链表中倒数第k个节点
[LeetCode&Python] Problem 202. Happy Number
[LeetCode&Python] Problem 520. Detect Capital
[LeetCode&Python] Problem 383. Ransom Note