【leetcode刷题笔记】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.


 

题解:设置两个变量,一个是current,初始化为A[0];另一个是count,记录current这个元素当前为止出现的次数。然后遍历A,如果当前元素和current相等,则count加1;否则,看count是否为0,如果count已经为0,就直接把current赋值成当前元素;如果count不为0,就把count减一即可。

这个思路的根本就是找不相等的元素配对,如果有两个不相等的元素,就把他们两个抵消,那么最后没有抵消掉的那个元素,就是出现次数超过⌊ n/2 ⌋的。

JAVA版本代码:

复制代码
 1 public class Solution {
 2     public int majorityElement(int[] num) {
 3         int current = num[0];
 4         int count = 0;
 5         for(int i = 1;i < num.length;i++){
 6             if(current == num[i])
 7                 count++;
 8             else{
 9                 if(count >0){
10                     count--;
11                 }else {
12                     current = num[i];
13                 }
14             }
15         }
16         return current;
17     }
18 }
复制代码

 

posted @   SunshineAtNoon  阅读(142)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2014-03-31 【leetnode刷题笔记】Maximum Depth of binary tree
2014-03-31 【leetcode刷题笔记】Single Number
点击右上角即可分享
微信分享提示