?LeetCode刷題實戰(zhàn)169:多數(shù)元素
Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ?n / 2? times. You may assume that the majority element always exists in the array.
題意
示例 1:
輸入:[3,2,3]
輸出:3
示例 2:
輸入:[2,2,1,1,1,2,2]
輸出:2
解題
class?Solution?{
????public?int?majorityElement(int[] nums)?{
????????int?len = nums.length;
????????int?res = Integer.MIN_VALUE;
????????Mapmap?= new?HashMap<>();
????????for(int?num:nums){
????????????map.put(num,map.getOrDefault(num,0)+1);
????????}
????????for(Map.Entryentry: map.entrySet()){
????????????if(entry.getValue()>len/2){
????????????????res = entry.getKey();
????????????}
????????}
????????return?res;
????}
}
class?Solution?{
????public?int?majorityElement(int[] nums)?{
????????Arrays.sort(nums);
????????return?nums[nums.length/2];
????}
}
當遇到與cand_num相同的數(shù),則票數(shù)count = count + 1,否則票數(shù)count = count - 1。
當票數(shù)count為0時,更換候選人,并將票數(shù)count重置為1。
遍歷完數(shù)組后,cand_num即為最終答案。
投票法是遇到相同的則票數(shù) + 1,遇到不同的則票數(shù) - 1。
且“多數(shù)元素”的個數(shù)> ? n/2 ?,其余元素的個數(shù)總和<= ? n/2 ?。
因此“多數(shù)元素”的個數(shù) - 其余元素的個數(shù)總和 的結果 肯定 >= 1。
這就相當于每個“多數(shù)元素”和其他元素 兩兩相互抵消,抵消到最后肯定還剩余至少1個“多數(shù)元素”。
class?Solution?{
????public?int?majorityElement(int[] nums)?{
????????int?cand_num = nums[0], count = 1;
????????for?(int?i = 1; i < nums.length; ++i) {
????????????if?(cand_num == nums[i])
????????????????++count;
????????????else?if?(--count == 0) {
????????????????cand_num = nums[i];
????????????????count = 1;
????????????}
????????}
????????return?cand_num;
????}
}
評論
圖片
表情
