Jianzhi - Numbers that appear more than half of the time in the array - hashmap practice

topic description

There is a number in the array that occurs more than half of the length of the array, please find this number. For example, input an array {1,2,3,2,2,2,5,4,2} with a length of 9. Since the number 2 appears 5 times in the array, which exceeds half the length of the array, 2 is output. Output 0 if not present.

train of thought

1. Practice the use of HashMap, and the statistics are over;
2. Sort, take the median;
3. Invincible-Moore voting method.

Moore voting method:
Sum of votes: Since the number of times the mode appears exceeds half of the length of the array; if the number of votes for the mode is +1 and the number of votes for the non-moderate is −1, then there must be a sum of votes of all numbers > 0.

Positive and negative offset of votes: Let the mode of the array nums be x and the length of the array be n. If the sum of votes of the first a numbers of nums = 0, then the sum of votes of the last (na) numbers in the array must still be >0 (that is, the mode of the last (na) numbers is still x).

It's a very clear idea, and it's true.

the code

1. HashMap practice.

import java.util.HashMap;
import java.util.Map;

class Solution {
    
    
	public static int majorityElement(int[] nums) {
    
    
        // 创建hashmap, 数-次数
		HashMap<Integer, Integer> hash = counter(nums);
        // 遍历,选出长度大于一半的
		int res = MapEntry(hash, nums);
		return res;
	}

	public static HashMap<Integer, Integer> counter(int[] nums) {
    
    
		HashMap<Integer, Integer> count = new HashMap<Integer, Integer>();
		for (int num : nums) {
    
    
			if (count.containsKey(num)) {
    
    
				int old_v = count.get(num);
				count.put(num, old_v + 1);
			} else {
    
    
				count.put(num, 1);
			}
		}
		return count;
	}

	public static int MapEntry(HashMap<Integer, Integer> hashmap, int[] nums) {
    
    

		int res = 0;
		for (Map.Entry<Integer, Integer> entry : hashmap.entrySet()) {
    
    
			
			if (entry.getValue() > (nums.length / 2)) {
    
    
				res = entry.getKey();
			}
		}
		return res;
	}
}

2. Don't write the sorting;
3. Moore voting method

class Solution {
    
    
    public int majorityElement(int[] nums) {
    
    
        int x = 0, votes = 0;
        for(int num : nums){
    
    
            if(votes == 0) x = num;
            votes += num == x ? 1 : -1;
        }
        return x;
    }
}

Guess you like

Origin blog.csdn.net/qq_32301683/article/details/108503321