請(qǐng)?jiān)O(shè)計(jì)一個(gè)高效算法,判斷數(shù)組中是否有重復(fù)值。必須保證額外空間復(fù)雜度為O(1)。
給定一個(gè)int數(shù)組A及它的大小n,請(qǐng)返回它是否有重復(fù)值。
測(cè)試樣例:
輸入:[1,2,3,4,5,5,6],7
返回:true
class Checker {
public:
void swap(vector<int> &A,int i,int j)
{
int temp;
temp=A[i];
A[i]=A[j];
A[j]=temp;
}
// 調(diào)整堆, adjusting_node是當(dāng)前待調(diào)整的節(jié)點(diǎn),last_node是最后一個(gè)節(jié)點(diǎn)
void adjust_haep(vector<int> &A, int adjusting_node, int last_node)
{
int parent = adjusting_node, child = 2 * adjusting_node + 1;
int curr_value = A[adjusting_node];
while(child <= last_node){
if(child < last_node && A[child] < A[child+1]){
++child;
}
if(curr_value < A[child]){
A[parent] = A[child];
parent = child;
child = 2*parent + 1;
}
else{
break;
}
}
A[parent] = curr_value;
}
bool checkDuplicate(vector<int> a, int n) {
// write code here
// 生成堆,從最后節(jié)點(diǎn)的parent開(kāi)始
for(int i=n/2-1; i>=0; --i){
adjust_haep(a, i, n-1);
}
// 每次A[0]和最后的節(jié)點(diǎn)交換,然后調(diào)整堆
for(int i=n-1; i>0; --i){
swap(a, i, 0);
adjust_haep(a, 0, i-1);
if(i<n-1 && a[i] == a[i+1]){
return true;
}
}
return false;
}
};