codility demo test

ref => https://app.codility.com/c/run/demoPXTZHE-W26

This is a demo task.
Write a function:
class Solution { public int solution(int[] A); }
that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.
For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
Given A = [1, 2, 3], the function should return 4.
Given A = [−1, −3], the function should return 1.
Write an efficient algorithm for the following assumptions:
  • N is an integer within the range [1..100,000];
  • each element of array A is an integer within the range [−1,000,000..1,000,000].



function solution(A) {
    // write your code in JavaScript (Node.js 8.9.4)
    const greate0Ar = findGreater0(A).sort((a, b) => a - b);
    const N = findSlotOne(greate0Ar) - 1;
    return N;
}

function findGreater0(A) {

    const filterRepeat = [... new Set(A)]
 const filterGreaterThan0 = filterRepeat.filter(N => N > 0)
    return (filterGreaterThan0.length > 0)? filterGreaterThan0: [0];
}

function findSlotOne(A) {

    let i = 0;
  let map = new Map()
  A.forEach((N) => { map.set(N,N) })
    let N = map.size > 0? true: undefined;
    while( i < 1000000 && N !== undefined ) {
        i += 1;
        N = map.get(i);
console.log(i,N)
    }
    return i + 1;
}

solution([3,2,1])
hin在 cases test 裡面放入 想要測試的 A 值
[1,3,6,4,1,2]
[1,2,3]
[3,2,1]
[]
[-9999999,0]
[1,9999999]
[0]
[1,3,4]

留言