zoukankan      html  css  js  c++  java
  • lintcode 中等题:Majority number II 主元素 II

    题目

    主元素II

    给定一个整型数组,找到主元素,它在数组中的出现次数严格大于数组元素个数的三分之一。

    样例

    给出数组[1,2,1,2,1,3,3] 返回 1

    注意

    数组中只有唯一的主元素

    挑战

    要求时间复杂度为O(n),空间复杂度为O(1)。

    解题

    利用HashMap,key值是元素值,value是出现次数,但是时间复杂度和空间复杂度都是O(N)

    public class Solution {
        /**
         * @param nums: A list of integers
         * @return: The majority number that occurs more than 1/3
         */
        public int majorityNumber(ArrayList<Integer> nums) {
            // write your code
            HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
            if(nums == null)
                return 0;
            for(int i = 0;i< nums.size();i++){
                int num = nums.get(i);
                if(map.containsKey(num)){
                    map.put(num,map.get(num) + 1);
                }else{
                    map.put(num,1);
                }
                if(map.get(num) > nums.size()/3)
                    return num;
            }
            return 0;
        }
    }
    Java Code

    总耗时: 2099 ms

    九章详解

    主元素(Majority Number)定义为数组中出现次数严格超过一半的数。找到这个数。要求使用O(1)的额外空间和O(n)的时间。

    进阶1:如果数组中存在且只存在一个出现次数严格超过1/3的数,找到这个数。要求使用O(1)的额外空间和O(n)的时间。

    进阶2:如果数组中存在且只存在一个出现次数严格超过1/k的数,找到这个数。要求使用O(k)的额外空间和O(n)的时间。

    解答

    采用抵消法。一旦发现数组中存在两个不同的数,就都删除,直到剩下的数都一样。此时剩下的数就是主元素。因为每次抵消操作之后,剩下来的数种,主元素一定也还是超过一半的。具体实现的时候,记录一个candidate和其出现的次数count,遍历每个数,如果count==0,则把candidate置为遍历到的数,否则看遍历到的数和candidate是否相等,如果相等,则count++,否则count--(抵消),遍历结束后,candidate就是主元素。

     

    进阶1:思路是,如果出现3个不一样的数,就抵消掉。记录两个candidate和每个candidate分别的出现次数。如果遍历到的数和两个candidate都不等,就count都减1。最后可能会剩下两个candidate,再遍历一次整个数组验证一下谁是主元素。

    public class Solution {
        /**
         * @param nums: A list of integers
         * @return: The majority number that occurs more than 1/3
         */
        public int majorityNumber(ArrayList<Integer> nums) {
            // write your code
            if(nums == null)
                return 0;
            int num1 = Integer.MIN_VALUE;
            int times1 = 0;
            int num2 = Integer.MIN_VALUE;
            int times2 = 0;
            for(int i = 0;i< nums.size();i++){
                int num = nums.get(i);
                if( num1 == num){
                    times1 ++;
                }else if(num2 == num){
                    times2 ++;
                }else if( times1==0 ){
                    times1 = 1;
                    num1 = num;
                }else if(times2 ==0){
                    times2 = 1;
                    num2 = num;
                }else{
                    times1--;
                    times2--;
                }
            }
            times1 = 0;
            times2 = 0;
            for(int i=0;i<nums.size(); i++){
                int num = nums.get(i);
                if(num == num1){
                    times1 ++;
                }else if(num == num2){
                    times2 ++;
                }
            }
            return times1>times2?num1:num2;
            
        }
    }
    Java Code
    class Solution:
        """
        @param nums: A list of integers
        @return: The majority number occurs more than 1/3
        """
        def majorityNumber(self, nums):
            # write your code here
            count1 = 0
            count2 = 0
            candidate1 = 0
            candidate2 = 0
            for num in nums:
                if num == candidate1:
                    count1 += 1
                elif num == candidate2:
                    count2 += 2
                elif count1 ==0:
                    count1 = 1
                    candidate1 = num
                elif count2 == 0:
                    count2 = 1
                    candidate2 = num
                else:
                    count1 -= 1
                    count2 -= 1
            count1 = 0
            count2 = 0
            for num in nums:
                if num == candidate1:
                    count1 +=1
                elif num == candidate2:
                    count2 +=1
            if count1>len(nums)/3:
                return candidate1
            else:
                return candidate2
    Python Code

    进阶2:思路是,如果出现k个不一样的数,就抵消掉。这里需要用巧妙的数据结构来记录Candidates,并使得如下操作均为O(1):

    1. 加入一个Candidate/给某个Candidate出现次数+1

    2. Candidates中是否存在某个数

    3. Candidates中所有数的出现次数 - 1

    4. 移除出现次数为0的Candidates

    对于1,2两个操作,我们自然可以想到使用Hash表来完成。对于第4两个操作,我们希望能够有出现次数最少的Candidate的信息,但是如果使用Heap则并非O(1)的时间复杂度。注意到每一次加入一个Candidate时,count均为1,每一次给改变一个Candidate出现次数时,也只涉及到加1运算。因此,如果我们能维护Candidates的有序性,就可以容易的解决这个问题。方法是,使用LinkedList。与普通的LinkedList不同的是,我们将所有出现次数相同的Candidate放在一个Bucket里,Bucket内部的Candidate用Doubly Linked List链接起来,Bucket之间也用Doubly Linked List链接起来。这样针对+1运算,我们只需要通过Hash表找到对应的Candidate,把Candidate从当前的Bucket移动到下一个Bucket(出现次数+1的Bucket)。另外,对于所有数-1的操作,我们记录全局的一个Base,每次-1操作,则Base+1。如果Base和Buckets中的第一个Bucket中的Candidates的出现次数相同,则整个删除第一个Bucket。最后,我们会得到最大k-1个Candidates,重新遍历一遍整个数组,用O(k)的Hash记录这k-1个Candidates的出现次数,就可以验证谁是真正的主元素。

     

  • 相关阅读:
    vue的特点
    暴力卸载低版本vuecli
    C#实现汉字转换为拼音缩写的代码
    .net 发送手机短信息
    js 小小jquery等比例缩放图片效果
    Android应用程序运行机制解析
    大型网站的架构设计问题大型高并发高负载网站的系统架构
    《UDP原理》
    《计算机网络中port和socket的作用》
    《线程并发》
  • 原文地址:https://www.cnblogs.com/bbbblog/p/4915270.html
Copyright © 2011-2022 走看看