11. Pair That Hits the Target
A gift card can be spent on exactly two different items from a shop's price list. The price of every item is written in an array, and the card holds a fixed amount that must be used up exactly.
Write a method pairSum that takes the array nums of item prices and an integer target (the card's value) and returns the positions of the two items whose prices add up to target, as an array [i, j] with i < j. Positions start at 0.
Exactly one such pair exists in every test, and an item cannot be used twice.
Example 1
- Input:
- nums = [2,7,11,15], target = 9
- Output:
- [0,1]
- Explanation:
The prices at positions 0 and 1 are 2 and 7, and 2 + 7 = 9.
Example 2
- Input:
- nums = [3,2,4], target = 6
- Output:
- [1,2]
- Explanation:
2 + 4 = 6 at positions 1 and 2. The 3 cannot be paired with itself.
Constraints
2 ≤ nums.length ≤ 1000
-106 ≤ nums[i] ≤ 106
Exactly one pair of positions adds up to target
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(n)