zoukankan      html  css  js  c++  java
  • 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.

    解法一:

    public class Solution {
        public int majorityElement(int[] num) {
            if(num.length == 1) return num[0];
            
            Arrays.sort(num);           //对num进行排序
            
            return num[num.length/2];   //中间值一定是majorityElement,否则不可能过半
        }
    }

    解法二:

    public class Solution {
        public int majorityElement(int[] num) {
            if(num.length == 1) return num[0];
            
            Arrays.sort(num);                //对数组进行排序
            
            int start = num[0];
            int count = 1;
            for(int i=1; i<num.length; i++){  //遍历数组,求连续相同的元素的个数
                if(start == num[i]){          //如果与start相同,count++
                    count++;
                    if(count > num.length/2) return num[i];
                } else{                       //如果与start不同,从num[i]开始重新统计连续相同的个数
                    start = num[i];
                    count = 1;
                }
            }
            
            return -1;   //查找失败
        }
    }

    解法三:

    public class Solution {
        public int majorityElement(int[] num) {
            if(num.length == 1) return num[0];
            
            Map<Integer, Integer> myMap = new HashMap<Integer, Integer>();
            for(int i=0; i<num.length; i++) {    
                if(myMap.containsKey(num[i])){              //利用HashMap来统计num数组中各个元素出现的个数
                    myMap.put(num[i], myMap.get(num[i])+1);   // Map<num[i], count>
                }else{
                    myMap.put(num[i], 1);
                }
            }
            
            Iterator myIterator = myMap.entrySet().iterator();
            while(myIterator.hasNext()){                      //遍历Map找出count > length/2 的元素
                java.util.Map.Entry myEntry = (java.util.Map.Entry) myIterator.next();
                int count = (int) myEntry.getValue();
                int result = (int) myEntry.getKey();
                if(count > (num.length/2)) return result;
            }
            
            return -1;   //查找失败
        }
    }



  • 相关阅读:
    USACO 5.1 Starry Night
    USACO 4.4 Frame Up
    USACO 4.4 Shuttle Puzzle
    USACO 4.3 Letter Game (字典树)
    USACO 4.3 Street Race
    BZOJ 1036: [ZJOI2008]树的统计Count (树链剖分模板题)
    BZOJ 1861: [Zjoi2006]Book 书架 (splay)
    codeforces 354 D. Transferring Pyramid
    codeforces 286 E. Ladies' Shop (FFT)
    USACO 4.3 Buy Low, Buy Lower
  • 原文地址:https://www.cnblogs.com/dosmile/p/6444453.html
Copyright © 2011-2022 走看看