public boolean checkIfExist(int[] arr) { Set<Integer> seen = new HashSet<>(); int…
- User
public boolean checkIfExist(int[] arr) { Set seen = new HashSet<>(); int zeroCount = 0;
for (int num : arr) { if (num == 0) { zeroCount++; if (zeroCount == 2) { return true; // Если нашли два нуля, то 0 == 2 * 0 } } else { if (seen.contains(2 * num) || (num % 2 == 0 && seen.contains(num / 2))) { return true; } } seen.add(num); } return false; }Given an array arr of integers, check if there exist two indices i and j such that :
i != j 0 <= i, j < arr.length arr[i] == 2 * arr[j] Мне кажется, или для этой задачи необязательно считать нули, ответ всё-равно правильно зачтётся
- Assistant
Yes, you are correct. In this problem, it's not necessary to handle zeros separately by counting them. The main check in your code:
if (seen.contains(2 * num) || (num % 2 == 0 && seen.contains(num / 2))) { return true; }will correctly handle zeros as well. Here's why:
-
When
num == 0, both2 * numandnum / 2(since zero divided by any non-zero number is zero) will be zero. So the condition simplifies to:if (seen.contains(0) || seen.contains(0)) { return true; } -
On the first occurrence of zero,
seendoes not contain zero yet, so the condition is false. Zero is then added to theseenset.
-