剑指offer——数组中出现次数超过一半的数字_(待写最优法分治)

来源:互联网 发布:云计算培训视频 编辑:程序博客网 时间:2024/05/16 14:09

题目描述

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。



思路1:基于快排(Arrays.sort)时间复杂度 nlogn,不要使用这种。

import java.util.Arrays;public class Solution {    public int MoreThanHalfNum_Solution(int [] array) {        Arrays.sort(array);        int mid = array.length/2;        int count =0;        for(int i=0;i<array.length;i++){        if(array[mid]==array[i])count++;        if(count>mid)return array[mid];        }        return 0;    }}


思路2:

打擂算法:

public class Solution {    public int MoreThanHalfNum_Solution(int [] array) {           int c=0;       int testnum=array[0];       // 找出相同个数最多的那个数       for(int i=0;i<array.length;i++){       if(c==0||testnum==array[i]){       testnum =array[i];       c++;       }       else {c--;       }       }//for              c=0;       //计算有多少相同的       for(int i=0;i<array.length;i++){       if(testnum==array[i])c++;       }       if(c>array.length/2)       return testnum;       return 0;    }}



思路3:分治法

阅读全文
0 0