-
Notifications
You must be signed in to change notification settings - Fork 153
/
CountNonDivisible.java
57 lines (48 loc) · 1.84 KB
/
CountNonDivisible.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package CountNonDivisible;
import java.util.*;
class Solution {
public int[] solution(int[] A) {
// main idea:
// using "HashMap" to count
// map1(key, value)
HashMap<Integer, Integer> map1 = new HashMap<>();
// key: the elements, value, count of elements
for(int i=0; i< A.length; i++){
if(map1.containsKey(A[i]) == false){
map1.put(A[i], 1); // add new element
}
else{
map1.put(A[i], map1.get(A[i])+1 ); // count++
}
}
// map2(key, value)
HashMap<Integer, Integer> map2 = new HashMap<>();
// key: the elements, value, count of "number of non-divisors" of elements
for( int n : map1.keySet() ){
int numDivisors =0;
// find divisors from 1 to sqrt(n)
int sqrtN = (int)Math.sqrt(n);
for(int i=1; i<=sqrtN; i++ ){
if( n % i == 0){ // means: i could be a divisor
int anotherDivisor = n/i;
if(map1.containsKey(i) == true ){
numDivisors = numDivisors + map1.get(i);
}
if(anotherDivisor != i){ // avoid double count (be careful)
if(map1.containsKey(anotherDivisor) == true){
numDivisors = numDivisors + map1.get(anotherDivisor);
}
}
}
}
int numNonDivisors = A.length - numDivisors;
map2.put(n, numNonDivisors);
}
// results: number of non-divisors
int[] results = new int[A.length];
for (int i = 0; i < A.length; i++) {
results[i] = map2.get(A[i]);
}
return results;
}
}