[코딜리티] countnondivisors

나의 풀이

첫번째 풀이

function solution(A) {
    // write your code in JavaScript (Node.js 8.9.4)
    const answer = new Array(A.length);
    for (let i = 0; i < A.length; i++) {
        let nonDivisorNum = 0;
        for (let j =0 ; j < A.length; j++ ) {
            if (A[i] < A[j]) {
                nonDivisorNum++;
                continue;
            }
            if (A[i] % A[j] !==0){
                nonDivisorNum++;
            }
        }

        answer[i] = nonDivisorNum;
    }

    return answer;
}

두번째 풀이

function solution(A) {
    // write your code in JavaScript (Node.js 8.9.4)
    const numbers = new Array(A.length*2+1).fill(0);
    const answer = new Array(A.length);
    for (const a of A) {
        numbers[a]++;
    }

    for (let i = 0; i < A.length; i++) {
        let divisors = 0;
        for (let num =0 ; num*num <= A[i]; num++ ) {
            if (A[i] % num ===0){
                divisors += numbers[num];

                if (A[i] / num !== num) {
                    divisors += numbers[A[i]/num];
                }
            }
        }

        answer[i] = A.length - divisors;
    }

    return answer;
}

좋은 웹페이지 즐겨찾기