Topic https://leetcode.com/problems/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, A, target=9
Output:index1=1, index2=2
Ideas
First consider the time Complexity O (n^2) loop traversal, Leetcode can not endure.
The second scenario is O (N), when iterating through an array, the value is key, the index is a dictionary of value, and then each time the target value minus the current value from the dictionary gets index,index less than I, the description exists in the dictionary.
Code O (n^2)
classSolution1:#@param {integer[]} nums #@param {integer} target #@return {integer[]} deftwosum (self, Nums, target): RLT= [] if notNums:returnRLT forIinchRange (len (nums)): forJinchRange (Len (nums[i+1:])): ifNums[i] + nums[i+j] = =target:rlt.append (i) rlt.append (i+j)returnRlt
Code O (N)
classSolution:#@param {integer[]} nums #@param {integer} target #@return {integer[]} deftwosum (self, Nums, target): RLT= [] if notNums:returnRLT num_dict= {} forIinchRange (len (nums)):ifNums[i] not inchNum_dict:num_dict[nums[i]]=IPrintNums[i],i J= Num_dict.get (Target-nums[i], 1) ifJ < I andJ >-1: Rlt.append (J+1) rlt.append (i+1) returnRLTreturnRlt
Refer to Address 1. http://blog.csdn.net/jiadebin890724/article/details/23305449
Leetcode1-two Sums