算法练习:找出数组大于 n/2 的元素

题目:

  • 给定一个大小为 n 的数组nums ,返回其中的多数元素。多数元素是指在数组中出现次数 大于 n/2 的元素。
  • 你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例:

输入:nums = [3,2,3]
输出:3

实现:

1. main方法

public static void main(String[] args) {
    int[] nums = {2,2,1,1,1,2,2};
    //方式一:
    method1(nums);
    //方式二:
    method2(nums);
    //方式三:摩尔投票法
    method3(nums);
}

2. 方式一:

/**
 * 方式一:排序取中间值即可
 */
private static int method1(int[] nums) {
    // 方式一:排序取中间值即可
    Arrays.sort(nums);
    System.out.println("way1: " + nums[nums.length / 2]);
    return  nums[nums.length / 2];
}

原理:

  • 使用排序,大于n.length/2 的必定在最中间

3. 方式二:

/**
 * 方式二:使用HashMap实现
 */
private static int method2(int[] nums) {
    // 使用HashMap实现
    Map<Integer, Integer> map = new HashMap<>();
    // 遍历数组,将数组中的元素作为key,出现的次数作为value
    for (int num : nums) {
        Integer count = map.get(num);
        if (count == null) {
            count = 0;
        }
        map.put(num, ++count);
        if (count > nums.length / 2) {
            System.out.println("way2: " + num);
            return num;
        }
    }
    // 如果没有找到,返回-1
    return -1;
}

原理:

  • 使用Hashmap实现,key为值,value为次数
  • value大于nums.length / 2就找到并返回

3. 方式三:

/**
     * 摩尔投票法-核心就是对拼消耗
     * 这想法真的是太妙了,而且还是一次遍历就解决了,而且空间复杂度还是O(1)。
     * @param nums
     * @return
     */
 private static int method3(int[] nums) {
     // 摩尔投票法-核心就是对拼消耗
     int count = 0;
     int candidate = 0;
     for (int num : nums) {
         if (count == 0) {
             candidate = num;
         }
         count += (num == candidate) ? 1 : -1;
     }
     System.out.println("way3: " + candidate);
     return candidate;
 }

原理:

  • 使用的是摩尔投票法:核心就是对拼消耗
  • 17
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值