Reputation: 22043
I tried the easiest problem in Leecodes to solve a twoSum,
The problems:
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.
My Conceptual Plan: Fix the first number and find (target - first)
Used: an O(n) iteration * O(n) linear search
from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)): #loop
find = target - nums[i]
print(i, find)
for j in range(i, len(nums)):#linear search
if find == nums[j]:
print(j)
return [i, j]
return None
When tried to check it
In [51]: Solution().twoSum(nums, target)
0 3
0
Out[51]: [0, 0]
Failed to find the problems and depressed to be stuck with the easiest problem in leecode.
Upvotes: 1
Views: 48
Reputation: 261
Try looping from i + 1
to len(nums)
in the second loop as you cannot use the same element twice. Other than that it looks correct.
Upvotes: 2