zoukankan      html  css  js  c++  java
  • Majority Element,Majority Element II

    一: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 numsSize = nums.size();
            int times = 0;
            int res = 0;
            for(int i=0;i<nums.size();i++){
                if(i==0){
                    res = nums[i];
                    times = 1;
                }else{
                    if(nums[i]!=res){
                        times--;
                        if(times==0){
                            res = nums[i];
                            times = 1;
                        }
                    }else{
                        times++;
                    }
                }
            }
            return res;
        }
    };

     二:Majority Element II

    Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

    出现 ⌊ n/3 ⌋的数,在数组中至多只有两个,可以画图理解。

    class Solution {
    public:
        vector<int> majorityElement(vector<int>& nums) {
            vector<int> res;
            int numsSize = nums.size();
            int resval1 = 0,resval2=0;
            int times1 = 0,times2=0;
            for(int i=0;i<numsSize;i++){
                if(i==0){
                    resval1 = nums[i];
                    times1++;
                }else{
                    if(nums[i]==resval1){
                        times1++;
                    }else if(times2==0){
                        times2=1;
                        resval2 = nums[i];
                    }else if(nums[i]==resval2){
                        times2++;
                    }else{
                        times1--;
                        times2--;
                        if(times1==0){
                            times1=1;
                            resval1=nums[i];
                        }
                    }
                }
            }
            int cnt1=0,cnt2=0;
            for(int i=0;i<numsSize;i++){
                if(nums[i]==resval1)
                   cnt1++;
                if(nums[i]==resval2)
                   cnt2++;
            }
            if(cnt1>(numsSize/3))
                res.push_back(resval1);
            if(cnt2!=numsSize && cnt2>(numsSize/3))
                res.push_back(resval2);
            return res;
        }
    };
  • 相关阅读:
    最小的K个数
    CentOS 7 连接不到网络解决方法
    数组中超过一半的数字
    字符串的排列
    二叉搜索树与双向链表
    复杂链表的复制
    二叉树中和为某一数值的路径
    二叉搜索树的后序遍历序列
    从上到下打印二叉树
    java的图形文档
  • 原文地址:https://www.cnblogs.com/zengzy/p/4960642.html
Copyright © 2011-2022 走看看