Description:
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
Ideas:
The first idea in my mind is traversing the list using enumerate() to record the idx and elem, then
traversing the remaining elem in the list again, and add the two elem to judge if the result is equal
to the target. In this way, i found it does work, but it's too slow. Then I saw that if I can judge whether
elem which substracts from the target is in the list.It will more efficient.
On 01.28, I thought it's possible to use two pointers to solve this problem. First, Sort the list in
ascending, then we can use i, j to travserse list from head & tail respectively.
My code:
# mapping the subtract num in list
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i1, x in enumerate(nums):
temp = target-x
if (temp in nums) and (nums.index(temp) != i1):
i2 = nums.index(temp)
return [i1, i2]
Execution takes:20ms
Memory consumption:12.9MB
# pointers
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
new_nums = sorted(nums, reverse=False)
i = 0
j = len(new_nums) - 1
while i < j:
x = new_nums[i]
y = new_nums[j]
total = x + y
if total == target:
if x != y:
return [nums.index(x), nums.index(y)]
elif x == y:
return [i for (i, m) in enumerate(nums) if m==x]
elif total < target:
i += 1
elif total > target:
j -= 1
return False
Execution takes:24ms
Memory consumption:13.1MB
The others code:
# use dict
def twoSum(self, nums, target):
dct = {}
for i, n in enumerate(nums):
cp = target - n
if cp in dct:
return [dct[cp], i]
else:
dct[n] = i
Execution time takes:20ms
Memory consumption:13.1MB
Execution time for searching key in dict:
- key in dict : 1.088 s
- dict.get(key) : 1.294 s
- dict[key] : 1.01 s
summary
It seems that I haven't consider time complexity, maybe i have forgotten what time complexity is.
In this series,I’ll record my exercise in leetcode, and try to write the process in English. This’s the first essay in 2021.01.27 by Cheung. Hope it will be a good start.