【Leetcode】 面试题 17.10. Find Majority Element LCCI 主要元素

Problem

Leetcode

A majority element is an element that makes up more than half of the items in an array. Given a positive integers array, find the majority element. If there is no majority element, return -1. Do this in O(N) time and O(1) space.

Example

Example1:

Input: [1,2,5,9,5,9,5,5,5]
Output: 5

Example2:

Input: [3,2]
Output: -1

Example3:

Input: [2,2,1,1,1,2,2]
Output: 2

Solution

Java

Solution1 排序

class Solution {
    public int majorityElement(int[] nums) {
        Arrays.sort(nums);
        int mid = nums[nums.length / 2];
        int cnt = 0;
        for(int j = 0; j < nums.length; j++) {
            if(nums[j] == mid)
                cnt++;
        }
        if(cnt > nums.length / 2)
            return mid;
        else
            return -1;
    }
}

Solution2 摩尔投票算法

class Solution {
    public int majorityElement(int[] nums) {
        int count = 1;
        int candidate = nums[0];
        for(int i = 1; i < nums.length; i++) {
            if(nums[i] != candidate) {
                if(count == 0) {
                    candidate = nums[i];
                    count++;
                }
                else
                    count--;
            }
            else 
                count++;
        }
        int times = 0;
        for(int j = 0; j < nums.length; j++) {
            if(nums[j] == candidate)
                times++;
        }
        if(times > (nums.length / 2))
            return candidate;
        else
            return -1;
    }
}

思路

Solution1 排序

将数组排序后,中间的数据不一定是主要元素,但主要元素一定在中间。
所以再将中间值与数组中每个值进行比较,若相等,则计数cnt+1。如果cnt最后大于等于 n / 2,则说明中间值就是主要元素,否则数组无主要元素。
这种比较简单,很容易想,但是复杂度较高。
在这里插入图片描述

Solution2 摩尔投票算法

算法思想:
首先设置count和candidate两个变量。从数组第一个数据开始,candidate 初始化为 nums[0], count = 1。然后按顺序将数组元素与 candidate 比较,如果两数据相等,则 count++, candidate不变。如果两数据不等,则 count 减一。当 count == 0, 且待比较的数据与 candidate 不等时,candidate 修改为待比较的这个数据,count = 1。比到最后,如果存在主要元素的话,那么留下来的candidate就是主要元素了。

所以在最后要和排序算法一样,要遍历数组与candidate比较,若出现次数大于 n / 2,说明candidate就是主要元素。

性能明显提升
摩尔投票算法

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值