https://oj.leetcode.com/problems/majority-element/
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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
public class Solution { public int majorityElement(int[] num) { int last=num[0]; int cnt=1; for(int i=1;i<num.length;i++){ if(num[i]!=last){ cnt--; if(cnt==0){ last=num[i]; cnt=1; } }else{ cnt++; } } return last; } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。