16. The Lone Sock
After a laundry day, every sock in the basket has a matching partner with the same pattern number, except for one sock whose partner has gone missing. The socks are in the basket in no particular order.
Write a method singleNumber that takes the array nums of pattern numbers and returns the pattern number of the sock that has no partner. Every other pattern number appears exactly twice.
Example 1
- Input:
- nums = [4,1,2,1,2]
- Output:
- 4
- Explanation:
1 and 2 each appear twice, so the lonely pattern is 4.
Example 2
- Input:
- nums = [7]
- Output:
- 7
- Explanation:
A single sock has no partner at all.
Constraints
1 ≤ nums.length ≤ 999, and nums.length is odd
-109 ≤ nums[i] ≤ 109
Exactly one value appears once; every other value appears exactly twice
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(1)