zoukankan      html  css  js  c++  java
  • 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.

    本题的解法是假设数组中一定存在这样的绝对众数。如果没有这样的假设,这种做法只能算是求出候选值,需要再次遍历,计算该数在数组中出现的次数,得出是不是绝对众数的结论。

    class Solution {
    public:
        int majorityElement(vector<int>& nums) {
            int count = 0;
            int m = nums[0];
            for (size_t i = 0; i < nums.size(); i++) {
                if (count == 0) {
                    m = nums[i];
                    count = 1;
                } else if (nums[i] != m) {
                    count--;
                } else {
                    count++;
                }
            }
            return m;
        }
    };
  • 相关阅读:
    测试的种类
    软件测试的原则
    软件测试的目的
    软件测试的对象
    软件的分类
    软件测试
    mysql 视图
    mysql 字段添加以及删除
    mysql 引擎类型
    mysql 数据插入insert
  • 原文地址:https://www.cnblogs.com/wxquare/p/5941254.html
Copyright © 2011-2022 走看看