• 169. Majority Element 出现次数超过n/2的元素


    [抄题]:

    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.

     [暴力解法]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    [思维问题]:

    以为n个元素的出现次数一定也要用n个变量来存。

    [一句话思路]:

    用一个count来存最多次数,节约空间

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    1. 看清要求,最后返回的是major元素,而不是次数

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    用一个count的++--来节约存储空间

    [复杂度]:Time complexity: O(n) Space complexity: O(1)

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    [关键模板化代码]:

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

    229. Majority Element II 数学题,也是醉了

     [代码风格] :

    class Solution {
        public int majorityElement(int[] nums) {
            //ini
            int major = nums[0];
            int count = 1;
            //1 - n
            for (int i = 1; i < nums.length; i++) {
                //nums[i] != major, count--,if count == 0
                if (nums[i] != major) {
                    if (count == 0) {
                        major = nums[i];
                        count++;
                    }
                    count--;
                }else {
                    //nums[i] == major, count++
                    count++;
                }    
            }
            return major;
        }
    }
    View Code
  • 相关阅读:
    SQL Server 循环插入数据
    转:Visual Studio 打开程序提示仅我的代码怎么办
    DevExpress XAF 访问当前视图中选定的对象
    DevExpress安装
    待定位的小bug
    easyui datagrid的toolbar 按钮可以像linkbutton一样设置使能状态
    使用jquery同时设置两个对象的method为同一函数
    首页变黑白的办法
    关于jQueryEasyUI DateBox的基本使用
    好东西分享兼备忘
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8570646.html
Copyright © 2020-2023  润新知