zoukankan      html  css  js  c++  java
  • 169. Majority Element

    原题链接:https://leetcode.com/problems/majority-element/description/
    这道题目之前《剑指Offer》见到过,这次就直接能想起书上写的第二种较为简单的方法了:

    /**
     * Created by clearbug on 2018/2/26.
     */
    public class Solution {
    
        public static void main(String[] args) {
            Solution s = new Solution();
            System.out.println(s.majorityElement(new int[]{1, 2, 2, 3, 2, 5}));
            System.out.println(s.majorityElement(new int[]{1, 2, 2, 3, 2, 5, 8, 8, 8, 7, 6, 5, 8}));
        }
    
        public int majorityElement(int[] nums) {
            int times = 1;
            int temp = nums[0];
            for (int i = 1; i < nums.length; i++) {
                if (nums[i] == temp) {
                    times++;
                } else {
                    if (times > 0) {
                        times--;
                    } else {
                        temp = nums[i];
                        times = 1;
                    }
                }
            }
    
            return temp;
        }
    }
    

    第一种方法,就是利用快速排序的思想来解决啦!

    官方答案

    1. 双层循环暴力法
    2. HashMap优化省去一层循环
    3. 先排序,后用中间索引位置
    4. 随机数猜测法,感觉这个方法比较符合某些人的大脑思路
    5. 就是上面说的那种实现了

    参考

    http://www.cnblogs.com/optor/p/8568645.html

  • 相关阅读:
    2020-08-20
    2020-08-19
    2020-08-14
    2020-08-13
    使用numpy实现机器学习模型
    分治法学习
    2020-08-09
    2020-08-02
    四月是你的谎言下载
    新博客
  • 原文地址:https://www.cnblogs.com/optor/p/8618905.html
Copyright © 2011-2022 走看看