| Markdown版本筆記 | 我的GitHub首頁 | 我的博客 | 我的微信 | 我的郵箱 |
|---|---|---|---|---|
| MyAndroidBlogs | baiqiantao | baiqiantao | bqt20094 | baiqiantao@sina.com |
算法 數組中出現次數最多的數字
目錄
數組中出現次數最多的數字
給定一個int數組,找出出現次數最多的數字(出現次數超過數組長度的一半)
方式一:快速排序
先對這個數組進行排序,在已排序的數組中,位於中間位置的數字就是超過數組長度一半的那個數。
public class Test {
public static void main(String[] args) throws Exception {
int[] array = { 1, 1, 1, 1, 5, 1, 5, 1, 5, 5, 5 };
qsort(array);
System.out.println(Arrays.toString(array));
}
public static void qsort(int[] arr) {
qsort(arr, 0, arr.length - 1);
}
public static void qsort(int[] arr, int low, int high) {
if (low < high) {
int pivot = partition(arr, low, high);//將表一分為二
qsort(arr, low, pivot);//對低子表【遞歸】排序
qsort(arr, pivot + 1, high);//遞歸對高子表遞歸排序
}
}
private static int partition(int[] arr, int low, int high) {
int pivotkey = arr[low];//選擇一個【基准元素】,通常選擇第一個元素或者最后一個元素
while (low < high) {//從表的兩端【交替】地向中間掃描
//將比基准元素小的交換到低端
while (low < high && arr[high] >= pivotkey) {
high--;
}
swap(arr, low, high);
//將比基准元素大的交換到高端
while (low < high && arr[low] <= pivotkey) {
low++;
}
swap(arr, low, high);
}
return low;//此時基准元素在其排好序后的正確位置
}
public static void swap(int[] arr, int i, int j) {
if (i == j) return;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
時間復雜度為 O(n*lgN)
空間復雜度為 O(n*lgN)
方式二:兩次循環
第一次循環是為了記錄各個數字出現的次數
第二次循環是為了比較各個數字出現的次數
這種方式沒有利用出現次數超過數組長度的一半這個特殊條件,可以在任何數組中找出出現次數最多的數字。
public class Test {
public static void main(String[] args) throws Exception {
int[] array = { 1, 1, 1, 1, 5, 1, 5, 1, 5, 5, 5 };
System.out.println(mostNum(array));
}
public static int mostNum(int[] array) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < array.length; i++) {
int key = array[i];
if (map.containsKey(key)) {
map.replace(key, map.get(key) + 1);
} else {
map.put(key, 1);
}
}
int key = array[0];
for (Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() > map.get(key)) {
key = entry.getKey();
}
}
return key;
}
}
時間復雜度為O(n)
空間復雜度為O(n)
方式三:一次循環
取巧的做法,僅當出現次數超過數組長度的一半這種條件下才保證正確。
public class Test {
public static void main(String[] args) throws Exception {
int[] array = { 1, 1, 1, 1, 5, 1, 5, 1, 5, 5, 5 };
System.out.println(mostNum(array));
}
public static int mostNum(int[] array) {
int count = 1, value = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] == value) {
count++; //如果下一個數字與之前保存的數字相同,則次數加1
} else {
count--; //如果不同,則次數減1
}
if (count == 0) {
value = array[i]; //如果次數為0,則需要保存下一個數字,並把次數設定為1
count = 1;
}
}
return value;
}
}
時間復雜度為O(n)
空間復雜度為O(1)
2018-12-8
