LeetCode No.169 Majority Element | #Hashmap #Boyer–Moore majority vote algorithm

Q:

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that the array is non-empty and the majority element always exist in the array.

A:

使用Hashmap最基本的思路。

public int majorityElement(int[] nums) {
    Map myMap = new HashMap();
    //Hashtable myMap = new Hashtable();
    int target = 0;
    for (int num: nums) {
        if (!myMap.containsKey(num))   //如果出现一个数之前不在map里
            myMap.put(num, 1);     //放进去 <原值,计数>
        else
            myMap.put(num, myMap.get(num)+1);  //如果存在,计数+1

        if (myMap.get(num)>nums.length/2) {   
            target = num;
            break;                //不一定traverse整个nums,也许结果就出来了
        }
    }
    return target;
}

BoyerMoore majority vote algorithm
基本思路:最初设置两个值,一个target,一个count,分别进行统计。target从选取nums[0]开始,每当计数变成0的时候,target值就会换。其实可以按“消除”的想法去理解,比如target值是3,连续出现了四次,那么这个时候count=4,但是连续又连续出现了五次不是3的值,那么count不仅被清0了,而且target的值也被替换了,从新开始统计。到最后,都“消除”完了,还能成为target,说明具有数量上的优势,也就是我们要找的“大量”、“总数过半”的值。


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

    return target;
}

test case: {5,4,3,3,7,3,1,3,3} total: 9,length:9

target count point to index (i) point to value (num[i])
5 1 1 4
5 0 2 3
3 1 3 3
3 2 4 7
3 1 5 3
3 2 6 1
3 1 7 3
3 2 8 3

同样的算法,下面这个代码更好:

public int majorityElement(int[] nums) {
    int target = 0, count = 0;
    for (int num: nums) {
        if (count == 0)
            target = num;    //每次target值被赋值替换完,下面的判断直接进行计数累加,0-->1
        
        if (num != target)
            count --;
        else
            count ++;
    }
    return target;
}

test case: {5,4,3,3,7,3,1,3,3} total: 9,length:9

major count point to index (i) point to value (num[i])
0 0 0 5
5 1 1 4
5 0 2 3
3 1 3 3
3 2 4 7
3 1 5 3
3 2 6 1
3 1 7 3
3 2 8 3

注:
两个表格,得出的结果一样,只不过起点不一样。
表格前两列是(再次)进入for循环之前的值,后两列是进入for之后要与前两列去比较的值,比较完之后,根据判断语句得出的结果,写入下一行的前两列。

你可能感兴趣的:(LeetCode No.169 Majority Element | #Hashmap #Boyer–Moore majority vote algorithm)