The array nums holds n integers, each between 1 and n inclusive. No value appears more than twice. Return every value that appears exactly twice, in any order. When nothing repeats, return an empty array.
5 sits at indices 0 and 3, and 1 at indices 1 and 5. Every other value appears once, and 4 and 7 don't appear at all. [5,1] is also accepted.
Each of 1, 2 and 3 appears once, so nothing repeats.
Constraints
n == nums.length1 <= n <= 10⁵1 <= nums[i] <= nnums appears once or twice.A hash set makes this easy. Can you do it in O(n) time with only O(1) extra memory, not counting the array you return? The judge only checks the answer, so that part is up to you.
A set of the values seen so far finds every repeat in one pass. For the O(1)-memory version, notice that every value v lies between 1 and n, so v − 1 is a valid index: the array itself can record which values you have already met.