LeetCode 169. Majority Element

来源:互联网 发布:央视网络 编辑:程序博客网 时间:2024/05/17 23:23

LeetCode 169. Majority Element

问题来源LeetCode 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.

问题分析

这道题是求一个数组中出现次数超过总数目一半的数字。一种比较简单的方式就是用Map保存所有的数,对所有的数出现的次数进行分析。但是占用的空间太多了。另一种方法就是:

某一个字出现的次数超过总数的一半,可以知道其他数出现的次数不会到一半。维护变量下x 用来统计 y出现的次数。一旦出现了别的数,x就减去1,如果x=0了,就记录下来当前的数为y,继续记录y出现的次数,这样最后剩下的肯定是所要求的那个数。

Java代码

public int majorityElement(int[] nums) {    int major = nums[0],count = 1;    for(int i =1;i < nums.length;i++){        if(count == 0){            major = nums[i];            count++;        }else if(major == nums[i]){            count++;        }else count--;    }    return major;}

LeetCode学习笔记持续更新

GitHub地址 https://github.com/yanqinghe/leetcode

CSDN博客地址 http://blog.csdn.net/yanqinghe123/article/category/7176678

原创粉丝点击