【LeetCode-面试算法经典-Java实现】【169-Majority Element(主元素)】

126 篇文章 82 订阅

【169-Majority Element(主元素)】


【LeetCode-面试算法经典-Java实现】【所有题目目录索引】


代码下载【https://github.com/Wang-Jun-Chao】

原题

  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.

题目大意

  给定一个数组,找这个数组中的主元素,主元素是元素出现次数大于⌊ n/2 ⌋的元素。
  假设给定的数组非空,主元素都存在。

解题思路

  用一个标记cnt记录某个元素出现的次数,如果后面的元素和它相同就加一,有一个元素和他不相同就减一,当cnt小于等于0时重新记录新的元素。

代码实现

算法实现类

public class Solution {
    public int majorityElement(int[] num) {
        int main = num[0]; // 用于记录主元素,假设第一个是主元素
        int count = 1; // 用于抵消数的个数

        for (int i = 1; i < num.length; i++) { // 从第二个元素开始到最后一个元素
            if (main == num[i]) { // 如果两个数相同就不能抵消
                count++; // 用于抵消的数据加1
            } else {
                if (count > 0) { // 如果不相同,并且有可以抵消的数
                    count--; // 进行数据抵消
                } else { // 如果不相同,并且没有可以抵消的数
                    main = num[i]; // 记录最后不可以抵消的数
                }
            }
        }

        // 对于数组中可能没有主元素的情况,题中说明存在,此步可以省略。
//        count = 0;
//        for (int a : num) {
//            if (a == main) {
//                count++;
//            }
//        }
//
//        if (count >= num.length / 2) {
//            return main;
//        } else {
//            throw new RuntimeException("No majority element");
//        }

        return main;
    }
}

评测结果

  点击图片,鼠标不释放,拖动一段位置,释放后在新的窗口中查看完整图片。

这里写图片描述

特别说明

欢迎转载,转载请注明出处【http://blog.csdn.net/derrantcm/article/details/47902549

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值