169. Majority Element

来源:互联网 发布:魅族note6网络频段 编辑:程序博客网 时间:2024/05/18 17:39

Given an array of size n, findthe majority element. The majority element is the element that appears morethann/2 times.

You may assume that the arrayis non-empty and the majority element always exist in the array.

    翻译:给定一个大小为n的数组,找到多数元素。多数元素是出现超过n / 2倍的元素。您可以假定数组非空,并且多数元素始终存在于数组中。

    第一想法是排序取nums.length的一半,但是总是超时,用冒泡和快速排序。最后用了常规的遍历,写完后,看了下别人的,发现直接用Arrays的静态方法排序成功了,看了一下,它是用“经过调优的快速排序法”,代码如下:

public intmajorityElement(int[] nums) {

       /* int max=nums[0];

        int count=1;

        for(int i=1;i<nums.length;i++){

            if(count==0){

                max=nums[i];

                count++;

            }else{

                if(count>nums.length/2)break;

                if(nums[i]==max){

                    count++;

                }else{

                    count--;

                }

               

            }

        }

        return max;*/

         Arrays.sort(nums);

        return nums[nums.length/2];

       

    }

0 0