[Hackerrank] Pairs

Source: Internet
Author: User

Link: Pairs

This is the deformation of the two sum problem! The two sum problem requires that the two numbers in the array and the number is exactly equal to K. This is to find that the difference between the two numbers in the array is exactly equal to the two numbers in K. The conclusion is actually the question of "riding a donkey to find a horse": traversing ar [I], you only need to check whether ar [I] + K or AR [I]-K exists in the array, or use hashmap to complete this operation at O (1) time.

The question is not clear about whether the elements are repeated. It seems that there are no duplicates from editorial, but I still use the value of map to record the occurrence frequency of the number to process the duplicates.

The Code is as follows:

 1 import java.util.*; 2  3 public class Solution {     4     public static void main(String[] args) { 5         Scanner in = new Scanner(System.in); 6         int n = in.nextInt(); 7         int k = in.nextInt(); 8         HashMap<Integer, Integer> map = new HashMap<Integer,Integer>(); 9         int[] ar = new int[n];10         for(int i = 0;i < n;i ++){11             ar[i] = in.nextInt();12             if(!map.containsKey(ar[i]))13                 map.put(ar[i], 0);14             map.put(ar[i], map.get(ar[i])+1);15         }16         17         int answer = 0;18         for(int i = 0;i < n;i ++){19             int up = ar[i]+k;20             if(map.containsKey(up))21                 answer += map.get(up);22             int down = ar[i]-k;23             if(map.containsKey(down))24                 answer += map.get(down);25         }26         System.out.println(answer/2);27         28     }29 }

 

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.