Skip to content

Commit 7b088e3

Browse files
AC
HashMap is hash table
1 parent 99e9ab1 commit 7b088e3

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package com.mycompany.set_map;
2+
3+
/*
4+
* To change this license header, choose License Headers in Project Properties.
5+
* To change this template file, choose Tools | Templates
6+
* and open the template in the editor.
7+
*/
8+
/**
9+
*
10+
* @author Admin
11+
*/
12+
import java.util.Scanner;
13+
import java.util.HashMap;
14+
15+
public class J08015 {
16+
17+
public static void main(String[] args) {
18+
Scanner sc = new Scanner(System.in);
19+
int t = sc.nextInt();
20+
21+
while (t-- > 0) {
22+
int n = sc.nextInt();
23+
long k = sc.nextLong();
24+
long[] arr = new long[n]; //kich thuoc cua mang chi de int
25+
HashMap<Long, Integer> hm = new HashMap<>(); // tạo đối tượng hashmap
26+
for (int i = 0; i < n; i++) {
27+
arr[i] = sc.nextLong();
28+
}
29+
for (int i = 0; i < n; i++) {
30+
if (!hm.containsKey(arr[i])) {
31+
hm.put(arr[i], 0); // khởi tạo key arr[i] có value = 0
32+
}
33+
hm.put(arr[i], hm.get(arr[i]) + 1); //tăng value của key lên 1
34+
}
35+
long twice_count = 0;
36+
for (int i = 0; i < n; i++) {
37+
if (hm.get(k - arr[i]) != null) { //tồn tại cặp số có tổng bằng k
38+
twice_count += hm.get(k - arr[i]);
39+
}
40+
if (k - arr[i] == arr[i]) { // trừ chính số a[i] ra khỏi kết quả.
41+
twice_count -= 1;
42+
}
43+
}
44+
System.out.println(twice_count / 2);
45+
}
46+
}
47+
}

0 commit comments

Comments
 (0)