剑指Offer 面试题39. 数组中出现次数超过一半的数字(Java代码)

https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof/

题目描述

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。

输入输出样例

输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2

题解

这道题目有几种解法,比较灵活。

数组问题

  • 可以想到使用HashMap对数组中元素进行计数
  • 或者将数组进行排序,出现在中间的元素一定是排序出现最多次数的数字(但是这个还需要最后验证一些数组中该数字是否出现了这么多次数)

比较难想到的解法,摩尔投票机制。

HashMap计数:

import java.util.*;
public class Solution {
    public int MoreThanHalfNum_Solution(int [] array) {        
        // 1. 使用HashMap解题
        int halfLen = array.length / 2;
        // 需要将数字和对应的出现的次数存入map中
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int num : array){
            int count = map.getOrDefault(num, 0) + 1;
            map.put(num, count);
            if(count > halfLen ) return num;
        }
        
        return 0;
    }
}

使用快速排序:

import java.util.*;
public class Solution {
    public int MoreThanHalfNum_Solution(int [] array) {     
        // 2. 将数组排序,然后解题(使用快速排序)
    	quickSort(array, 0, array.length-1);
        int ret = array[array.length/2];
        
        int count = 0;
        for(int num:array){
            if(ret == num) count++;
        }
        
        return (count > array.length/2) ? ret : 0;
    }
    private Random random = new Random(System.currentTimeMillis());
    public void quickSort(int[] array, int left, int right){
        if(left >= right) return;
        int randomIndex = random.nextInt(right-left) + left + 1;
        swap(array, left, randomIndex);    // 交换值
        int 
            l = left,
            r = right,
            pivot = array[l];    // 基准点
        while(l<r){
            while(l<r && array[r] >= pivot) r--;    // 右边元素都是大于pivot的
            array[l] = array[r]; 
            while(l<r && array[l] <= pivot) l++;
            array[r] = array[l]; 
        }
        array[l] = pivot;
        
        quickSort(array, left, l-1);
        quickSort(array, l+1, right);
    }
    
    public void swap(int[] array, int index1, int index2){
        int temp = array[index1];
        array[index1] = array[index2];
        array[index2] = temp;
    }
}

摩尔投票机制:
由于该数字出现的次数大于数组长度的一半,所以

import java.util.*;
public class Solution {
    public int MoreThanHalfNum_Solution(int [] array) {
        // 3. 使用摩尔投票法
        int votes = 0;
        int x = 0;
        for(int num:array){
            if(votes == 0) x = num;
            votes += (num == x) ? 1 : -1;
        }
        
        int count = 0;
        for(int num:array){
            if(x == num) count++;
        }
        
        return (count > array.length/2) ? x : 0;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值