본문 바로가기
algorithm/Codility

Codility[Lesson 3] - Time Complexity(PermMissingElem)

by 하늘둥둥 2021. 8. 26.

An array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing.

Your goal is to find that missing element.

Write a function:

class Solution { public int solution(int[] A); }

that, given an array A, returns the value of the missing element.

For example, given array A such that:

A[0] = 2 A[1] = 3 A[2] = 1 A[3] = 5

the function should return 4, as it is the missing element.

Write an efficient algorithm for the following assumptions:

N is an integer within the range [0..100,000];the elements of A are all distinct;each element of array A is an integer within the range [1..(N + 1)].

public int solution (int[] A){
	
	// A배열을 오름차운으로 sort 한다
	Arrays.sort(A);
	for(int i=0; i<A.length; i++){
			// sort된 배열에 i번째와 수의 차이는 1로 그 조건값이 일치하지 않으면
			// 비어진 값으로 판단하여 i번쨰 다음값을 리턴한다.
			if(i+1 != A[i]) return i+1
	}

	// for문 도는중에 return을 만나지 못한 경우 마지막수로 판단하여 return 한다.
	return A.length +1;

}

댓글