LeetCode Majority Element JAVA

本文介绍了如何通过排序数组来解决多数元素问题,即找出数组中出现次数超过一半的元素。这种方法简洁高效,只需两句话即可实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

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

开始采用的比较笨的办法,就是遍历数组,从第一个开始,计算这个值出现的所有次数,再计算第二个值出现的次数,取两个之中较大的一个数:

在idea跑了一下好像都可以通过,但是提交答案的时候好像超时了。。。。算法如下:

public class Solution {
    public int majorityElement(int[] nums) {
        int numtemp = 0;
        if(nums.length == 1){
            return nums[0];
        }
        for(int i = 0; i <nums.length-1; i++){
            int temp1 = nums[i];
            int num1 = 0;
            int temp2 = nums[i+1];
            int num2 = 0;
            for(int j =0; j < nums.length;j++){
                if(temp1 == nums[j]){
                    num1++;
                }
            }
            for(int j =0; j < nums.length;j++){
                if(temp2 == nums[j]){
                    num2++;
                }
            }
           numtemp = num1 > num2 ? temp1 : temp2; 
        }
        return numtemp;
    }
}

 后来仔细一想这个题目,这不是脑筋急转弯吗???这个数出现的次数超过数组总长度的一半,那么,我把这个数组直接排序一下,取他的中间值不就是我们要的那个数字了么。尼玛!!!两句话搞定!!!

public class Solution {
    public int majorityElement(int[] nums) {
       Arrays.sort(nums);
        return nums[nums.length/2];
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值