`

LeetCode 169 - Majority Number

 
阅读更多

Majority Number I

Given an array of integers, the majority number is the number that occurs more than half of the size of the array. Find it.

 

Example

Given [1, 1, 1, 1, 2, 2, 2], return 1 

Challenge

O(n) time and O(1) extra space 

public int majorityNumber(List<Integer> nums) {
    int candidate = 0, count = 0;
    for(int num : nums) {
        if(num == candidate) {
            count++;
        } else if(count != 0) {
            count--;
        } else {
            candidate = num;
            count = 1;
        }
    }
    return candidate;
}

 

Majority Number II

 

Given an array of integers, the majority number is the number that occursmore than 1/3 of the size of the array. Find it.

 

Example

Given [1, 2, 1, 2, 1, 3, 3], return 1.

public List<Integer> majorityElement(int[] nums) {
    int cnt1=0, cnt2=0;
    int a = 0, b = 0;
    for(int n: nums){
        if (cnt1 == 0 || n == a) {
            cnt1++;
            a = n;
        } else if (cnt2 == 0 || n==b) {
            cnt2++;
            b = n;
        } else {
            cnt1--;
            cnt2--;
        }
    }
    cnt1 = cnt2 = 0;
    for(int n: nums){
        if (n==a) cnt1++;
        else if (n==b) cnt2++;
    }

    List<Integer> result = new ArrayList<>();
    if (cnt1 > nums.length/3) result.add(a);
    if (cnt2 > nums.length/3) result.add(b);
    return result;
}

 

Majority Number III

Given an array of integers and a number k, the majority number is the number that occurs more than 1/k of the size of the array. Find it.

Example

Given [3,1,2,3,2,3,3,4,4,4] and k=3, return 3.

Note

There is only one majority number in the array.

Challenge

O(n) time and O(k) extra space

public int majorityNumber(List<Integer> nums, int k) {
    Map<Integer, Integer> map = new HashMap<>();
    for(int num:nums) {
        if(map.containsKey(num)) {
            map.put(num, map.get(num)+1);
        } else {
            if(map.size() == k-1) {
                List<Integer> trash = new ArrayList<>();
                for(int key:map.keySet()) {
                    int cnt = map.get(key);
                    if(--cnt == 0) {
                        trash.add(key);
                    } else {
                        map.put(key, cnt);
                    }
                }
                for(int key:trash) map.remove(key);
            } else {
                map.put(num, 1);
            }
        }
    }
    for(int key:map.keySet()) {
        int cnt = 0;
        for(int num:nums) {
            if(num==key) cnt++;
        }
        if(cnt > nums.size()/k) return key;
    }
    return -1;
}

C++的代码: 

vector<int> majorityElement(vector<int>& nums) {
    unordered_map<int,int> map;
    for(int num:nums) {
        if(map.size() < 2 || map.count(num))  {
            map[num]++;
        } else {
            vector<int> keys;
            for(auto& p:map) {
                if(--p.second == 0) {
                    keys.push_back(p.first);
                }
            }
            for(int key:keys) map.erase(key);
        }
    }
    vector<int> result;
    for(auto& p : map) {
        int cnt = 0;
        for(int num:nums) {
            if(num == p.first && ++cnt > nums.size()/3) {
                result.push_back(num);
                break;
            }
        }
    }
    return result;
}

 

Reference:

http://www.geeksforgeeks.org/given-an-array-of-of-size-n-finds-all-the-elements-that-appear-more-than-nk-times/

分享到:
评论

相关推荐

    leetcode卡-Programming:编程

    leetcode卡 Programming 课程设计:光城 ...Number(202)!(要求全部用哈希思想实现!)(选做)(注意:在第四天会进行继续学习) 练习: Three Sum(求三数之和) Majority Element(求众数) Missi

    LeetCode最全代码

    191 |[Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/) | [C++](./C++/number-of-1-bits.cpp) [Python](./Python/number-of-1-bits.py) | _O(1)_ | _O(1)_ | Easy ||| 201 | [Bitwise AND of ...

    leetcode有效期-algorithmTask:算法任务

    Number(202)!(要求全部用哈希思想实现!)(选做)(注意:在第四天会进行继续学习) 链表 实现单链表、循环链表、双向链表,支持增删操作 实现单链表反转 实现两个有序的链表合并为一个有序链表 实现求链表的中间...

    Leetcode的ac是什么意思-LeetCodeInJava:leetcode-java

    #169 Majority Element #171 Excel Sheet Column Number #217 Contains Duplicate #226 Invert Binary Tree #237 Delete Node in a Linked List #238 Product of Array Except Self #242 Valid Anagram #258 Add ...

    戳气球leetcode-leetcode:leetcode

    leetcode category other hot keywords:Palindrome(mic), Subsequence Array 螺旋矩阵Spiral Matrix 顺时针打印矩阵 Next Permutation Product of Array Except Self 189.rotate-array 283.move-zero Range Sum ...

    leetcode有效期-Datawhale-Coding:Datawhale-编码

    Number(202)!(要求全部用哈希思想实现!)(选做)(注意:在第四天会进行继续学习) 【链表】 实现单链表、循环链表、双向链表,支持增删操作 实现单链表反转 实现两个有序的链表合并为一个有序链表 实现求链表的...

    圆和矩形是否重叠leetcode-leetcode_solutions:leetcode_solutions

    圆和椭圆重叠leetcode ——#158 尖端 关心特殊情况 ...是一个常数,所以可以计算出缺失的那个169.Majority Element -&gt; Hashtable | Boyer-Moore 多数投票算法283. 移零 -&gt; 27. 移除元素243.Shortest Word Dista

    leetcode和oj-leetCode:尝试一些OJ

    Number 52.2% Easy 371 两个整数的和 51.6% Easy 104 二叉树的最大深度 50.1% Easy 325% Add the Easy 389.数字 49.9% 简单 226 反转二叉树 48.9% 简单 283 移动零点 46.9% 简单 404 左叶总和 45.5% 简单 383 赎金...

    leetcode2sumc-DataWhale_exercise:用C++编程

    Number(202)!(要求全部用哈希思想实现!)(选做)(注意:在第四天会进行继续学习) 【链表】 实现单链表、循环链表、双向链表,支持增删操作 实现单链表反转 实现两个有序的链表合并为一个有序链表 实现求链表的...

    validnumberleetcode自动机----:数据结构打卡

    valid number leetcode ...Majority Element(求众数) 英文版: 中文版: Missing Positive(求缺失的第一个正数)[作为可选] 英文版: 中文版: Linked List Cycle I(环形链表) 英文版: 中文版: Me

    cpp-算法精粹

    AlgoHub囊括了 POJ, ZOJ, leetcode, HackerRank 等网站的经典题目(一些质量不高的题目则忽略),且 AlgoHub有非常简单的加题系统,用户不需要写一行代码即可自己添加题目,所以AlgoHub的题库还在飞速增长中。...

    validnumberleetcode自动机-code_with_py:编程任务

    valid number ...Majority Element(求众数) 英文版: 中文版: Missing Positive(求缺失的第一个正数)[作为可选] 英文版: 中文版: Linked List Cycle I(环形链表) 英文版: 中文版: Merge k

    validnumberleetcode自动机-LearingTripofNoah:我自己的学习之旅,天天学习至此方休

    Majority Element(求众数) 英文版: 中文版: Missing Positive(求缺失的第一个正数) 英文版: 中文版: Linked List Cycle I(环形链表) 英文版: 中文版: Merge k Sorted Lists(合并 k 个排序链表) 英文版...

Global site tag (gtag.js) - Google Analytics