the solution of CountNonDivisible by Codility
Posted jhcelue
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了the solution of CountNonDivisible by Codility相关的知识,希望对你有一定的参考价值。
question:https://codility.com/programmers/lessons/9
To solve this question , I get each element‘s divsors which appearing in input Array A using Sieve of Eratosthenes method. Time complexity is O(nlogn);
Then we iterate array A to get the ith non-divsors by A.size() - count(element) for element in divsor[A[i]] in divsors. Time complexity is O(n*?
); ?
represent the average of divsors
this method unsatisfy the time requirement , for two test case get TIMEOUT error. NEED IMPROVE IT LATER.
code:
#include <algorithm> #include <map> //this method not fast enough vector<int> solution(vector<int> &A) { // write your code in C++11 map<int,int> dic; map<int,vector<int> > divsors; int size = A.size(); int max = *max_element(A.begin(),A.end()); for(int i=0; i<size; i++){ dic[A[i]]++; if(divsors.count(A[i])==0){ vector<int> vec(1,1); divsors.insert(make_pair(A[i],vec)); } } for(int i=2; i<= max; i++){ int element = i; while(element <=max){ if(divsors.count(element)!=0 && find(divsors[element].begin(),divsors[element].end(),i)==divsors[element].end()){ divsors[element].push_back(i); } element+=i; } } vector<int > res; for(int i=0; i<size; i++){ vector<int> t = divsors[A[i]]; int cnt = size; for(int j=0; j<t.size(); j++){ cnt -= dic[t[j]]; } res.push_back(cnt); } return res; }
以上是关于the solution of CountNonDivisible by Codility的主要内容,如果未能解决你的问题,请参考以下文章
Lintcode372 Delete Node in the Middle of Singly Linked List solution 题解
[Mathematics][MIT 18.03] Proof of a Theory about the Solution to Second-order Linear Homogeneous Dif
BZOJ 3546: [ONTAK2010]Life of the Party