一:題目
給定含有n個元素的多重集合s,每個元素在s中出現的次數稱爲該元素的重數,多重集s中重數最大的元素稱爲衆數,給定多重集合s,求s中的衆數集重數。
二:思路
首先,我們最容易想到的就是統計每個數的出現次數,然後比較得出結果。這個思路可以利用容器來實現。
仔細思考,這道題目還可以用分治法來解決。
解決步驟:
①給數組排序;
②找出中位數v並且確定中位數的個數num和左右邊界;
③如果左邊界左邊數字的個數比num大,說明衆數可能在左邊,重複②之後的步驟;
④如果右邊界右邊數字的個數比num大,說明衆數可能在右邊,重複②之後的步驟;
⑤得出衆數v和重數num。
三:代碼
public class solution {
public static final int maxn = 10000;
public static int[] a = new int[maxn];
public static int num, v;
public static void main(String[] args) {
Scanner cin = new Scanner(new BufferedInputStream(System.in));
System.out.println("請輸入數組長度(<=10000):");
int n = cin.nextInt();
Random rand = new Random();
for (int i = 0; i < n; i++) {
a[i] = (rand.nextInt(100) + 1) % 20;
}
Arrays.sort(a, 0, n);
for(int i = 0; i < n; i++) {
System.out.println(a[i]);
}
solve(0, n - 1);
System.out.println("Value:" + v);
System.out.println("Number:" + num);
}
public static void solve(int l, int r) {
if (l > r)
return;
int mid = (l + r) / 2;
int i = mid, j = mid;
while (i >= 0 && a[i] == a[mid])
i--;
while (a[j] == a[mid] && j <= a.length - 1)
j++;
if (j - i - 1 > num) {
num = j - i - 1;
v = a[mid];
}
if (i - l + 1 > num) {
solve(l, i);
}
if (r - j + 1 > num) {
solve(j, r);
}
}
}