Given an array arr
of integers, check if there exist two integers N
and M
such that N
is the double of M
( i.e. N = 2 * M
).
More formally check if there exist two indices i
and j
such that :
i != j
0 <= i, j < arr.length
arr[i] == 2 * arr[j]
Example 1:
Input: arr = [10,2,5,3] Output: true
Approach
Java
public class CheckIfNDoubleExist {public static void main(String[] args) {int[] arr = { 10, 2, 5, 3 };System.out.println(checkIfExist(arr));}static boolean checkIfExist(int[] arr) {for (int i = 0; i < arr.length; i++) {for (int j = 0; j < arr.length; j++) {if (i != j) {if (arr[i] == 2 * arr[j] || arr[j] == 2 * arr[i])return true;}}}return false;}}
C++
#include <bits/stdc++.h>using namespace std;bool checkIfExist(vector<int> &arr){for (int i = 0; i < arr.size(); i++){for (int j = 0; j < arr.size(); j++){if (i != j){if (arr[i] == 2 * arr[j] || arr[j] == 2 * arr[i])return true;}}}return false;}int main(){vector<int> arr = {10, 2, 5, 3};if (checkIfExist(arr))cout << "true";elsecout << "false";return 0;}
No comments:
Post a Comment