博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
主元素
阅读量:6956 次
发布时间:2019-06-27

本文共 1330 字,大约阅读时间需要 4 分钟。

hot3.png

原题

  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;    }}

转载于:https://my.oschina.net/u/2822116/blog/812108

你可能感兴趣的文章
box-sizing
查看>>
KMP算法
查看>>
log4j配置
查看>>
转:点积&叉积
查看>>
怎样找到excel两列之间同行相同的数据
查看>>
《Andrew Ng深度学习》笔记4
查看>>
JSON数据格式解析
查看>>
个人作业3——个人总结(Alpha阶段)
查看>>
录音,
查看>>
header 的蓝色,
查看>>
Hadoop中文文档
查看>>
python3.x与2.x的区别
查看>>
SCOI2011 地板 (BZOJ2331)
查看>>
七大进程间通信和线程同步
查看>>
VC++ msdn
查看>>
【HDOJ】3367 Pseudoforest
查看>>
如何获取Window
查看>>
Eclipse配置ADT(在Eclipse中进行Android开发)
查看>>
ionic的页面直接的跳转
查看>>
冒泡排序
查看>>