zoukankan      html  css  js  c++  java
  • 【LEETCODE】35、169题, Majority Element

    package y2019.Algorithm.array;
    
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * @ProjectName: cutter-point
     * @Package: y2019.Algorithm.array
     * @ClassName: MajorityElement
     * @Author: xiaof
     * @Description: 169. 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.
     *
     * Input: [3,2,3]
     * Output: 3
     *
     * 获取重复数据达到n/2的数据
     *
     * @Date: 2019/7/2 10:50
     * @Version: 1.0
     */
    public class MajorityElement {
    
        //自己的解法,效率极底。。。
        public int solution(int[] nums) {
            //我们考虑用hash的原理做
            Map<Integer, Integer> map = new HashMap();
            for(int i = 0; i < nums.length; ++i) {
                if(map.containsKey(nums[i])) {
                    map.put(nums[i], map.get(nums[i]) + 1);
                } else {
                    map.put(nums[i], 1);
                }
            }
            //取出出现次数最大的
            Integer result = null;
            int maxTimes = 0;
            for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
                if(entry.getValue() > maxTimes) {
                    maxTimes = entry.getValue();
                    result = entry.getKey();
                }
            }
    
            return result;
        }
    
    
        //我们换个思路,这题majority element always exist in the array. 必定存在这个元素
        //那么我们只要求出最大出现次数的元素,那么就一定满足要求
        public int solution2(int[] nums) {
    
            int count = 1;
            int result = nums[0];
    
            for(int i = 1; i < nums.length; ++i) {
                if(count == 0) {
                    //当前元素出现次数以及衰减完毕
                    result = nums[i]; //换新元素
                    count++;
                } else if (nums[i] == result) {
                    //如果重复出现
                    count++;
                } else {
                    count--;
                }
            }
    
            return result;
        }
    
        public static void main(String args[]) {
    
            int pres[] = {2,2,1,1,1,2,2,1,1};
            System.out.println(new MajorityElement().solution2(pres));
    
        }
    
    }

  • 相关阅读:
    「APIO2017」商旅
    【CQOI2017】小Q的表格
    【HNOI2016】树
    【NOI2018模拟】Yja
    测试
    Loj #6073.「2017 山东一轮集训 Day5」距离
    「AHOI / HNOI2017」影魔
    Loj 6068. 「2017 山东一轮集训 Day4」棋盘
    【SDOI2014】向量集
    远程服务器安装nginx
  • 原文地址:https://www.cnblogs.com/cutter-point/p/11119411.html
Copyright © 2011-2022 走看看