码迷,mamicode.com
首页 > 其他好文 > 详细

the solution of CountNonDivisible by Codility

时间:2015-06-03 23:32:45      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:programming   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

标签:programming   codility   

原文地址:http://blog.csdn.net/chenlei0630/article/details/46352329

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!