zoukankan      html  css  js  c++  java
  • [LintCode] Majority Number 求大多数

    Given an array of integers, the majority number is the number that occurs more than half of the size of the array. Find it.

    Notice

    You may assume that the array is non-empty and the majority number always exist in the array.

     
    Example

    Given [1, 1, 1, 1, 2, 2, 2], return 1

    Challenge

    O(n) time and O(1) extra space

    LeetCode上的原题,请参见我之前的博客Majority Element

    解法一:

    class Solution {
    public:
        /**
         * @param nums: A list of integers
         * @return: The majority number
         */
        int majorityNumber(vector<int> nums) {
            int res = 0, cnt = 0;
            for (int num : nums) {
                if (cnt == 0) {res = num; ++cnt;}
                else (num == res) ? ++cnt : --cnt;
            }
            return res;
        }
    };

    解法二:

    class Solution {
    public:
        /**
         * @param nums: A list of integers
         * @return: The majority number
         */
        int majorityNumber(vector<int> nums) {
            int res = 0;
            for (int i = 0; i < 32; ++i) {
                int ones = 0, zeros = 0;
                for (int num : nums) {
                    if ((num & (1 << i)) != 0) ++ones;
                    else ++zeros;
                }
                if (ones > zeros) res |= (1 << i);
            }
            return res;
        }
    };
  • 相关阅读:
    ABP理论学习之Swagger UI集成
    最佳加法表达式
    洛谷 P1736 创意吃鱼法
    洛谷P1387 最大正方形
    1078 最小生成树
    判断元素是否存在
    1531 山峰 【栈的应用】
    洛谷 P2335 [SDOI2005]位图
    矿藏估价
    二分法小结
  • 原文地址:https://www.cnblogs.com/grandyang/p/6068963.html
Copyright © 2011-2022 走看看