首页 > 代码库 > leetcode majority elements
leetcode majority elements
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.
解法:
As we sweep we maintain a pair consisting of a current candidate and a counter. Initially, the current candidate is unknown and the counter is 0.
When we move the pointer forward over an element e:
- If the counter is 0, we set the current candidate to e and we set the counter to 1.
- If the counter is not 0, we increment or decrement the counter according to whether e is the current candidate.
When we are done, the current candidate is the majority element, if there is a majority.
public class Solution { public int majorityElement(int[] num) { int sum=0; int result=0; for(int i=0;i<num.length;i++){ if(sum==0){ result=num[i]; sum++; } else if(result==num[i]){ sum++; if(sum>num.length/2){ return result; } } else sum--; } return result; }}
leetcode majority elements
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。