zoukankan      html  css  js  c++  java
  • majorityElement

    169. 多数元素
    给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
    
    你可以假设数组是非空的,并且给定的数组总是存在多数元素。
    
     
    
    示例 1:
    
    输入: [3,2,3]
    输出: 3
    示例 2:
    
    输入: [2,2,1,1,1,2,2]
    输出: 2
    
    // 投票法 // 另外有hash,排序取n/2等方法可求解
    class Solution {
        public int majorityElement(int[] nums) {
            int cnt = 0, res = -1;
            for(int each: nums){
                if(cnt == 0) res = each;
                if(res == each) cnt++;
                else cnt--;
            }
            return res;
        }
    }
    
  • 相关阅读:
    python-04
    python-03
    python-02
    python-01
    day4-RHCS
    python 之元组(tuple)
    11.21
    python之猜数小游戏
    python之简陋的数据库
    11.20
  • 原文地址:https://www.cnblogs.com/athony/p/13061330.html
Copyright © 2011-2022 走看看