제목 설명
어레이의 길이가 N의 모든 숫자는 N-1의 범위에서 0이다. 일부 디지털 배열이 중복되어 있지만 중복 얼마나 많은 숫자 모른다. 각 숫자는 여러 번 반복 알고하지 마십시오. 중복 된 숫자를 하나의 배열을 찾아주세요. 예를 들어, 입력 배열 7 {2,3,1,0,2,5,3}의 길이, 다음 제 2 반복 자릿수 해당 출력.
사고
- 폭력 솔루션은, 트래버스, 진정한 디지털 중복 및 반복 수익을 찾을 수
- 해시 횟수가 2를 초과하면 1 ~ N-1, 확립 될 수 해시 어레이의 개수, 각 번호로 나타날 수를 보유하기 때문에, 중복 설명
- 난 번호 [I], 복제가 반환 할 수 = 알게되면 자기 특성의 사용은, N- 숫자는 n 미만의 수는 I에 상기 번호에 대응하는 위치, 즉, 반환하는 i 번째 디지털 위치를 복원 할 수있다
코드
방법 1 :
class Solution {
public:
// Parameters:
// numbers: an array of integers
// length: the length of array numbers
// duplication: (Output) the duplicated number in the array number
// Return value: true if the input is valid, and there are some duplications in the array number
// otherwise false
bool duplicate(int numbers[], int length, int* duplication) {
if(length < 1)
return false;
for(int i = 0; i < length; i++)
{
for(int j = i+1;j<length;j++)
{
if(numbers[i] == numbers[j]){
*duplication = numbers[i];
return true;
}
}
}
return false;
}
};
방법 2 :
class Solution {
public:
bool duplicate(int numbers[], int length, int* duplication) {
if(length < 1)
return false;
vector<int> Hash(length);
for(int i = 0; i < length;i++)
{
Hash[numbers[i]]++;
}
for(int i = 0; i < length;i++)
{
if(Hash[i]>1)
{
*duplication = i;
return true;
}
}
return false;
}
};
방법 세 가지 :
class Solution {
public:
bool duplicate(int numbers[], int length, int* duplication) {
if(length < 1)
return false;
int index = 0;
while(index < length)
{
if(numbers[index]== index)
{
index ++;
}
else
{
int tmp = numbers[index];
if(tmp == numbers[tmp]) // 出现重复
{
*duplication = tmp;
return true;
}
else //没有重复,则换位置
{
numbers[index] = numbers[tmp];
numbers[tmp] = tmp;
}
}
}
return false;
}
};