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
原文地址:https://www.cnblogs.com/chiyeung/p/9532353.html
时间: 2024-10-04 23:56:51