(LeetCode 面试经典 150 题) 169. 多数元素(哈希表 || 二分查找)

题目:169. 多数元素

方法一:二分法,最坏的时间复杂度0(nlogn),但平均0(n)即可。空间复杂度为0(1)。

C++版本:

cpp 复制代码
int n=nums.size();
        int l=0,r=n-1;
        while(l<r){
            int mid=(l+r)/2;
            int ans=0;
            for(auto x:nums){
                if(x==nums[mid]) ans++;
            }
            if(ans>n/2) break;
            else l=mid+1;
        }
        return nums[(l+r)/2];

JAVA版本:

java 复制代码
class Solution {
    public int majorityElement(int[] nums) {
        int n=nums.length;
        int l=0,r=n-1;
        while(l<r){
            int mid=(l+r)/2;
            int ans=0;
            for(var x:nums){
                if(x==nums[mid]) ans++;
            }
            if(ans>n/2) break;
            else l=mid+1;
        }
        return nums[(l+r)/2];
    }
}

Go版本:

go 复制代码
func majorityElement(nums []int) int {
    n:=len(nums)
    l,r:=0,n-1
    for l<r {
        mid:=(l+r)/2
        ans:=0
        for _,x:=range nums {
            if nums[mid]==x {
                ans++
            }
        }
        if ans>n/2 {
            break
        }else{
            l=mid+1
        }
    }
    return nums[(l+r)/2]
}

方法二:哈希表,时间复杂度0(n),空间复杂度0(n)。

C++版本:

cpp 复制代码
class Solution {
public:
    int majorityElement(vector<int>& nums) {
        unordered_map<int,int> mp;
        int n=nums.size();
        int res=0;
        for(auto x:nums){
            mp[x]++;
            if(mp[x]>n/2){
                res=x;
                break;
            }
        }
        return res;
    }
};

JAVA版本:

java 复制代码
class Solution {
    public int majorityElement(int[] nums) {
        Map<Integer,Integer> mp = new HashMap<>();
        int n=nums.length;
        int res=0;
        for(var x:nums){
            mp.put(x,mp.getOrDefault(x,0)+1);
            if(mp.get(x)>n/2){
                res=x;
                break;
            }
        }
        return res;
    }
}

Go版本:

go 复制代码
func majorityElement(nums []int) int {
    n:=len(nums)
    mp:=make(map[int]int)
    res:=0
    for _,x:=range nums {
        mp[x]++
        if mp[x]>n/2 {
            res=x
            break
        }
    }
    return res
}
相关推荐
wydaicls1 小时前
C语言对单链表的操作
c语言·数据结构·算法
傻童:CPU1 小时前
C语言需要掌握的基础知识点之排序
c语言·算法·排序算法
骁的小小站3 小时前
Verilator 和 GTKwave联合仿真
开发语言·c++·经验分享·笔记·学习·fpga开发
计算机学姐4 小时前
基于微信小程序的高校班务管理系统【2026最新】
java·vue.js·spring boot·mysql·微信小程序·小程序·mybatis
一路向北⁢4 小时前
基于 Apache POI 5.2.5 构建高效 Excel 工具类:从零到生产级实践
java·apache·excel·apache poi·easy-excel·fast-excel
大数据张老师5 小时前
数据结构——邻接矩阵
数据结构·算法
低音钢琴6 小时前
【人工智能系列:机器学习学习和进阶01】机器学习初学者指南:理解核心算法与应用
人工智能·算法·机器学习
旭意6 小时前
C++蓝桥杯之结构体10.15
开发语言·c++
毕设源码-赖学姐7 小时前
【开题答辩全过程】以 基于Android的校园快递互助APP为例,包含答辩的问题和答案
java·eclipse
damo017 小时前
stripe 支付对接
java·stripe