import java.util.*; public class Main { public static int solve(int[][] nums1, int[][] nums2, int tar) { int ans =0; //add first array in hashmap and make its frequency map HashMap<Integer,Integer> fmap = new HashMap<>(); for(int i=0 ; i< nums1.length ; i++){ for(int j = 0 ; j < nums1[0].length ; j++){ int val = nums1[i][j]; fmap.put(val , fmap.getOrDefault(val,0)+1); } } //now iterate through 2nd array and if target - nums2[i] is present in map then add its frequency (as frequency will be no. pair which is equal to target) for(int i =0 ; i<nums2.length ; i++){ for(int j = 0 ; j < nums2[0].length ; j++){ int val = nums2[i][j]; int rem = tar - val; //remaining value if(fmap.containsKey(rem)) ans += fmap.get(rem); } } return ans; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int[][] mat1 = new int[N][N]; for (int i = 0; i < mat1.length; i++) { for (int j = 0; j < mat1[0].length; j++) { mat1[i][j] = sc.nextInt(); } } int[][] mat2 = new int[N][N]; for (int i = 0; i < mat2.length; i++) { for (int j = 0; j < mat2[0].length; j++) { mat2[i][j] = sc.nextInt(); } } int K = sc.nextInt(); System.out.println(solve(mat1, mat2, K)); } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter