알고리즘/[ Codility ]

[ Codility ][Lesson4][Medium] MissingInteger

kim.svadoz 2021. 11. 12. 16:51
728x90
반응형

https://app.codility.com/programmers/lessons/4-counting_elements/missing_integer/

 

MissingInteger coding task - Learn to Code - Codility

Find the smallest positive integer that does not occur in a given sequence.

app.codility.com

문제

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].

접근

차례대로 등장하지 않은 가장 작은 양의 정수를 구하는 문제로,

처음 시도는 정렬을 한 후에 음수가 끝나는 시점을 idx로 잡고 풀어나갔는데, 어디선가 틀렸다는 메세지가 나왔고

문제를 다시 보니 Set으로 쉽게 풀 수 있을 것 같았다.

코드

/**
 * Codility Lesson4 Medium
 * 자료구조, 구현
 */
public class L4_Medium_MissingInteger {
    class Solution {
        public int solution(int[] A) {
            Set<Integer> set = new HashSet<>();
            for (int i : A) {
                set.add(i);
            }
            for (int i = 1; i < Integer.MAX_VALUE; i++) {
                if (!set.contains(i)) {
                    return i;
                }
            }
            return -1;
        }
    }
}
728x90
반응형

'알고리즘 > [ Codility ]' 카테고리의 다른 글

[ Codility ][Lesson10][Medium] Flags  (0) 2021.11.09