Leetcode 1:two Sum
Given an array of integers, find the numbers such that they add up to a specific target number.
The function twosum should return indices of the numbers such that they add up to the target, where index1 must is Les S than Index2. Please note that your returned answers (both Index1 and INDEX2) is not zero-based.
You may assume this each input would has exactly one solution.
Input: numbers={2, 7, one, target=9
Output: index1=1, index2=2
Analysis
Use Python dict structure to solve it.
Store array to an dict. Let's assume X is a number in array. If both X and (Target-x) is in the dict, then they is what we is looking for.
Pay attention to an exception:
If target is twice x, we should take extra effort. Details is in codes explanation. Solution
Python Codes
Class solution (Object): Def twosum (self, Nums, target): "" ": Type Nums:list[int]: type target:in T:rtype:list[int] "" "L = [] D = {}" ": Store List value and index t o Dict:dict[value] = index + 1:if list Cantains Many same value and target is twice value, return the values ' Indexes ' "" for index, X in Enumerate (nums): If x isn't in d:d[x] = index + 1 elif target = = 2 * x:l = [d[x], index+1] return L "": If (t Arget-x) also exist in Dict and target are not twice value,: The result is indexes of X and (Target-x) "" " For x in Nums:if ((target-x) in D) and target! = 2 * x:l = [d[x], D[target-x]] return L
Leetcode 1:two Sum