码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode&Python] Problem1: Two Sum

时间:2018-08-24 23:41:35      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:beginning   bec   nbsp   color   may   amp   python   exactly   RoCE   

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

标签:beginning   bec   nbsp   color   may   amp   python   exactly   RoCE   

原文地址:https://www.cnblogs.com/chiyeung/p/9532353.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!