• LeetCode--Majority Element


    Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

    You may assume that the array is non-empty and the majority element always exist in the array.

    题目描述:给出一个size为n的数组,找出其中出现次数最多的元素,且该元素出现次数多于⌊ n/2 ⌋次 。

    题目中还给定假设数组非空且一定存在一个多数元素。

    题目分析:用哈希表为出现过的元素做映射,对应的键值value记录出现的次数,最后遍历哈希表,找出次数最多的元素。

    代码如下:

    public class Solution {
        public int majorityElement(int[] nums) {
            HashMap<Integer, Integer> h = new HashMap<Integer, Integer>();
            for(int i : nums){
                if(!h.containsKey(i)){
                    h.put(i, 1);
                }
                else{
                    h.put(i, h.get(i)+1);
                }
            }
            
            int max = -1;
            int k = -1;
            for(Map.Entry<Integer, Integer> entry: h.entrySet()){
                if(max<entry.getValue()){
                    max = entry.getValue();
                    k = entry.getKey();
                }
            }
            return k;
        }
    }

     解法二:应为数组中多数元素出现的次数至少为⌊ n/2 ⌋ ,则可以有一个巧妙的方法。每次搜索到有不同元素时,则一次将这一对不同元素删除,则最后剩下的必定是出现次数最多的元素。代码如下:

    public class Solution {
        public int majorityElement(int[] nums) {
            int currentnum = 0;
            int count = 0;
            for(int i=0; i<nums.length; i++){
                if(count==0){ //说明至今还未遇到相同元素
                    currentnum = nums[i];
                    count = 1;
                }
                else{
                    if(currentnum==nums[i]) //如果跟当前标记元素相同,则相同个数加1
                        count++;
                    else //如果跟当前标记元素不同,则将一对都删除(前一个元素通过count--删除,后一个元素通过i++删除)
                        count--;
                }
            }
            return currentnum;
        }
    }
  • 相关阅读:
    负载(Load)分析及问题排查
    MySQL 数据库规范--调优篇(终结篇)
    AbstractQueuedSynchronizer
    为什么String被设计为不可变?是否真的不可变?
    数据库 分库 分表 分区
    Oracle 数据库知识汇总篇
    小知识:如何判断数据文件的高水位线
    RHEL7安装11204 RAC的注意事项
    案例:DG主库未设置force logging导致备库坏块
    Oracle 11g RAC之HAIP相关问题总结
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/4514928.html
Copyright © 2020-2023  润新知