Java 可数不可分编码训练任务
我现在正在进行可变性训练。有些任务我可以自己解决,但有些任务有问题。 这项任务的难度很大。中等,但我熄火了 问题:Java 可数不可分编码训练任务,java,arrays,algorithm,training-data,Java,Arrays,Algorithm,Training Data,我现在正在进行可变性训练。有些任务我可以自己解决,但有些任务有问题。 这项任务的难度很大。中等,但我熄火了 问题: 您将得到一个由N个整数组成的非空零索引数组。 对于每个数字A[i],0≤ i
您将得到一个由N个整数组成的非空零索引数组。 对于每个数字A[i],0≤ i
A[0] = 3
A[1] = 1
A[2] = 2
A[3] = 3
A[4] = 6
对于以下要素:
A[0] = 3, the non-divisors are: 2, 6,
A[1] = 1, the non-divisors are: 3, 2, 3, 6,
A[2] = 2, the non-divisors are: 3, 3, 6,
A[3] = 3, the non-divisors are: 2, 6,
A[6] = 6, there aren't any non-divisors.
编写一个函数:
class Solution { public int[] solution(int[] A); }
给定一个由N个整数组成的非空零索引数组,返回一个表示非除数数的整数序列。
序列应返回为:
- 结构结果(在C中)
- 或整数向量(在C++中)
- 或记录结果(帕斯卡)
- 或整数数组(在任何其他编程语言中)
A[0] = 3
A[1] = 1
A[2] = 2
A[3] = 3
A[4] = 6
函数应该返回[2,4,3,2,0],如上所述。
假设:
- N是[1..50000]范围内的整数李>
- 数组A的每个元素都是[1..2*N]范围内的整数
- 期望的最坏情况时间复杂度为O(N*log(N))李>
- 预计最坏情况下的空间复杂度为O(N),超出了输入存储 (不计算输入参数所需的存储)
我写了一些解决方案。但我的解决方案体积庞大,仍然具有O(n^2)复杂性。 你能帮我一些想法或算法如何做它的最佳?这不是面试任务或其他什么。我只是在训练,试着解决所有的任务。 你可以在这里找到这个任务:第9课,第1课的第一个任务 谢谢大家! 要了解数字“2”在以下结果[2,4,3,2,0]上出现两次的原因,请参见下面的代码
A[0] = 3, the non-divisors are: 2, 6 >> Quantity: 2
A[1] = 1, the non-divisors are: 3, 2, 3, 6 >> Quantity: 4
A[2] = 2, the non-divisors are: 3, 3, 6, >> Quantity: 3
A[3] = 3, the non-divisors are: 2, 6 >> Quantity: 2
A[6] = 6, there aren't any non-divisors. >> Quantity: 0
因为返回数表示非除数的数量! 索引[0]有2个非除数,索引[3]也有2个非除数。解决方案尝试:(已编辑,请参见下文) 这些都不是很有用。也许这是“游戏”的一部分,但我现在不玩这个游戏。基本的想法应该很清楚,我假设它现在可以正常工作,直到有人证明它是一个反例-P 它仍然没有达到O(N)存储的复杂性,但我还没有想到一种可能的方法来彻底实现这一点…
/**
/**
* Count Non-divisible
*/
public class Solution {
public int[] solution(int[] A) {
int[] div = new int[A.length];
for (int e = 0; e < div.length; e++) {
div[e] = 0;
for (int i = 0; i < A.length; i++) {
int dividend = A[e];
if (dividend % A[i] != 0) {
div[e] += 1;
}
}
}
return div;
}
public static void main(String args[]) {
int[] A = new int[]{3, 1, 2, 3, 6};
Solution s = new Solution();
int[] B = s.solution(A);
for (int i = 0; i < B.length; i++) {
System.out.println(B[i]);
}
}
}
*不可除计数
*/
公共类解决方案{
公共int[]解决方案(int[]A){
int[]div=新的int[A.length];
对于(int e=0;e
此解决方案得100分
public int[]解决方案(int[]A){
int[][]D=新int[A.长度*2+1][2];
for(int i=0;i 对于(int j=1;j这是我的100分Python解决方案。希望对其他人有所帮助
def solution(A):
''' Solution for the CountNonDivisible by codility
Author: Sheng Yu - codesays.com
'''
from math import sqrt
A_max = max(A)
A_len = len(A)
# Compute the frequency of occurrence of each
# element in array A
count = {}
for element in A:
count[element] = count.get(element,0)+1
# Compute the divisors for each element in A
divisors = {}
for element in A:
# Every nature number has a divisor 1.
divisors[element] = [1]
# In this for loop, we only find out all the
# divisors less than sqrt(A_max), with brute
# force method.
for divisor in xrange(2, int(sqrt(A_max))+1):
multiple = divisor
while multiple <= A_max:
if multiple in divisors and not divisor in divisors[multiple]:
divisors[multiple].append(divisor)
multiple += divisor
# In this loop, we compute all the divisors
# greater than sqrt(A_max), filter out some
# useless ones, and combine them.
for element in divisors:
temp = [element/div for div in divisors[element]]
# Filter out the duplicate divisors
temp = [item for item in temp if item not in divisors[element]]
divisors[element].extend(temp)
# The result of each number should be, the array length minus
# the total number of occurances of its divisors.
result = []
for element in A:
result.append(A_len-sum([count.get(div,0) for div in divisors[element]]))
return result
def溶液(A):
可数不可分的余度的‘’解
作者:盛宇-codesays.com
'''
从数学导入sqrt
A_max=max(A)
A_len=len(A)
#计算每个事件的发生频率
#数组A中的元素
计数={}
对于A中的元素:
count[element]=count.get(element,0)+1
#计算一个矩阵中每个元素的除数
除数={}
对于A中的元素:
#每个自然数都有一个除数1。
除数[元素]=[1]
#在这个for循环中,我们只找到所有
#小于sqrt(A_max)的除数,带brute
#力法。
对于xrange(2,int(sqrt(A_max))+1中的除数:
倍数=除数
虽然多个我想我将在C++中分享我的解决方案,它得到100分。我认为这很简单。< /P>
Map<Integer, Long> map = IntStream.range(0, A.length)
.collect(HashMap::new,
(acc, i) -> acc.compute(A[i], (k, v) -> v == null ? 1 : ++v),
HashMap::putAll);
int[] removed = new int[A.length];
for (int i = 0; i < A.length; i++) {
int N = A[i];
int max = N;
List<Integer> divisors = new ArrayList<>();
if (N == 1) {
divisors.add(1);
} else {
for (int div = 1; div < max; div++) {
if (N % div == 0) {
divisors.add(div);
if (div != N / div) {
divisors.add(N / div);
}
}
if (N / div < max) {
max = N / div;
}
}
}
removed[i] += map.entrySet().stream()
.filter(entry -> divisors.stream().noneMatch(div -> Objects.equals(entry.getKey(), div)))
.mapToLong(e -> e.getValue()).sum();
首先,它统计数组中每个数字的出现次数
vector<int> solution(vector<int> &A) {
int N = A.size();
vector<int> counts (*std::max_element(A.begin(), A.end()) + 1,0);
// Calculate occurences of each number in the array
for (int i = 0; i < N; ++i)
{
counts[A[i]] += 1;
}
std::vector<int> answer(N,0);
// For each element of the array
for (int i = 0; i < N; ++i)
{
// Calulate how many of its divisors are in the array
int divisors = 0;
for (int j = 1; j * j <= A[i]; ++j)
{
if (A[i] % j == 0)
{
divisors += counts[j];
if (A[i] / j != j)
{
divisors += counts[A[i] / j];
}
}
}
// Subtract the number of divisors from the number of elements in the array
answer[i] = N - divisors;
}
return answer;
}
然后,对于每个数组元素i
,它会找到其除数的数目,范围为1到sqrt(i)
,包括除法结果的除数
最后,它从数组中的元素总数中减去给定元素的除数总数
vector<int> solution(vector<int> &A) {
int N = A.size();
vector<int> counts (*std::max_element(A.begin(), A.end()) + 1,0);
// Calculate occurences of each number in the array
for (int i = 0; i < N; ++i)
{
counts[A[i]] += 1;
}
std::vector<int> answer(N,0);
// For each element of the array
for (int i = 0; i < N; ++i)
{
// Calulate how many of its divisors are in the array
int divisors = 0;
for (int j = 1; j * j <= A[i]; ++j)
{
if (A[i] % j == 0)
{
divisors += counts[j];
if (A[i] / j != j)
{
divisors += counts[A[i] / j];
}
}
}
// Subtract the number of divisors from the number of elements in the array
answer[i] = N - divisors;
}
return answer;
}
向量解决方案(向量&A){
int N=A.size();
向量计数(*std::max_元素(A.begin(),A.end())+1,0);
//计算数组中每个数字的出现次数
对于(int i=0;i 对于(intj=1;j*j这对我来说很有效,在C上的得分为100%
struct Results solution(int A[], int N) {
struct Results result;
// write your code in C99
int *numbers = (int *)calloc(2*N + 1, sizeof(int));
for (int i = 0; i < N; i++) {
++numbers[A[i]];
}
int *numbers2 = (int *)calloc(2*N + 1, sizeof(int));
for (int i = 0; 2*i < 2*N + 1; i++) {
if (numbers[i] != 0) {
for (int j = 2*i; j < 2*N + 1; j+=i) {
numbers2[j] += numbers[i];
}
}
}
int * Carr = (int *)calloc(N, sizeof(int));
for (int i = 0; i < N; i++) {
Carr[i] = N - numbers[A[i]] - numbers2[A[i]];
}
result.C = Carr;
result.L = N;
free(numbers);
free(numbers2);
return result;
}
结构结果解决方案(int A[],int N){
结构结果;
//用C99编写代码
int*numbers=(int*)calloc(2*N+1,sizeof(int));
对于(int i=0;istruct Results solution(int A[], int N) {
struct Results result;
// write your code in C99
int *numbers = (int *)calloc(2*N + 1, sizeof(int));
for (int i = 0; i < N; i++) {
++numbers[A[i]];
}
int *numbers2 = (int *)calloc(2*N + 1, sizeof(int));
for (int i = 0; 2*i < 2*N + 1; i++) {
if (numbers[i] != 0) {
for (int j = 2*i; j < 2*N + 1; j+=i) {
numbers2[j] += numbers[i];
}
}
}
int * Carr = (int *)calloc(N, sizeof(int));
for (int i = 0; i < N; i++) {
Carr[i] = N - numbers[A[i]] - numbers2[A[i]];
}
result.C = Carr;
result.L = N;
free(numbers);
free(numbers2);
return result;
}
function solution(A) {
var N = A.length;
if (N < 1 || N > 50000) throw 'Error: Bad input';
var uniqueDict = {};
var keys = [];
for (var i = 0; i < N; ++i) {
var num = A[i]
var uniqueCount = uniqueDict[num];
if (uniqueCount > 0) {
uniqueDict[num] = uniqueCount + 1;
} else {
uniqueDict[num] = 1;
keys.push(num);
}
}
keys.sort(function(a,b){
return a-b;
});
for (i = keys.length-1; i >= 0; --i) {
num = keys[i];
var divisorCount = divisors(num, uniqueDict);
var nonDivisorCount = N - divisorCount;
uniqueDict[num] = nonDivisorCount;
}
for (i = 0; i < N; ++i) {
num = A[i];
A[i] = uniqueDict[num];
}
return A;
}
function divisors(num, uniqueDict) {
var count = 0;
var x = 1;
while (x * x <= num) {
if (parseInt(num/x) === num/x) { // is divisor
if (uniqueDict[num/x] > 0) {
count += uniqueDict[num/x];
}
if (num/x !== x && uniqueDict[x] > 0) {
count += uniqueDict[x];
}
}
x++;
}
return count;
}
boolean[] result_;
public int[] solution(int[] A) {
int a[][] = new int[2*A.length + 1][2];
result_ = new boolean[2*A.length + 1];
for(int i : A) {
++a[i][0];
}
a[1][1] = A.length - a[1][0];
result_[1] = true;
for(int i : A) {
multCount(a,A,i);
}
int[] result = new int[A.length];
for(int i=0;i<result.length; i++) {
result[i] = a[A[i]][1];
}
return result;
}
private void multCount( int[][] a, int[] A, int item) {
if( result_[item] )
return;
int sub=(int)Math.sqrt(item);
a[item][1] = A.length;
if(item % sub == 0&& sub >1){
a[item][1] -= a[sub][0];
int rest = item/sub;
if(rest != sub) {
a[item][1] -= a[rest][0];
}
}
a[item][1] -= a[item][0];
a[item][1] -= a[1][0];
for(int i=2; i<sub; i++) {
if(item % i == 0) {
a[item][1] -= a[i][0];
int rest = item/i;
a[item][1] -= a[rest][0];
}
}
result_[item] = true;
}
function solution(A) {
var N = A.length;
var count = [];
var i;
for (i = 0; i < 2*N+1; ++i){
count.push(0);
}
for (i = 0; i < N; ++i){
++count[A[i]];
}
var divisors = [];
for (i = 0; i < 2*N+1; ++i){
divisors.push(0);
} //the actual code starts here, before it's just initialisation of variables.
i = 1;
var k;
while (i <= 2*N){
k = i;
while (k <= 2*N){
divisors[k] += count[i];
k += i;
}
++i;
}
var result = [];
for (i = 0; i < N; ++i){
result.push(0);
}
for (i = 0; i < N; ++i){
result[i] = N - divisors[A[i]];
}
return result;
}
import java.util.*;
class Solution {
public int[] solution(int[] A) {
int N = A.length;
HashMap<Integer, Integer> count = new HashMap<>();
for (int i : A) {
Integer key = count.get(i);
if (key != null) {
count.put(i, key + 1);
} else {
count.put(i, 1);
}
}
HashMap<Integer, Integer> divs = new HashMap<>();
for (Integer n : count.keySet()) {
int sum = 0;
int j = 1;
while (j * j <= n) {
if (n % j == 0) {
if (count.containsKey(j)) {
sum += count.get(j);
}
//find n = j*k cases to add both to the dividors
int k = n / j;
if (k != j) {
if (count.containsKey(k)) {
sum += count.get(k);
}
}
}
j++;
}
divs.put(n, N - sum);
}
for (int i = 0; i < A.length; i++) {
A[i] = divs.get(A[i]);
}
return A;
}
}
function solution(A) {
let count = {}
// counting number frequency
A.map(a => {
//console.log(count[a])
if (count[a] > 0) {
count[a] = count[a] + 1
} else {
count[a] = 1
}
})
// console.log(count)
let divs = {}
Object.keys(count).map(key => {
let sum = 0
let j = 1
while (j * j <= key) {
if (key % j == 0) {
if (count[j] > 0) {
sum += count[j]
}
// adding another dividor
let k = key / j
// scenario: 9 = 81 / 9. Escaping same number
if (k != j) {
if (count[k] > 0) {
sum += count[k]
}
}
// another possible solution: sum = sum * 2
// if key is square number: sum -= 1
}
j++
}
divs[key] = A.length - sum
})
// console.log(divs)
let answer = []
A.map(a => {
answer.push(divs[a])
})
// console.log(answer)
return answer
}
#include <math.h>
struct Results solution(int A[], int N) {
int maxA = 0, i, j, sqrtA;
int *counts, *cache;
struct Results result;
result.C = (int *) malloc(N*sizeof(int));
result.L = N;
// Grep the maximum.
for (i = 0; i < N; ++i) {
if (A[i] > maxA)
maxA = A[i];
}
++maxA;
// Initialize some arrays.
counts = (int *) malloc(maxA*sizeof(int));
cache = (int *) malloc(maxA*sizeof(int));
for (i = 0; i < maxA; ++i) {
counts[i] = 0;
cache[i] = -1;
}
// Count A.
for (i = 0; i < N; ++i) {
counts[A[i]] += 1;
}
// Main computation begins.
for (i = 0; i < N; ++i) {
// If the answer is already computed, use it.
if (cache[A[i]] >= 0) {
result.C[i] = cache[A[i]];
continue;
}
// There's no existing answer, compute it.
cache[A[i]] = N;
sqrtA = (int) sqrt(A[i]);
for (j = 1; j <= sqrtA; ++j) {
if (A[i]%j == 0) {
cache[A[i]] -= counts[j];
if (j*j != A[i]) {
cache[A[i]] -= counts[A[i]/j];
}
}
}
result.C[i] = cache[A[i]];
}
// Since Codility prohibits the system calls,
// below free commands are commented.
// free(counts);
// free(cache);
return result;
}
import static java.lang.Integer.max;
import java.util.Arrays;
public int[] solution(int[] A) {
final int N = A.length;
final int MAX_VALUE_TBL = 2*50000;
int[] r = new int[N]; // result table
int[] AS_AV = new int[MAX_VALUE_TBL + 1]; // number of cell with values
int[] AS_AR = new int[MAX_VALUE_TBL + 1]; // results yet counted for values
boolean[] b = new boolean[MAX_VALUE_TBL + 1]; // if value has been counted
if (N == 1) return r;
for (int i = 0; i < N; i++) {
int v = A[i];
AS_AV[v]++;
}
for (int i = 0; i < N; i++) {
int cu_val = A[i];
if (!b[cu_val]) {
int am_div = getAmDivisors(cu_val, AS_AV);
r[i] = N - am_div;
b[cu_val] = true;
AS_AR[cu_val] = r[i];
} else {
r[i] = AS_AR[cu_val];
}
}
return r;
}
private int getAmDivisors(int cu_val, int[] AS_AV) {
int r = 0;
int sqr = (int) Math.sqrt(cu_val);
for (int divisor = sqr; divisor > 0; divisor--) {
if (cu_val % divisor == 0) {
r += AS_AV[divisor];
if (divisor * divisor != cu_val) {
r += AS_AV[cu_val / divisor];
}
}
}
return r;
}
def solution(A):
N=len(A)
num_non_divisors=[0]*N
if N<2:
return num_non_divisors
MaxVal=max(A)
#Trivial cases
if MaxVal < 2:
return num_non_divisors
MinVal=min(A)
if MinVal==MaxVal:
return num_non_divisors
Occur = [0] * (MaxVal + 1)
#Occurences of e in A
for e in A:
Occur[e]+=1
#Divisors of any element lower than MaxVal
Divisors = [Occur[1]] * (MaxVal + 1)
#DejaVu to avoid counting them more than once
DejaVu = [0] * (MaxVal + 1)
for e in A:
if e!=1 and DejaVu[e]==0:
Divisors[e]+=Occur[e]
DejaVu[e]+=1
i = 2
while (i * i <= MaxVal):
#We start at i x i to avoid counting 2 times multiples of the form k x i, where k<i.
k = i * i
while (k <= MaxVal):
Divisors[k] += Occur[i]
if i * i < k: #equivalent k/i != i
#Symmetric divisor
Divisors[k] += Occur[int(k/i)];
k += i
i += 1
#Re-initialize DejaVu
DejaVu = [0] * (MaxVal + 1)
for i in range(0,len(A)):
if not DejaVu[A[i]]:
DejaVu[A[i]]=N-Divisors[A[i]]
num_non_divisors[i]=DejaVu[A[i]]
return num_non_divisors
def solution(a)
elements = a.inject(Hash.new(0)) {|acc, el| acc[el] +=1;acc }
n = elements.keys.sort
div = n.each.inject(Hash.new(0)) do |acc, el|
k=el
while k < n[-1]
k+=el
acc[k] += elements[el]
end
acc
end
a.map {|x| a.size - elements[x] - div[x] }
end
public int[] solution(int[] A) {
//find max number. To be used for 'count sort' array size.
int max = A[0];
for (int i = 1 ; i < A.length ; i++) {
max = Math.max(max, A[i]);
}
//count sort
int [] count = new int [max+1];
for (int i = 0 ; i < A.length ; i++) {
count[A[i]]++;
}
int [] nonDiv = new int [max+1];
//initially count all elements as non divisible (minus 'number of occurrences' of the the given number)
for (int i = 1 ; i < nonDiv.length; i++) {
if (count[i] != 0) {//skip numbers which don't exists in table A
nonDiv[i] = A.length - count[i];
}
}
//sieve
for (int i = 1 ; i < nonDiv.length; i++) {
if (count[i] != 0) {//skip numbers which don't exists in table A
int s = i*2;
while (s<nonDiv.length) {
if (nonDiv[s] != 0) {
//Sieve. Most important part. Decrease number of non-divisible by the number of occurrences of number 'i'.
nonDiv[s] -= count[i];
}
s+=i;
}
}
}
//produce the output
int []res = new int [A.length];
for (int i = 0 ; i < A.length ; i++) {
res[i] = nonDiv[A[i]];
}
return res;
}
public class NonDivisiblesCounter
{
/// <summary>
/// 1. Count the ocurrences of each element
/// 2. Count all divisors for each element and subtract by the Length of array A to get nonDivisors
/// 3. Add it to a cache since the elements can repeat and you do not need to calculate again.
/// </summary>
/// <param name="A"></param>
/// <returns></returns>
public int[] Count(int[] A)
{
int n = A.Length;
var ocurrencesOfEach = CountOcurrencesOfEach(A);
var nonDivisorsOfEach = new int[n];
var nonDivisorsCache = new Dictionary<int, int>();
for (int i = 0; i < n; i++)
{
int element = A[i];
if (nonDivisorsCache.ContainsKey(element))
{
nonDivisorsOfEach[i] = nonDivisorsCache[element];
}
else
{
int nonDivisorCounter = n - CountDivisorsPerOcurrence(element, ocurrencesOfEach);
nonDivisorsOfEach[i] = nonDivisorCounter;
nonDivisorsCache[element] = nonDivisorCounter;
}
}
return nonDivisorsOfEach;
}
private int CountDivisorsPerOcurrence(int element, Dictionary<int, int> ocurrencesOfEach)
{
int square = (int)Math.Sqrt(element);
int divisorCounter = 0;
if (square * square == element && ocurrencesOfEach.ContainsKey(square))
{
divisorCounter += ocurrencesOfEach[square];
}
for (int divisor = 1; element / divisor > square; divisor++)
{
if (element % divisor == 0)
{
if (ocurrencesOfEach.ContainsKey(divisor))
{
divisorCounter += ocurrencesOfEach[divisor];
}
if (ocurrencesOfEach.ContainsKey(element / divisor))
{
divisorCounter += ocurrencesOfEach[element / divisor];
}
}
}
return divisorCounter;
}
private Dictionary<int, int> CountOcurrencesOfEach(int[] elements)
{
var result = new Dictionary<int, int>();
for (int i = 0; i < elements.Length; i++)
{
int element = elements[i];
if (result.ContainsKey(element))
{
result[element]++;
}
else
{
result.Add(element, 1);
}
}
return result;
}
}
package solution
// you can also use imports, for example:
// import "fmt"
// import "os"
// you can write to stdout for debugging purposes, e.g.
// fmt.Println("this is a debug message")
func Solution(A []int) []int {
tdMapping := make(map[int]int)
MaxValue := 2 * len(A)
occurs := make([]int, MaxValue+1)
for _, v := range A {
occurs[v]++
}
r := make([]int, len(A))
for i := 0; i < len(A); i++ {
totalDivisors := 0
if _, ok := tdMapping[A[i]]; ok {
totalDivisors = tdMapping[A[i]]
} else {
for j := 1; j*j <= A[i]; j++ {
if j*j == A[i] {
totalDivisors += occurs[j]
} else {
if A[i]%j == 0 {
totalDivisors += occurs[j] + occurs[A[i]/j]
}
}
}
tdMapping[A[i]] = totalDivisors
}
r[i] = len(A) - totalDivisors
}
return r
}
function solution(A) {
const createCounts = A => {
const counts = Array(A.length * 2 + 1).fill(0)
for (let i = 0; i < A.length; i++) {
counts[A[i]] += 1
}
return counts
}
const counts = createCounts(A)
const results = []
for (let i = 0; i < A.length; i++) {
let nonDivisiblesCount = A.length
let j = 1
while (j * j < A[i]) {
if (A[i] % j === 0) {
nonDivisiblesCount -= counts[j]
nonDivisiblesCount -= counts[A[i] / j]
}
j++
}
if (j * j === A[i]) {
nonDivisiblesCount -= counts[j]
}
results.push(nonDivisiblesCount)
}
return results
}
const A = [3, 1, 2, 3, 6]
console.log(A)
const s = solution(A)
console.log(s)
func Solution(A []int) []int {
aSize := len(A)
maxValue := A[0]
for idx := 0; idx < aSize; idx++ {
element := A[idx]
if maxValue < element {
maxValue = element
}
}
remainDividersCountList := make([]int, maxValue+1)
for idx := 0; idx < aSize; idx++ {
element := A[idx]
if remainDividersCountList[element] == 0 {
remainDividersCountList[element] = aSize - 1
} else {
remainDividersCountList[element] = remainDividersCountList[element] - 1
}
}
cachedResultMap := make([]int, maxValue+1)
alreadyCalculated := make([]int, maxValue+1)
alreadyCalculatedDuplicated := make([]int, maxValue+1)
caluclatedMap := make(map[int][]int)
for idx := 0; idx < aSize; idx++ {
element := A[idx]
if alreadyCalculated[element] == 0 {
for multiplier := 2; multiplier <= maxValue/element; multiplier++ {
multResult := element * multiplier
if multResult > maxValue {
break
} else {
cachedResult := cachedResultMap[multResult]
if cachedResult > 0 {
cachedResultMap[multResult] = cachedResult + 1
} else {
cachedResultMap[multResult] = 1
}
caluclatedMap[element] = append(caluclatedMap[element], multResult)
}
}
alreadyCalculated[element] = 1
} else if alreadyCalculatedDuplicated[element] == 0 {
multiplier := aSize - (remainDividersCountList[element] + 1)
list := caluclatedMap[element]
for repIdx := 0; repIdx < len(list); repIdx++ {
repElem := list[repIdx]
cachedResultMap[repElem] = cachedResultMap[repElem] + (1 * multiplier)
}
alreadyCalculatedDuplicated[element] = 1
}
}
result := make([]int, aSize)
for idx := 0; idx < aSize; idx++ {
element := A[idx]
result[idx] = remainDividersCountList[element] - cachedResultMap[element]
}
return result
}
Map<Integer, Long> map = IntStream.range(0, A.length)
.collect(HashMap::new,
(acc, i) -> acc.compute(A[i], (k, v) -> v == null ? 1 : ++v),
HashMap::putAll);
int[] removed = new int[A.length];
for (int i = 0; i < A.length; i++) {
int N = A[i];
int max = N;
List<Integer> divisors = new ArrayList<>();
if (N == 1) {
divisors.add(1);
} else {
for (int div = 1; div < max; div++) {
if (N % div == 0) {
divisors.add(div);
if (div != N / div) {
divisors.add(N / div);
}
}
if (N / div < max) {
max = N / div;
}
}
}
removed[i] += map.entrySet().stream()
.filter(entry -> divisors.stream().noneMatch(div -> Objects.equals(entry.getKey(), div)))
.mapToLong(e -> e.getValue()).sum();
public func solution(_ A : inout [Int]) -> [Int] {
let n = A.count
var counters = Array(repeating: 0, count: 2 * n + 1)
var divisors = Array(repeating: 0, count: 2 * n + 2)
var nonDivisors = Array(repeating: 0, count: n)
for i in A {
counters[i] += 1
}
for i in 1...2 * n {
if counters[i] > 0 {
var k = i
while k <= 2 * n {
if counters[k] > 0 {
divisors[k] += counters[i]
}
k += i
}
}
}
for i in 0..<n {
nonDivisors[i] = n - divisors[A[i]]
}
return nonDivisors
def get_divisors(n):
froot = int(n**.5)
divs = set()
# reverse through possible divisors which are lower than root(n)
while froot > 0:
if not n%froot:
divs.add(froot)
divs.add(n//froot) # Catch the higher divisor on the other side of froot
froot-=1
return divs
def solution(A):
N = len(A)
int_count = {}
# O(N) scan to count number frequency
for i in range(N):
int_count[A[i]] = int_count.get(A[i], 0) + 1
# Create an array for every i non-divisor count
div_count = {}
for i, freq in int_count.items():
divs = get_divisors(i)
num_divs = 0
for d in divs:
num_divs += int_count.get(d, 0)
div_count[i] = N-num_divs # N - divisors = non-divisors :-)
return [div_count[A[i]] for i in range(N)]