[LeetCode&Python] Problem 1: 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

  

 

posted on 2018-08-24 22:49  chiyeung  阅读(143)  评论(0)    收藏  举报

导航