数组中出现次数超过一半的数

来源:互联网 发布:淘宝营业额 编辑:程序博客网 时间:2024/05/16 04:40

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

时间限制:1秒

空间限制:32768k

这道题和腾讯2016研发工程师编程题中的微信红包一致。第一次做的时候,我用了最笨的一个方法,定义一个和该数组一样长的二位数组b[n][2],用b[i][0]存放a[j],然后用b[i][1]存放a[j]出现的次数,若次数大于n/2,则返回。

public int getValue(int[] gifts, int n) {        int a[][] = new int[n][2];        int temp = 0;        int k = 0;        for (int i = 0; i < n; i++) {            for (int j = 0; j < n; j++) {                if (a[j][0] == gifts[i])                    a[j][1]++;                if (a[j][1] >= n / 2) {                    temp = a[j][0];                    break;                }            }            a[i][0] = gifts[i];        }        return temp;    }

在第二次做的时候,参考了别人的思路,得到了比较简单的方法,俗称”打擂算法“。

public int Solution(int[] array) {        int temp = 0;        int count = 0;        for (int i = 0; i < array.length; i++) {            if (array[i] == temp)                count++;            else if (count > 0)                count--;            else {                temp = array[i];                count = 1;            }        }        count = 0;        for (int i = 0; i < array.length; i++)            if (temp == array[i])                count++;        return count > array.length / 2 ? temp : 0;    }

由于是在牛客网上提交的(http://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163?rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)它给出的测试数据中有不存在的情况,所以在最后使用了一次循环进行校验。
还有一种思路是同时去掉数组中两个不同的数字,到最后剩下的数字就是我们需要求的数字。和上面的思路基本一致。 

0 0