zoukankan      html  css  js  c++  java
  • 面试题 17.10. 主要元素

    面试题 17.10. 主要元素

    数组中占比超过一半的元素称之为主要元素。给定一个整数数组,找到它的主要元素。若没有,返回-1。

    示例 1:

      输入:[1,2,5,9,5,9,5,5,5]
      输出:5
     

    示例 2:

      输入:[3,2]
      输出:-1
     

    示例 3:

      输入:[2,2,1,1,1,2,2]
      输出:2

     

    解题思路

    方法一:map,此方法时间复杂度O(n),空间复杂度O(n)

    方法二:排序+双指针,此方法时间复杂度O(nlog2n),空间复杂度O(1)

    方法三:投票法

     

    方法一:map

    class Solution {
    public:
        int majorityElement(vector<int>& nums) {
            unordered_map<int, int> map;
            for(int i : nums) {
                map[i] ++;
                if(map[i] > nums.size() / 2) return i;
            }
            return -1;
        }
    };

    方法二:排序+双指针

    class Solution {
    public:
        int majorityElement(vector<int>& nums) {
            sort(nums.begin(), nums.end());
            for(int i = 0, j = 0; j < nums.size(); i = j) {
                while(j < nums.size() && nums[i] == nums[j]) j ++;
                if(j - i > nums.size() / 2) return nums[i];
            }
            return -1;
        }
    };

    方法三:投票法

    #include<iostream>
    #include<bits/stdc++.h>
    #include<cstring>
    #include<vector>
    #include<map>
    using namespace std;
    
    int getMainElem(vector<int>vec){
        int x,vote;
        for (int i = 0; i < vec.size(); i++)
        {
    
            if (vote==0)
            {
                x=vec[i];
            }
            vote+=(vec[i]==x)?1:-1;
        }
        vote=0;
        for (int i = 0; i < vec.size(); i++)
        {
            if (vec[i]==x)
                vote++;
        }
        if (vote>=vec.size()/2)
        {
            return x;
        }else
        {
            return -1;
        }
    }
    
    int main(){
        int arr[]={1,2,5,9,5,9,5,5,5};
        vector<int>vec(arr,arr+9);
        cout<<getMainElem(vec);
    }

    因上求缘,果上努力~~~~ 作者:每天卷学习,转载请注明原文链接:https://www.cnblogs.com/BlairGrowing/p/13549679.html

  • 相关阅读:
    阻止默认事件和冒泡
    js获取元素相对窗口位置
    ios中safari浏览器中date问题
    模拟单选框,多选框
    vue
    js合并两个对象的方法
    oracle 序列
    Oracle生成随机数大全
    JAVA基础面试题
    网速计算
  • 原文地址:https://www.cnblogs.com/BlairGrowing/p/13549679.html
Copyright © 2011-2022 走看看