169. 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.


我的思路:

首先想到的方法是排序,排序后的中位数则是要查找的数,但是这样的话时间复杂度为O(nlogn)

在看了discuss之后,想起来在《剑指offer》上也看过这道题,其中给出了两种思想,其中一种引入快排思想但是并未完全排序的O(n)的方法,另一种思路和discuss中给出的相仿。


discuss中的思路:

类似于对对碰的思想,由于待寻找的数字n出现的次数超过剩下所有数字的总和,初始设定一个数值n和次数,遍历数组,当与数值相同时次数加1,当与数值不同时次数减1;而当次数减少到0时,将次数重置为1并设置当前值为n。


例如:{1,2,1,2,1,2,1,1},1为待寻找的数字,则相当于前3对{1,2}都抵消了,只剩下最后的1了。


代码如下:

public class Solution {
    public int majorityElement(int[] nums) {
       //思路:出现次数超过一半的数字num出现的次数超过其他所有数字出现次数的总和
       //时间复杂度O(n)
       int i;
       int num = nums[0];
       int time = 1;
       
       for(i = 1; i < nums.length; i++){
           if(time == 0){
               //次数减少到1时,重置次数并将num设置为该数字
               num = nums[i];
               time = 1;
           }else if(nums[i] == num){
               //与num相等时增加次数
               time++;
           }else{
               time--;
           }
       }      
       return num;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值