Your algorithm is still O (n ^ 2), even when sorting and starting. And even if you deleted the O (n ^ 2) bit, the sorting is still O (n lg n). You can use O (n) algorithm to solve this problem. Here is one way to do this:
Suppose you have set the value S1 = { 1, 7, 4, 6, 3 } , and the difference is 2.
Build the set S2 = { 1 + 2, 7 + 2, 4 + 2, 6 + 2, 3 + 2 } = { 3, 9, 6, 8, 5 } .
The answer you are looking for is the intersection power of S1 and S2. The intersection {6, 3} , which has two elements, so the answer is 2.
You can implement this solution in one line of code, provided that you have a sequence of integers sequence and integer difference :
int result = sequence.Intersect(from item in sequence select item + difference).Count();
The Intersect method will build an effective hash table for you, which is O (n) to determine the intersection.
Eric Lippert
source share