leetcode:求众数

众数一定是出现次数大于n/2的元素,所以讲数组进行排列后,取中间值,就一定是众数。但是在计算比较大的数组时,时间会超过限制。

代码:

class Solution {
    public int majorityElement(int[] nums) {
        
        int n = nums.length;
        
        for(int i = 0 ;i< n;i++)
        {
            for(int j=0 ;j < n ;j++)
            {
                if(nums[i] > nums[j])
                {
                    int temp = nums[i];
                    nums[i] = nums[j];
                    nums[j] = temp;
                }
            }
        }
        
        return nums[n/2];
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_38261597/article/details/89189395