1. 程式人生 > 資訊 >一加智慧手錶 OnePlus Watch 外觀公佈:採用圓形錶盤,3 月 24 日釋出

一加智慧手錶 OnePlus Watch 外觀公佈:採用圓形錶盤,3 月 24 日釋出

摩爾投票法


摩爾投票法分為兩個階段:配對階段和計數階段

169. 多數元素

class Solution {
    public int majorityElement(int[] nums) {
        int candidate = nums[0], count = 0;
        // 配對階段
        for(int num : nums){
            if(count == 0){
                candidate = num;
            }
            if(
num == candidate){ count++; }else{ count--; } } // 計數階段 count = 0; for(int num : nums){ if(num == candidate){ count++; } } return count > nums.length / 2 ? candidate :
0; } }

229. 求眾數 II

在這裡插入圖片描述
思路:要選所有超過 ⌊ 1/3 ⌋ 次的元素,最多隻有2個,因為不可能3個元素都超過 1 / 3

如果至多選一個代表,那他的票數至少要超過一半(⌊ 1/2 ⌋)的票數;
如果至多選兩個代表,那他們的票數至少要超過 ⌊ 1/3 ⌋ 的票數;
如果至多選m個代表,那他們的票數至少要超過 ⌊ 1/(m+1) ⌋ 的票數。
class Solution {
    public List<Integer> majorityElement(int[] nums) {
        List<Integer> res = new ArrayList
<>(); if(nums.length == 0 || nums == null) return res; int cand1 = nums[0]; int count1 = 0; int cand2 = nums[0]; int count2 = 0; // 配對階段 for(int num : nums){ if(num == cand1){ count1++; }else if(num == cand2){ count2++; }else if(count1 == 0){ cand1 = num; count1++; }else if(count2 == 0){ cand2 = num; count2++; }else{ count1--; count2--; } } // 計數階段 count1 = 0; count2 = 0; for(int num : nums){ if(num == cand1) count1++; else if(num == cand2) count2++; } if(count1 > nums.length / 3) res.add(cand1); if(count2 > nums.length / 3) res.add(cand2); return res; } }