[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;
    }
};

本文转自博客园Grandyang的博客,原文链接:求众数[LintCode] Majority Number ,如需转载请自行联系原博主。

相关文章
|
存储 算法
[leetcode/lintcode 题解] 阿里算法面试真题:丑数 II · Ugly Number II
[leetcode/lintcode 题解] 阿里算法面试真题:丑数 II · Ugly Number II
[leetcode/lintcode 题解] 阿里算法面试真题:丑数 II · Ugly Number II
|
Java 数据安全/隐私保护
[LintCode] Number of Islands(岛屿个数)
描述 给一个01矩阵,求不同的岛屿的个数。 0代表海,1代表岛,如果两个1相邻,那么这两个1属于同一个岛。我们只考虑上下左右为相邻。 样例 在矩阵: [ [1, 1, 0, 0, 0], [0, 1, 0, 0, 1], [0, 0, 0, 1, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 1] ] 中有 3 个岛。
1249 0
|
机器学习/深度学习