赵明川
赵明川

Reputation: 3

Two Sum. I use a nested loop but it seems not work

class Solution(object)
  def twoSum(self,num,target):
    #nested for loop, but the result shows only the inner loop works

    for i in range(0,len(num)-1,1):
       for j in range(i+1,len(num),1):
             target=target-num[i]-num[j]
             if target!=0:
                target=target+num[i]+num[j]
             else:
                break

        return i,j
Solution().twoSum([0,1,1,3,0],4)

Output:(0, 4) #the first number never changes and always be zero.So I think it may be the problem of the outer loop, but why and what can I do to make it work?

Upvotes: 0

Views: 1182

Answers (1)

brunobell
brunobell

Reputation: 11

Since you're not telling your goal, I guess that you're looking for sort of solution like this?

class Solution(object):
    def twoSum(self, num, target):
        ans = []
        for i in range(len(num) - 1):
            for j in range(i + 1, len(num)):
                s = num[i] + num[j]
                if s == target:
                    ans.append((i, j))
        return ans

print Solution().twoSum([0, 1, 1, 3, 0], 4)

People would really just feel confused if you just ask this way.

Upvotes: 1

Related Questions