Idea: There is an unordered array with duplicate numbers, and an integer k to find out how many pairs of non-repeating pairs (I, j) make the difference between I and J just K. Since K is likely to be 0, and only a few two of the same number can form a number pair, it means that the number of each number in the array needs to be counted. You can establish a mapping between each number and its occurrence, and then traverse the number in the hash table, and if K is 0 and the number appears more than 1, the result counts from 1, and if K is not 0, and the new number obtained with the current number plus K is present in the array, the result is count from 1, See the code below:
classSolution { Public: intFindpairs (vector<int>& Nums,intk) {intCount =0, length =nums.size (); Unordered_map<int,int>numbers; for(Auto num:nums) {Numbers[num]++; } for(Auto num:numbers) {if(k = =0&& Num.second >1) count++; if(k >0&& Numbers.count (num.first+k)) count++; } returncount; }};
Find out the number pairs in the array with the difference value K