码迷,mamicode.com
首页 > 其他好文 > 详细

Lc169_多数元素

时间:2020-07-15 15:32:02      阅读:59      评论:0      收藏:0      [点我收藏+]

标签:并且   code   void   存在   test   string   package   ted   ++   


//给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ? n/2 ? 的元素。 
//
// 你可以假设数组是非空的,并且给定的数组总是存在多数元素。 
//
// 
//
// 示例 1: 
//
// 输入: [3,2,3]
//输出: 3 
//
// 示例 2: 
//
// 输入: [2,2,1,1,1,2,2]
//输出: 2
// 
// Related Topics 位运算 数组 分治算法

package leetcode.editor.cn;
//Java:多数元素
public class P169MajorityElement{
    public static void main(String[] args) {
        Solution solution = new P169MajorityElement().new Solution();
        // TO TEST
    }
    //leetcode submit region begin(Prohibit modification and deletion)
class Solution {
        //摩尔斯投票法
    public int majorityElement(int[] nums) {
        int count= 1;
        int represent = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if(represent == nums[i]){
                count++;
            }else{
                count--;
                if(count==0){
                    represent = nums[i];
                    count=1;
                }
            }

        }
        return represent;

    }
}
//leetcode submit region end(Prohibit modification and deletion)

}

Lc169_多数元素

标签:并且   code   void   存在   test   string   package   ted   ++   

原文地址:https://www.cnblogs.com/xiaoshahai/p/13305146.html

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