当前位置:网站首页>Daily 3 questions (3) - check whether integers and their multiples exist

Daily 3 questions (3) - check whether integers and their multiples exist

2022-06-25 10:48:00 Programmed ape without hair loss 2

subject :

Give you an array of integers  arr, Please check whether there are two integers  N and M, Satisfy  N  yes  M  Twice as many ( namely ,N = 2 * M).

More formally , Check if there are two subscripts  i and j Satisfy :

i != j
0 <= i, j < arr.length
arr[i] == 2 * arr[j]

Example 1:

Input :arr = [10,2,5,3]
Output :true
explain :N = 10 yes M = 5 Twice as many , namely 10 = 2 * 5 .
Example 2:

Input :arr = [7,1,14,11]
Output :true
explain :N = 14 yes M = 7 Twice as many , namely 14 = 2 * 7 .
Example 3:

Input :arr = [3,1,7,11]
Output :false
explain : Does not exist in this case N and M Satisfy N = 2 * M .

Tips :

2 <= arr.length <= 500
-10^3 <= arr[i] <= 10^3

Ideas :

Store all the numbers in the hash table first , Then traverse all the numbers xx, Judge 2x2x Whether it is in the hash table .

java Code :

class Solution {
     public boolean checkIfExist(int[] arr) {
        HashSet<Integer> set = new HashSet<>();
        for (int i : arr) {
            if (set.contains(2 * i) || (i % 2 == 0 && set.contains(i / 2)))
                return true;
            set.add(i);
        }
        return false;
    }
}
原网站

版权声明
本文为[Programmed ape without hair loss 2]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206251024211371.html