[Codility]PermCheck
배움/AlgorithmA non-empty array A consisting of N integers is given.
A permutation is a sequence containing each element from 1 to N once, and only once.
For example, array A such that:
A[0] = 4 A[1] = 1 A[2] = 3 A[3] = 2
is a permutation, but array A such that:
A[0] = 4 A[1] = 1 A[2] = 3
is not a permutation, because value 2 is missing.
The goal is to check whether array A is a permutation.
Write a function:
class Solution { public int solution(int[] A); }
that, given an array A, returns 1 if array A is a permutation and 0 if it is not.
For example, given array A such that:
A[0] = 4 A[1] = 1 A[2] = 3 A[3] = 2
the function should return 1.
Given array A such that:
A[0] = 4 A[1] = 1 A[2] = 3
the function should return 0.
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..1,000,000,000].
- 배열의 수가 순열이면 1 아니면 0을 리턴
1. 첫번째 시도
트리셋에 넣어서 순차 정렬 한 후 찾아내려고 함...
테스트 케이스 빼고 다 실패....ㅠㅠ
// you can also use imports, for example:
import java.util.*;
// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");
class Solution {
public int solution(int[] A) {
// write your code in Java SE 8
TreeSet<Integer> treeSet = new TreeSet<Integer>();
int returnValue = 0;
for(int i:A){
treeSet.add(i);
}
int num = treeSet.first();
while(treeSet.contains(num)){
if(num == treeSet.last()){
returnValue = 1;
break;
}
num++;
}
return returnValue;
}
}

2. 두번째 시도
// you can also use imports, for example:
import java.util.*;
// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");
class Solution {
public int solution(int[] A) {
// write your code in Java SE 8
// TreeSet<Integer> treeSet = new TreeSet<Integer>();
int returnValue = 0;
int[] sortA = new int[A.length];
Arrays.sort(A);
int minValue = A[0];
for(int i=0 ; i<A.length ; i++){
if(A[i] == minValue){
returnValue = 1;
}else{
returnValue = 0;
break;
}
minValue ++;
}
return returnValue;
}
}

단일 값에 대한 처리 및 시작값이 1이 아닌값에 대한 처리가 부족!
3. 최종버전
// you can also use imports, for example:
import java.util.*;
// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");
class Solution {
public int solution(int[] A) {
// write your code in Java SE 8
// TreeSet<Integer> treeSet = new TreeSet<Integer>();
Arrays.sort(A);
int minValue = 1;
for(int i=0 ; i<A.length ; i++){
if(A[i] != minValue){
return 0;
}
minValue ++;
}
return 1;
}
}

'배움 > Algorithm' 카테고리의 다른 글
| [Codility]CountDiv (0) | 2021.06.16 |
|---|---|
| [Codility]MissingInteger (0) | 2021.06.15 |
| [프로그래머스]가장 큰 수 (0) | 2021.03.23 |
| [프로그래머스]전화번호목록 (0) | 2021.03.22 |
| [프로그래머스]완주하지 못한 선수 (0) | 2021.03.21 |