Task description
You are given a non-empty zero-indexed array A consisting of N integers. For each number A[i] such that 0 ≤ i < N, we want to count the number of elements of the array that are not the divisors of A[i]. We say that these elements are non-divisors. For example, consider integer N = 5 and array A such that: A[0] = 3 A[1] = 1 A[2] = 2 A[3] = 3 A[4] = 6 For the following elements:
Write a function:
that, given a non-empty zero-indexed array A consisting of N integers, returns a sequence of integers representing the amount of non-divisors. The sequence should be returned as:
For example, given: A[0] = 3 A[1] = 1 A[2] = 2 A[3] = 3 A[4] = 6 the function should return [2, 4, 3, 2, 0], as explained above. Assume that:
Complexity:
Elements of input arrays can be modified. |
1.首先定义一个vector counts来记录A中每个元素出现的次数
2.对任意一个i,计算A中A[i]的因子数。由于我们只需要计算小于或等于sqrt(A[i])的因子便可得出A[i]的所有因子,故外层循环:i,0~N-1
内层循环:j,1~sqrt(A[i])。若A[i] % j = 0则 j 是A[i]的因子,A[i]的因子数+1,若 j 不等于sqrt(A[i]),则A[i] / j 也是A[i]的因子,A[i]的因子数继续 +1。
3.最后,对每个i,res[i]等于N减去A[i]的因子数。
代码:
// you can use includes, for example:
#include
//#include
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
vector
solution(vector
&A) {
// write your code in C++11
int N = A.size();
vector
::iterator max = max_element(A.begin(),A.end()); vector
counts(*max+1,0); for(int i = 0 ; i < N ; ++i) { counts[A[i]]++; } vector
res(N,0); for(int i = 0 ; i < N ; ++i) { 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]; } } } res[i] = N - divisors; } return res; }