我试图了解在尝试查找数组中的重复键时如何选择数据透视表。我见过的大多数例子总是选择第一个元素作为枢轴,假装这个元素在数组中重复。如果不是这样的话怎么办?如何正确选择枢轴?
假设数组a[lo...hi]
和v分区元素v = a[lo]
。我们还有2个索引gt和lt where
a[lo ... lt]
小于v a[lt ... gt]
等于v a[gt ... hi]
大于v 所以我的想法是从左到右扫描直到我> gt:
(a[i] < v)
:swap(a[i], a[lt]), i++, lt++
(a[i] > v) : swap(a[i], a[gt]); gt--
(a[i] == v): i++
这个想法与quicksort分区非常相似,我想知道在这种情况下如何正确选择枢轴。
答案 0 :(得分:0)
是否选择枢轴重复并不重要。您的算法应该尝试递归地找到重复元素,并且在找到重复键之前它不会停止。
/*
*assume that all element are positive, reutrn -1 when there is no duplicate keys
*/
int duplicate_key(int a[], int lo, int ho) {
if (ho - lo <= 1) return -1; //no duplicate keys when there is no more than 2 keys
a[lo ... lt] are less than v
a[lt ... gt] are equal to v
a[gt ... hi] are greater than v
if (gt - lt > 1) return v;
return max(duplicate_key(a, lo, it), duplicate_key(gt, hi));
}