LeetCode题解:Majority Element

来源:互联网 发布:51单片机与蓝牙模块 编辑:程序博客网 时间:2024/06/05 07:17

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

题意:找出数组中出现次数大于n/2的数

解决思路:由于该数出现次数大于n/2,因此它和每一个相异数抵消的话,剩余的个数仍然大于0,所以对每一个数计算出现次数,次数为负则换数

代码:

public class Solution {    public int majorityElement(int[] nums) {        int major=nums[0], count = 1;        for(int i=1; i<nums.length;i++){            if(count==0){                count++;                major=nums[i];            }else if(major==nums[i]){                count++;            }else count--;        }        return major;    }}
0 0
原创粉丝点击