• 【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));
    
        }
    
    }

  • 相关阅读:
    python中列表,元组,字典常用操作方法的总结
    python中字符串常用方法总结
    tomcat运行报错Failed to start component [StandardEngine[Catalina].StandardHost[localhost].XXXX
    在Linux Ubuntu16.04中如何修改文件名
    【蓝桥杯训练】第五天1369
    【python3】raise,assert,nonlocal 关键字解读
    【python3】yield 关键字解读
    【蓝桥杯训练】第四天1294、1297
    【蓝桥杯训练】第四天1291、1293
    【蓝桥杯训练】第四天1285、1290
  • 原文地址:https://www.cnblogs.com/cutter-point/p/11119411.html
Copyright © 2020-2023  润新知