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
  • 相关阅读:
    PHP 5.5.0 Alpha5 发布
    Ubuntu Touch 只是另一个 Android 皮肤?
    MariaDB 10 已经为动态列提供文档说明
    Percona Toolkit 2.1.9 发布,MySQL 管理工具
    Oracle Linux 6.4 发布
    Ruby 2.0.0 首个稳定版本(p0)发布
    Apache Pig 0.11.0 发布,大规模数据分析
    Node.js 0.8.21 稳定版发布
    红薯 MySQL 5.5 和 5.6 默认参数值的差异
    Django 1.5 正式版发布,支持 Python 3
  • 原文地址:https://www.cnblogs.com/carry6/p/11518049.html
Copyright © 2011-2022 走看看