런타임 스페이스 다 효율적으로 사용하래서 둘다 O(n)으로 했는데...
더 효율적으로 할 수 있는지... ;ㅅ;
/*
* It is known that the input vector a contains
* only numbers between 1 and a.length-1 (both ends inclusive).
* Find a number that occurs at least twice.
* Examples:
* A=[1,1,2,3] gives 1
* A=[2,2,3,4,3] gives 2 or 3, either one is acceptable
* A=[3,3,3,1] gives 3
* A=[0,1,2,3] will not occur
* The function is not allowed to modify A.
*/
public int findTwins(int[] a) {
int arr[] = new int[a.length]; // 복제배열 생성
for(int i = 0; i < a.length; i++)
{
arr[a[i]]++; // 복제 배열의 해당 원소 카운트
}
for(int j = 0; j < arr.length; j++)
{
if(arr[j] >= 2) // 카운트해서 2 이상인거 출력
return j;
}
return 0;
///////////////////////////////////////////////////////////////
// run-time : O(n)
// space : O(n)
///////////////////////////////////////////////////////////////
}
더 효율적으로 할 수 있는지... ;ㅅ;
/*
* It is known that the input vector a contains
* only numbers between 1 and a.length-1 (both ends inclusive).
* Find a number that occurs at least twice.
* Examples:
* A=[1,1,2,3] gives 1
* A=[2,2,3,4,3] gives 2 or 3, either one is acceptable
* A=[3,3,3,1] gives 3
* A=[0,1,2,3] will not occur
* The function is not allowed to modify A.
*/
public int findTwins(int[] a) {
int arr[] = new int[a.length]; // 복제배열 생성
for(int i = 0; i < a.length; i++)
{
arr[a[i]]++; // 복제 배열의 해당 원소 카운트
}
for(int j = 0; j < arr.length; j++)
{
if(arr[j] >= 2) // 카운트해서 2 이상인거 출력
return j;
}
return 0;
///////////////////////////////////////////////////////////////
// run-time : O(n)
// space : O(n)
///////////////////////////////////////////////////////////////
}
스몰토크횽은 집합으로 알아서 다 해주신다
이 방식은 전혀 쓸모가 없습니당. 왜냐하면 length가 무수히 크다면 그 경우에는 별 효용가치가 없군요
만약 내보고 해결 하라고 하면 다음과 같이 함
1. 배열을 정렬 시킴 2. 0번부터 n-1번까지 검색을 하면서 i번째와 i+1번쨰가 같다면 중복으로 판별
시간 복잡도는 배열의 정렬 시키는 것에 비례
단 배열이 무수히 크다고 했을 때 재귀로 구현을 한다면 정렬이 안 될 수도 있으므로 알아서 처리
근데 런타임이 중요한 경우라면 내가 한거처럼 O(n)으로 하고 스페이스를 O(n)쓰는건 불필요한가... 정렬은 아무리 빨라봤자 O(nlogn)이니.. 하긴 그건 스페이스는 덜 차지하지만..
\"덜\"이 아니라 \"안\"
만약 length가 무수히 크다면 런타임에서도 O(n)이랑 O(nlogn)도 차이가 많이 나지 않나연
정렬도 radix sort 나 bucket sort 하면 O(n) 됨 근데 글쓴이 답도 머리 꽤나 굴린 답인듯 굳ㅋ
programming pearls에 나오는 방식이네요.. 일반적인 경우에 그렇게 효율적이지는 않아요
그래도 어떤 경우에는 꽤 좋은 방법이겠네요