[英]Recursive algorithm to establish level of pairs element or to find the master element
[英]Efficient algorithm to find master element in an array?
我試圖找出包含 N 個整數的給定數組 A 是否具有“主元素”。 此數組的主元素是在數組中出現次數超過 n/2 次的元素。
例如:
A={5,1,3,5,5}
有一個主元素(在本例中為 5)。A={5,1,2,3,3}
沒有主元素。以下是我到目前為止的代碼。
我想知道解決這個問題的最有效算法是什么?
如果數組有主元素,算法需要返回true
如果沒有主元素,則返回false
。
boolean masterElement(int[] a) {
int count = 0;
boolean check = false;
for (int i = 0; i < a.length/2; i++) {
for (int j = 0; j < a.length; j++) {
if (a[i] == a[j]) {
count++;
}
}
if (count >= a.length/2) {
check = true;
break;
}
count = 0;
}
return check;
}
在 Java 8 中,你可以像這樣使用Streams
和Collectors
:
int[] a = {5,1,3,5,5};
final int n=a.length;
Map<Integer, List<Integer>> x = Arrays.stream(a).boxed().collect(Collectors.groupingBy(i->i));
// System.out.println(x); // {1=[1], 3=[3], 5=[5, 5, 5]}
x.forEach((k,v)->{
if(v.size()>n/2) System.out.println(k); // Check whether you need > or >=
});
請查看上面代碼中注釋中的解釋。
boolean masterElement(int[] a) {
int half = a.length / 2;
for (int i = 0; i < half; i++) {
int count = 1;
for (int j = i + 1; j < a.length && count <= half; j++) {
if (a[i] == a[j]) {
count++;
}
}
if (count > half) {
return true;
}
}
return false;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.