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.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
Constraints:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
- Only one valid answer exists.
The purpose of the twoSum
method is to find two numbers from the nums
list that add up to the target
sum. It does this by using a nested loop to iterate through all possible pairs of numbers in the nums
list.
The outer loop iterates over the indices of the nums
list from 0 to the length of the list. The inner loop iterates over the indices from i+1
to the length of the list. By starting the inner loop from i+1
, it ensures that each pair of numbers is considered only once and avoids redundant calculations (e.g., considering both (nums[i], nums[j]) and (nums[j], nums[i])).
Inside the nested loops, the method checks if the sum of the current pair of numbers (nums[i]
and nums[j]
) is equal to the target
sum. If a pair is found that satisfies this condition, the method immediately returns a tuple (i, j)
representing the indices of the two numbers. The break
statement following the return ensures that the method terminates and no further iterations are performed.
If no pair of numbers is found that adds up to the target
sum, the method will reach the end of the loops without encountering a return statement. In such cases, the method will implicitly return None
, indicating that no solution was found.
Another way:
Comments
Post a Comment