Pregunta de entrevista de Wallet Hub

Write Java code to find K-complementary pairs in a given array of integers. Given Array A, pair (i, j) is K- complementary if K = A[i] + A[j];

Respuestas de entrevistas

Anónimo

14 nov 2017

public class ComplimentryPair { public int noOfComplimentryPairUsingEight(int[] arr, int k) { Map map = new HashMap(); for (int i = 0; i map.getOrDefault(element, 0)).sum(); } public int noOfComplimentaryPair(int[] arr, int k) { Map map = new HashMap(); for (int i = 0; i < arr.length; i++) { int complValue = k - arr[i]; int tempValue = map.containsKey(complValue) ? map.get(complValue) : 0; map.put(complValue, tempValue + 1); } int counter = 0; for (int i = 0; i < arr.length; i++) { counter += map.containsKey(arr[i]) ? map.get(arr[i]) : 0; } return counter; } }

Anónimo

8 nov 2018

import java.util.Arrays; public class KComplemantaryPairs { public static void main(String[] args) { System.out.println( "findKComplemantaryOf(10, new int[]{1, 5, 9}) = " + findKComplemantaryOf(10, new int[]{1, 5, 9})); System.out.println("findKComplemantaryOf(10, new int[]{1, 5, 9, 9, 10, 0}) = " + findKComplemantaryOf(10, new int[]{1, 5, 9, 9, 10, 0})); System.out.println( "findKComplemantaryOf(10,new int[]{1, 5, 9, 11, -1,5})) = " + findKComplemantaryOf(10, new int[]{1, 5, 9, 11, -1, 5})); } private static int findKComplemantaryOf(int k, int[] numbers) { int total = 0; for (int number : numbers) { int complement = k - number; long count = Arrays.stream(numbers).filter(num -> num == complement).count(); total += count; } return total; } }