zoukankan      html  css  js  c++  java
  • 数组:数组中出现次数超过一半的数字

    题目描述

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

    思路分析

     三种解法:

    法1:使用HashMap存储,key是数组值,value是出现次数,全部存入后再for循环比较value*2是否大于length; 

    法2:排序。数组排序后,如果某个数字出现次数超过数组的长度的一半,则一定会数组中间的位置。所以我们取出排序后中间位置的数,统计一下它的出现次数是否           大于数组长度的一半;

    参考代码

    法1:运行时间:19ms  占用内存:9416k

     1 import java.util.HashMap;
     2 import java.util.Map;
     3 public class Solution {
     4     public int MoreThanHalfNum_Solution(int [] array) {
     5         HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
     6         int length = array.length;
     7         for(int i = 0; i < length; i++) {
     8             if(!map.containsKey(array[i])) {
     9                 map.put(array[i], 1);
    10             } else {
    11                 map.put(array[i], map.get(array[i]) + 1);
    12             }
    13         }
    14         for(Map.Entry<Integer, Integer> m : map.entrySet()) {
    15             if(m.getValue() * 2 > length) {
    16                 return m.getKey();
    17             }
    18         }
    19         return 0;
    20     }
    21 }
    View Code

    法2:运行时间:15ms  占用内存:9336k

     1 import java.util.Arrays;
     2 public class Solution {
     3     public int MoreThanHalfNum_Solution(int [] array) {
     4         Arrays.sort(array);
     5         int half = array.length / 2;
     6         int count = 0;
     7         for(int i = 0; i < array.length; i++) {
     8             if(array[i] == array[half]) {
     9                 count++;
    10             }
    11         }
    12         if(count > half) {
    13             return array[half];
    14         } else {
    15             return 0;
    16         }
    17     }
    18 }
    View Code
  • 相关阅读:
    谷歌 colab调用 Kaggle 数据集
    TensorFlow/Keras binary_crossentropy损失函数
    R语言 pivot_longer 图表变换
    R语言 ggplot2 柱状图
    R语言 ggplot2 笔记
    Bash 批量删除指定后缀的文件
    MacBook 风扇控制软件 Macs Fan Control
    R语言 dplyr selec 辅助函数
    R语言一次性更新全部packages
    R语言 glue 版本冲突
  • 原文地址:https://www.cnblogs.com/carry6/p/11518049.html
Copyright © 2011-2022 走看看