There might be a better way, but I would first try the following:
1. Sort the data, O(n log n)
{ 1, 2, 3, 5, 7, 9, 12 };
2. Remove duplicates, if any. (could be combined into step 3 to prevent another traversal)
{ 1, 2, 3, 5, 7, 9, 12 };
3. Have two indices to keep track of where you are (one for each pair), increment them like the movement of an inch worm, so to speak.
Counter A: nums[0] --> 1
Counter B: nums[1] --> 2
difference less than 2, so increment counter B
Counter A: nums[0] --> 1
Counter B: nums[2] --> 3
difference equal to 2, so add to list of pairs, and increment counter A
Counter A: nums[1] --> 2
Counter B: nums[2] --> 3
difference less than 2, so increment counter B
Counter A: nums[1] --> 2
Counter B: nums[3] --> 5
difference greater than 2, so increment counter A
Counter A: nums[2] --> 3
Counter B: nums[3] --> 5
difference equal to 2, so add to list of pairs, and increment counter A.
etc. |