I am currently working on problem 1 in Leetcode, named "Two Sum."
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].
My current code is:
def twosum_indices(nums, target):
for i in nums:
for v in nums[i + 1:]:
if i + v == target:
return nums.index(i), nums.index(v)
In this, nums is a list of integers, and the program must return two different indexes in a list, such that their true values add up to a given target. Although this works fine on most test cases, it fails on a list like [3,3] where both values are the same, and returns the same index twice, like [0,0] instead of returning the actual answer of [0,1]. Why is this happening?