剑指offer之找出无序数组中出现次数超过一半的数字

本文介绍了三种高效查找数组中出现次数超过一半的元素的方法:排序验证法、使用HashMap计数法及巧妙的抵消法,并提供了Java实现示例。

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

最简单也最容易想到的做法,就是先排序,如果存在的话,中间的数字肯定是要求的数字,

然后再遍历一遍数组进行验证即可。但是这种做法,时间复杂度是O(nlogn)。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;

public class Solution {
  public int MoreThanHalfNum_Solution(int [] array) {
    if(null == array || array.length == 0){
      return 0;
    }
    Arrays.sort(array);
    int result = array[array.length / 2];
    int number = 0;
    for(int i = 0 ;i < array.length; i ++){
      if(array[i] == result){
        number ++;
      }
    }
    return number > array.length/2 ? result: 0;
  }

  public static void main(String[] args){
    int[] array = {1,2,3,2,2,2,5,4,2};
    Solution solution = new Solution();
    System.out.println(solution.MoreThanHalfNum_Solution(array));
  }
}

第二种做法则是利用map。

import java.util.HashMap;

public class Solution {
  public int MoreThanHalfNum_Solution(int [] array) {
    if(null == array || array.length == 0){
      return 0;
    }
    HashMap<Integer,Integer> map = new HashMap<>();
    for(int i = 0;i < array.length;i++){
      Integer temp = map.get(array[i]);
      if(null == temp){
        map.put(array[i],1);
        temp = 1;
      }else{
        temp++;
        map.put(array[i],temp);
      }
      if(temp > array.length/2 ) return array[i];
    }
    return 0;
  }

  public static void main(String[] args){
    int[] array = {1,2,3,2,2,2,5,4,2};
    Solution solution = new Solution();
    System.out.println(solution.MoreThanHalfNum_Solution(array));
  }
}

最后一种做法,比较巧妙的想法,则是利用数组特点,因为要求的数字多于数组的一般,则每遇到一个数字,若和之前相同则加1,若不同则减1,若为0则换一个数字,最后剩下的即为要求的数字。


public class Solution {
  public int MoreThanHalfNum_Solution(int [] array) {
    if(null == array || array.length == 0){
      return 0;
    }
    int result = array[0];
    int times = 1;
    for(int i = 0;i < array.length;i++){
      if(times == 0){
        result = array[i];
      }else if (result == array[i]){
        times++;
      }else{
        times--;
      }
    }
    times = 0;
    for(int i = 0;i<array.length;i++){
      if(array[i] == result){
        times++;
      }
    }
    return times > array.length/2 ? result : 0;
  }

  public static void main(String[] args){
    int[] array = {1,2,3,2,2,2,5,4,2};
    Solution solution = new Solution();
    System.out.println(solution.MoreThanHalfNum_Solution(array));
  }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值