??題目來源:
? ? ? ? leetcode題目,網址:面試題 17.10. 主要元素 - 力扣(LeetCode)
解題思路:
? ? ? ?首先,順序遍歷數組,將不同的數字消去,最后留下的數字若計數小于等于 0,則不存在主要元素。然后遍歷數組,對最后留下的數字計數,判斷其是否是主要元素。
解題代碼:
class Solution {public int majorityElement(int[] nums) {int res=0;int cnt=0;for(int num:nums){if(num==res){cnt++;}else{cnt--;if(cnt<0){res=num;cnt=1;}}}if(cnt<=0){return -1;}int count=0;for(int num:nums){if(num==res){count++;}}return count>nums.length/2?res:-1;}
}
總結:
? ? ? 官方題解也是一樣的思路。通過 Boyer-Moore?投票算法得到可能的主要元素或表名不存在主要元素,然后判斷可能的主要元素是否是主要元素。