0
Leetcode two_Sum Problem
I got my first problem at Leetcode! The easiest one though... I completed with a while and several if statements. But when I try to use another solution, I was stuck. ......def two_sum(self,nums,target)....... j=1 while True: for i in range(j): If j<=len(nums)-1: if nums[i]+nums[j]==target: return [i,j] break else: j+=1 else: break Anyone can take a look and any help?
5 Réponses
+ 3
The while loop is infinite. The break statements only act on the "for" and "if" loops.
The logic behind your code seems to be fine, but I can't be sure since there's no description about the problem.
+ 1
Hi Diego, thank you for reply. Below is the problem itself.
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].
I skipped the class and function, just focused on the algorithm. Do you think the range(j) is an issue?
+ 1
j=1
while j <= len(nums)-1:
for i in range(j):
if nums[i]+nums[j]=target:
return [i,j]
else:
pass
j+=1
problem resolved.
+ 1
for j in range(len(nums)):
for i in range(j):
if nums[i] + nums[j] == target:
return [i,j]
0
Yours looks better. The runtimes are similar, since our logics are the same, I assume.