Number of Different Subsequences GCDs LeetCode solution in Java

1
class Solution {
2
int max = 0;
3
Set<Integer> exist = new HashSet();
4

5
public int countDifferentSubsequenceGCDs(int[] nums) {
6
getMax(nums);
7
for (int num : nums) exist.add(num);
8
int count = 0;
9
for (int i = 1; i <= max; i++) if (findGCD(i)) count++; // <---- findGCD
10
return count;
11
}
12

13
public void getMax(int[] nums) {
14
for (int i : nums) max = Math.max(max, i);
15
}
16

17
public int gcd(int a, int b) {
18
return (a == 0) ? b : gcd(b % a, a);
19
}
20

21
public boolean findGCD(int num) {
22
int val = 0;
23
for (int i = num; i <= max; i += num)
24
if (exist.contains(i)) val = gcd(i, val); // <---- gcd between two number
25
return (val == num);
26
}
27
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0