思路1:创建一个数组,将原数组元素当做下标统计次数
int findRepeatNumber(int* nums, int numsSize){
int nums_harsh[numsSize];
/*init nums_harsh*/
for(int i = 0;i < numsSize;i++)
{
nums_harsh[i] = 0;
}
/*count times*/
for(int i = 0;i < numsSize;i++)
{
nums_harsh[nums[i]]++;
/*find*/
if(nums_harsh[nums[i]] == 2)
{
return nums[i];
}
}
/*no such element*/
return -1;
}
思路2:排序,邻居比较
LeetCode上,这个算法无法通过,主要时间复杂度太高
只允许O(n)
/*快排*/
void quickSort(int* nums,int start,int end);
int findRepeatNumber(int* nums, int numsSize){
quickSort(nums,0,numsSize-1);
for(int i = 0;i < numsSize;i++)
{
if(nums[i] == nums[i+1])
{
return nums[i];
}
}
return -1;
}
void quickSort(int* nums,int start,int end)
{
if(start >= end)
return;
int pivot = nums[start];//枢轴
int left = start;
int right = end;
while(left < right)
{
while(pivot <= nums[right] && left < right)
{
right--;
}
nums[left] = nums[right];
while(pivot >= nums[left] && left < right)
{
left++;
}
nums[right] = nums[left];
}
nums[left] = pivot;
quickSort(nums,start,left-1);
quickSort(nums,left+1,end);
}
思路3:对应更换,书中给定的思路
1.将tem元素归位nums[tem]
2.已归位的元素不会被打扰
3.n个元素至多归位n次
int findRepeatNumber(int* nums, int numsSize){
for(int i = 0;i < numsSize;i++)
{
while(nums[i] != i)
{
if(nums[i] == nums[nums[i]])
return nums[i];
else
{
/*交换*/
int tem;
tem = nums[i];
nums[i] = nums[nums[i]];
nums[tem] = tem;
}
}
}
return -1;
}