Find out the number pairs in the array with the difference value K

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.