Sobes.tech
Senior
46

/** * Ricerca di due numeri in un array la cui somma sia uguale a un numero dato * <p> * Scrivi una funzione che accetti come primo argomento un array di numeri positivi * non ordinati * e come secondo argomento un numero positivo. * La funzione dovrebbe restituire true se nell'array * ci sono 2 numeri la cui somma dà il secondo argomento. * <p> * Input: ([10, 15, 3, 7], 17) * Output: true */

Le aziende dove è stato chiesto
VKVK

Risposta dell'AI

sobes.tech AI

java public class TwoSum { public static boolean hasTwoSum(int[] nums, int target) { Set<Integer> complements = new HashSet<>(); for (int num : nums) { if (complements.contains(num)) { return true; } complements.add(target - num); } return false; }

public static void main(String[] args) {
    int[] arr = {10, 15, 3, 7};
    int target = 17;
    System.out.println(hasTwoSum(arr, target)); // true
}

}


Функция `hasTwoSum` использует множество для хранения "дополняющих" чисел, которые нужны, чтобы в сумме получить `target`. При проходе по массиву, если текущее число есть в множестве, значит найдено два числа, сумма которых равна `target`. Это решение работает за O(n) по времени и O(n) по памяти.