题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,
超过数组长度的一半,因此输出2。如果不存在则输出0。
思路1:
该思路很好,时间复杂度为O(n)。
如果有符合条件的数字,则它出现的次数比其他所有数字出现的次数和还要多。
1)在遍历数组时保存两个值:一是数组中一个数字temp,一是次数count。遍历下一个数字时,
若它与temp相同,则count++,否则count–;若count=0,则temp为下一个数字,并将count置为1。
若存在符合条件的数,则相当于将其与其他数相抵消,抵消剩下的一定是该数。若不存在,剩下的不一定是该数
所以需要2)步骤验证。
2)遍历结束后,所保存的数字即为所求。然后再判断它是否符合条件即可。
思路2:
该思路容易理解,但最坏时间复杂度O(n^2),显然不如思路1
1)快速排序
2)排序后如果存在该数,则该数一定是中间的数mid=len/2;
3)检查中间数arr[mid]的count是否超过一半
package swordToOffer._28_MoreThanHalfNum;
import java.util.Arrays;
public class Solution {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 2, 2, 2, 5, 4, 2};
Solution s = new Solution();
s.quickSort(arr, 0, arr.length - 1);
System.out.println(Arrays.toString(arr));
}
public int MoreThanHalfNum_Solution(int[] array) {
if(array==null && array.length==0 ){
return 0;
}
int temp=array[0];
int count=1;
for(int i=1;i<array.length;i++){
if(count==0){
temp=array[i];
count=1;
}else{
if(array[i]==temp){
count++;
}else{
count--;
}
}
}
//检查temp是否个数超过一半
count=0;
for(int i:array){
if(i==temp){
count++;
}
}
if(count>array.length/2){
return temp;
}
return 0;
}
public int MoreThanHalfNum_Solution2(int[] array) {
int len = array.length;
if (len == 0) {
return 0;
}
quickSort(array, 0, len - 1);
int mid = len / 2;
//检查中位数是否个数超过一半
int count = 0;
for(int i=0;i<array.length;i++){
if(array[i]==array[mid]){
count++;
}
}
if(count>len/2)
return array[mid];
return 0;
}
/**
* 快速排序
*/
public void quickSort(int[] arr, int left, int right) {
if (left >= right) {
return;
}
int leftNum = left;
int rightNum = right;
int base = arr[leftNum];
//从右往左找比base小的
while (left < right) {
while (right > left && arr[right] >= base) {
right--;
}
//从左往右找比base大的
while (right > left && arr[left] <= base) {
left++;
}
//找到后就交换
swap(arr, right, left);
}
//交换base和arr[left]位置
swap(arr,leftNum,left);
//递归调用
quickSort(arr, leftNum, left - 1);
quickSort(arr, left + 1, rightNum);
}
public void swap(int[] arr, int n, int m) {
int temp = arr[n];
arr[n] = arr[m];
arr[m] = temp;
}
}