文章标题

来源:互联网 发布:域名交易新闻 编辑:程序博客网 时间:2024/05/01 13:43

给定一个n个整型元素的数组a,其中有一个元素出现次数超过n / 2,求这个元素。据说是百度的一道题

分析
设置一个当前值和当前值的计数器,初始化当前值为数组首元素,计数器值为1,然后从第二个元素开始遍历整个数组,对于每个被遍历到的值a[i]

1 如果a[i]==currentValue,则计数器值加1

2 如果a[i] != currentValue, 则计数器值减1,如果计数器值小于0,则更新当前值为a[i],并将计数器值重置为1

代码:

package test;public class TSort {    public static int sort(int [] a){        int now = a[0];        int count=1;        for(int i =1;i<a.length;i++){            if(a[i]==now)                count++;            else{                count--;                if(count<0)                    now = a[i];                count=1;            }        }        return now;    }    public static void main(String[] args) {        int []a = {1,3,54,1,1,2,1,7,1,9,1,1};        System.out.println(sort(a));    }}
0 0
原创粉丝点击