File tree 1 file changed +47
-0
lines changed
Set_Map/src/main/java/com/mycompany/set_map
1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments