I am working on the Two Sums question from Leetcode, where you have to find the indices of the two numbers that add up to the target.
In the question statement three examples were given to check for: nums = [2,7,11,15]
& target = 9
(should output [0,1]
), nums = [3,2,4]
& target = 6
(should output [1,2]
) and finally nums = [3,3]
& target = 6
(should output [0,1]
). The order of the output is said to not be important. Link to question
My code works perfectly for the first two situations, however for nums = [3,3]
& target = 6
it returns [0, 0]
instead of the desired [0,1]
. I think the error is because nums.index(j)
in my code returns the index for the very first value of 3
it finds, so 0
instead of the desired 1
.
Is there a way to fix this without having to change the entire code? (so to get the correct index in case of duplicates in the nums
list?)
Thank you in advance!
This is my code:
class Solution:
def twoSum (output, nums, target):
output = []
for i in range(len(nums)):
for j in nums[i+1:]:
if nums[i]+j == target:
output.append(i)
output.append(nums.index(j))
return output