[編程題]數組中重複的數字
時間限制:1秒 空間限制:32768K
題目描述
在一個長度爲n的數組裏的所有數字都在0到n-1的範圍內。 數組中某些數字是重複的,但不知道有幾個數字是重複的。也不知道每個數字重複幾次。請找出數組中任意一個重複的數字。 例如,如果輸入長度爲7的數組{2,3,1,0,2,5,3},那麼對應的輸出是第一個重複的數字2。
解題思路
- 找到任意重複的一個值並賦值到duplication[0]
- 函數返回True/False
- 不是返回任一重複的一個值,而是返回數組中第一個出現的重複的值
思路1
用字典(鍵值對)。因爲Python對字典的key的存儲方式爲哈希表,對應Java中的HashMap,其查找速度爲常數時間O(1)。但以空間換時間,字典需要開闢額外的存儲空間,具有較高的空間複雜度。
def duplicate(self, numbers, duplication):
dict = {}
for num in numbers:
if num not in dict:
dict[num] = 0
else:
duplication[0] = num
return True
return False1
思路2
不需要額外的數組保存,利用題目中說“數組裏數字的範圍在0 ~ n-1 之間”,所以可以利用現有數組設置標誌,當一個數字被訪問過後,可以設置對應位上的數 + n,之後再遇到相同的數時,會發現對應位上的數已經大於等於n了,那麼直接返回這個數即可。
Python
def duplicate(self, numbers, duplication):
long = len(numbers)
for i in range(len(numbers)):
index = numbers[i]%long if numbers[i] >= long else numbers[i]
if numbers[index] > long:
duplication[0] = index
return True
numbers[index] += long
return False
C++
class Solution {
public:
bool duplicate(int nums[], int len, int* duplication)
{
if(nums == NULL || len <= 1)
return false;
int tmp;
int j = 0;
for(j = 0; j< len;)
{
tmp = nums[j];
if(tmp != j)
{
if(tmp == nums[tmp])
{
*duplication = tmp;
return true;
}
nums[j] = nums[tmp];
nums[tmp] = tmp;
}
if(nums[j] == j)
++j;
}
return 0;
}
};