Algorithm Notes
  • Introduction
  • Search & Backtracking 搜索与回溯
    • Tree 与 BackTracking 的比较
    • Subsets, Combination 与 Permutation
    • Subsets & Combinations & Combination Sum
    • 枚举法
    • N 皇后 + 矩阵 Index Trick
    • Sudoku 数独 + 矩阵 Index Trick
    • Word Ladder I & II
    • Number of ways 类
    • DFS flood filling
    • Strobogrammatic 数生成
    • String 构造式 DFS + Backtracking
    • Word Pattern I & II
    • (G) Binary Watch
    • (FB) Phone Letter Combination
    • 常见搜索问题的迭代解法
  • String,字符串类
    • 多步翻转法
    • Substring 结构和遍历
    • Palindrome 问题
    • Palindrome Continued
    • String / LinkedList 大数运算
    • 序列化与压缩
    • 5/24 String 杂题
    • Knuth–Morris–Pratt 字符串匹配
    • Lempel–Ziv–Welch 字符串压缩算法
    • (G) Decode String
    • (G) UTF-8 Validation
  • Binary Tree,二叉树
    • 各种 Binary Tree 定义
    • LCA 类问题
    • 三序遍历,vertical order
    • Post order traversal 的应用
    • Min/Max/Balanced Depth
    • BST
    • 子树结构
    • Level Order traversal
    • Morris 遍历
    • 修改结构
    • 创建 / 序列化
    • 子树组合,BST query
    • 路径与路径和
    • NestedInteger 类
    • (FB) 从 Binary Tree Path 看如何递归转迭代
    • (FB) Binary Tree Path 比较路径大小
    • 比较好玩的 Binary Tree 概率题
  • Segment & Fenwick Tree,区间树
    • Segment Tree 基础操作
    • Segment Tree 的应用
    • Fenwick Tree (Binary Indexed Tree)
    • Range Sum Query 2D - Immutable
  • Union-Find,并查集
    • Union-Find,并查集基础
    • Union-Find, 并查集应用
  • Dynamic Programming, 动态规划
    • 6/20, 入门 House Robber
    • 7/12, Paint Fence / House
    • 6/24, 滚动数组
    • 6/24, 记忆化搜索
    • 6/24, 博弈类 DP
    • 博弈类DP, Flip Game
    • 6/25, 区间类DP
    • 6/27, subarray 划分类,股票
    • 7/2, 字符串类
    • Bomb Enemies
    • 8/2,背包问题
    • (G) Max Vacation
    • (11/4新增) AST 子树结构 DP
  • LinkedList,链表
    • 6/9, LinkedList,反转与删除
    • 6/11, LinkedList 杂题
    • (FB) 链表的递归与倒序打印
  • LinkedIn 面经,算法题
    • 6/17, LinkedIn 面经题
    • 6/28, LinkedIn 面经题
    • 7/6, LinkedIn 面经
    • Shortest Word Distance 类
    • DFA Parse Integer
  • Two Pointers,双指针
    • 3 Sum, 3 Sum Closest / Smaller, 4 Sum
    • 对撞型,灌水类
    • 对撞型,partition类
    • Wiggle Sort I & II
    • 双指针,窗口类
    • 双指针,窗口类
    • Heap,排序 matrix 中的 two pointers
  • Bit & Math,位运算与数学
    • Bit Manipulation,对于 '1' 位的操作
    • Math & Bit Manipulation, Power of X
    • 坐标系 & 数值计算类
    • Add Digits
    • 用 int 做字符串 signature
  • Interval 与 扫描线
    • Range Addition & LCS
    • 7/5, Interval 类,扫描线
  • Trie,字典树
    • 6/9, Trie, 字典树
  • 单调栈,LIS
    • 4/13 LIS
    • 栈, 单调栈
    • Largest Divisible Subset
  • Binary Search 类
    • Matrix Binary Search
    • Array Binary Search
    • Find Peak Element I & II
    • **Median of Two Sorted Arrays
  • Graph & Topological Sort,图 & 拓扑排序
    • 有向 / 无向 图的基本性质和操作
    • 拓扑排序, DFS 做法
    • 拓扑排序, BFS 做法
    • Course Schedule I & II
    • Alien Dictionary
    • Undirected Graph, BFS
    • Undirected Graph, DFS
    • 矩阵,BFS 最短距离探索
    • 欧拉回路,Hierholzer算法
    • AI, 迷宫生成
    • AI, 迷宫寻路算法
    • (G) Deep Copy 无向图成有向图
  • 括号与数学表达式的计算
  • Iterator 类
  • Majority Element,Moore's Voting
  • Matrix Inplace Operations
  • 常见数据结构设计
  • (G) Design / OOD 类算法题
  • 随机算法 & 数据结构
  • (FB) I/O Buffer
  • (FB) Simplify Path, H-Index I & II
  • (FB) Excel Sheet, Remove Duplicates
  • Integer 的构造,操作,序列化
  • Frequency 类问题
  • Missing Number 类,元素交换,数组环形跳转
  • 8/10, Google Tag
  • (FB) Rearrange String k Distance Apart
  • Abstract Algebra
    • Chap1 -- Why Abstract Algebra ?
    • Chap2 -- Operations
    • Chap3 -- The Definition of Groups
Powered by GitBook
On this page
  • 遍历一次,保存一个长度为k - 1的数组:
  • 最后数组中剩下的数,就是candidate,每个统计一下就可以了
  • 这个方法可以解决任意1/k的majority number
  • Majority Element
  • Majority Element II
  • Moore's Voting Algorithm.
  • Majority Number III
  • (Google) Majority Element
  • 解决办法就是依次检查所有可能的出现 majority element 的位置 [n/k,2n/k, .... ,n] ,在每个位置上根据当前元素做 search for range,O(log n),如此重复最多 k 次即可。

Was this helpful?

Majority Element,Moore's Voting

PreviousIterator 类NextMatrix Inplace Operations

Last updated 4 years ago

Was this helpful?

遍历一次,保存一个长度为k - 1的数组:

  • 如果数组中包括这个数,则该数count + 1

  • 如果数组中有空位,则放入概该,count置为1

  • 如果数组中有数字count为0,则替换该数,count置为1

  • 所有数字count减1

最后数组中剩下的数,就是candidate,每个统计一下就可以了

这个方法可以解决任意1/k的majority number

经典的投票算法。

public class Solution {
    public int majorityElement(int[] num) {

        int major=num[0], count = 1;
        for(int i=1; i<num.length;i++){
            if(count==0){
                count++;
                major=num[i];
            }else if(major==num[i]){
                count++;
            }else count--;

        }
        return major;
    }
}

Moore's Voting Algorithm.

遍历一次,保存一个长度为k - 1的数组: 1. 如果数组中包括这个数,则该数count + 1 2. 如果数组中有空位,则放入该数,count置为1 3. 如果数组中有数字count为0,则替换该数,count置为1 4. 所有数字count减1

最后数组中剩下的数,就是candidate; 此时再扫一遍数组,确认每个 candidate 的真正出现次数,并根据时候符合最终要求添加到最终结果里。

在这个算法中,count = 0 并不一定代表这个数不是 majority 应该被“立刻”踢出去。

这个方法可以解决任意n/k的majority number

从思想上说,这种做法有点像蓄水池抽样,又有点像 find the celebrity,都是 streaming data 然后维护固定 size 进行淘汰的机制。

public class Solution {
    public List<Integer> majorityElement(int[] nums) {
        List<Integer> list = new ArrayList<>();
        if(nums == null || nums.length == 0) return list;

        int count1 = 0;
        int count2 = 0;
        int num1 = 0;
        int num2 = 1; 
        // 1 and 2 should be initialized to be different numbers

        for(int i = 0; i < nums.length; i++){
            if(nums[i] == num1){
                count1++;
            } else if(nums[i] == num2) {
                count2++;
            } else if(count1 == 0){
                num1 = nums[i];
                count1 = 1;
            } else if(count2 == 0){
                num2 = nums[i];
                count2 = 1;
            } else {
                count1 --;
                count2 --;
            }
        }
        int n = nums.length;

        count1 = 0;
        count2 = 0;
        for(int i = 0; i < nums.length; i++){
            if(nums[i] == num1) count1++;
            else if(nums[i] == num2) count2++;
        }

        if(count1 > n / 3) list.add(num1);
        if(count2 > n / 3) list.add(num2);

        return list;
    }
}

同样的思路扩展开来的通用解法,不过注意这题说了只会有一个 majority element 所以最后 return 那里有所不同,但是这个算法完全可以找到所有 k - 1 个。

    public int majorityNumber(ArrayList<Integer> nums, int k) {
        // write your code
        int n = nums.size();

        List<Integer> numList = new ArrayList<>();
        List<Integer> countList = new ArrayList<>();

        if(nums == null || nums.size() == 0) return -1;

        for(int i = 0; i < n; i++){
            int num = nums.get(i);
            if(numList.size() < k - 1 && !numList.contains(num)){
                numList.add(num);
                countList.add(1);
            } else {
                int index = numList.indexOf(num);
                if(index != -1){
                    // current number is in candidate list;
                    countList.set(index, countList.get(index) + 1);
                } else {
                    int zeroIndex = countList.indexOf(0);
                    if(zeroIndex != -1){
                        numList.remove(zeroIndex);
                        countList.remove(zeroIndex);
                        numList.add(num);
                        countList.add(1);
                    } else {
                        for(int j = 0; j < countList.size(); j++){
                            countList.set(j, countList.get(j) - 1);
                        }
                    }
                }
            }
        }

        //List<Integer> rst = new ArrayList<>();
        for(int i = 0; i < numList.size(); i++){
            int count = 0;
            for(int num : nums){
                if(num == numList.get(i)) count++;
            }
            //if(count > n / k) rst.add(numList.get(i));
            if(count > n / k) return numList.get(i);
        }
        return -1;
    }

(Google) Majority Element

之前google面经里有的关于majority element的题,就是一个排序数组有n个值,求所有出现次数等于或者超过n / k的值。 比如[1 1 2 2 2 2 3 4 5 5 5 5] k = 3 return [2,5]

解决办法就是依次检查所有可能的出现 majority element 的位置 [n/k,2n/k, .... ,n] ,在每个位置上根据当前元素做 search for range,O(log n),如此重复最多 k 次即可。

Majority Element
Majority Element II
Majority Number III
http://www.1point3acres.com/bbs/thread-191900-1-1.html