码迷,mamicode.com
首页 > 编程语言 > 详细

169. 多数元素-数组/众数-简单

时间:2020-10-14 20:32:30      阅读:22      评论:0      收藏:0      [点我收藏+]

标签:and   输入   次数   element   --   ret   tco   col   problem   

问题描述

给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ? n/2 ? 的元素。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

 

示例 1:

输入: [3,2,3]
输出: 3
示例 2:

输入: [2,2,1,1,1,2,2]
输出: 2

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/majority-element

解答

//投票法
class Solution {
    public int majorityElement(int[] nums) {
        int c = 0, candidate = 0;
        for(int i:nums){
            if(c == 0){
                candidate = i;
                c++;
                continue;
            }else{
                if(candidate == i)c++;
                else c--;
            }
        }
        return candidate;
    }
}

 

169. 多数元素-数组/众数-简单

标签:and   输入   次数   element   --   ret   tco   col   problem   

原文地址:https://www.cnblogs.com/xxxxxiaochuan/p/13814118.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!