29. Double Trouble
A bakery sells trays of cookies, and the number of cookies on each tray is written in an array. A regular customer always asks whether there is one tray that holds exactly twice as many cookies as some other tray, because she likes to buy them as a pair.
Write a method hasDoublePair that takes the array nums and returns true if there are two different positions i and j such that nums[i] == 2 * nums[j], and false otherwise. A tray cannot be paired with itself, but two different trays with 0 cookies do count as a pair.
Example 1
- Input:
- nums = [10,2,5,3]
- Output:
- true
- Explanation:
The tray with 10 cookies holds exactly twice the 5 of another tray.
Example 2
- Input:
- nums = [3,1,7,11]
- Output:
- false
- Explanation:
No tray holds exactly double another, so the answer is false.
Constraints
1 ≤ nums.length ≤ 1000
-109 ≤ nums[i] ≤ 109
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)