I am trying to solve the twoSum LeetCode problem via a brute force algorithm. Essentially the question is to find the indexes of two numbers that equal to the target. So if I had a list [7,2,4,1] and my target was 9, I would return index of 7 & 9 (which in this ex is [0,1]) as the solution.
I have written this algorithm here:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
if (len(nums) < 2):
return False
count = 0
for i in range(len(nums)):
for j in range (i 1, len(nums)):
if nums[i] nums[j] == target:
ans = str(nums.index(nums[j])) str(nums.index(nums[i]))
return ans
count = count 1
It works for everything except the one scenario where two elements in a list are duplicates. So if the list contained [3,3] with target 6, my algorithm is returning index [0,0] instead of [0,1]. What is causing this issue and what would be the proper solution to fixing it?
CodePudding user response:
ans = str(nums.index(nums[j])) str(nums.index(nums[i]))
This happens because you try to obtain the index of 3 on this line twice, which will return index 0 twice. Why not return string of i
and j
itself since they are already indices?
So:
ans = str(j) str(i)
CodePudding user response:
The problem is not from your algorithm but in the way you translate the answer in string (ans = str(nums.index(nums[j])) str(nums.index(nums[i]))
)
l.index(i)
will return the first index of l
containing the value i, so when the value is duplicated, nums.index(nums[j])==nums.index(nums[i])
, I believe you actually want to have ans = str(j) str(i)
instead