Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

python - Two Sum solution on LeetCode

I am currently on LeetCode and am looking through the solutions for the Two Sum problem. Here are the instructions,

"Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order."

I ran across a couple solutions and I saw this answer:

def twoSum(self, nums: [int], target: int) -> tuple:
    num2idx = {}        
    for idx, val in enumerate(nums):
        if target - val in num2idx:
            return num2idx[target - val], idx
        num2idx[val] = idx

The part that I am unsure of is this,

if target - val in num2idx:
  return num2idx[target - val], idx
num2idx[val] = idx

How exactly will this return both indices of the numbers that add up to the target? It looks to me like what is being return is solely the, "target-val" as well as the index of the current num being iterated over.

question from:https://stackoverflow.com/questions/65832737/two-sum-solution-on-leetcode

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

num2idx is holding the location of each number, not the number itself. The statement

 return num2idx[target - val], idx

returns the index of the current number, as well as the index of the number that makes up the difference between the current number and the target.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...