The sword refers to the Offer-29-java implementation of finding elements that appear more than half of the times in an array

Idea:
There is a number in the array that appears more than half the length of the array, which means it appears more times than all other numbers combined.
So we can consider saving two values ​​when traversing the array: one is a number in the array, and one is the number of times. When we traverse to the next number, if the next number is the same as the number we saved before, the number is increased by 1; if the next number is different from the number we saved before, the number is decreased by 1. If the count is zero after subtracting 1, we need to save the next number and set the count to 1. Since the number we're looking for occurs more times than all other numbers combined, the number we're looking for must be the corresponding number for which the last count was set to 1.

java specific implementation:

/**
 * 找出数组中出现次数超过一半的数字 
 * 算法实现思想,定义两个变量num,count,分别记录数字遍历中的数字,和计数器变量。
 * 将第一个元素取出来赋值给num,count初始值为1,然后遍历数组,依次和前面的num比较,
 * 如果相同,则count加1,如果不同则count减1,如果减去之后,count为0,则将当前数组赋值给num 然后count重置为1
 * 
 * 
 */
public class GetOffer {
    public static void main(String[] args) {
        int arr1[] = { 1, 2, 3, 2, 2, 2, 5, 4, 2 };
        int result1 = getNum(arr1);
        System.out.println(result1);
        int arr2[] = { 2, 2, 2, 2, 2, 1, 3, 4, 5 };
        int result2 = getNum(arr2);
        System.out.println(result2);
    }

    private static int getNum(int[] arr) {
        // 健壮性
        if (arr == null && arr.length < 1) {
            return -1;
        }
        int num = arr[0];
        int count = 1;
        // 遍历比较
        for (int i = 1; i < arr.length; i++) {
            if (num == arr[i]) {
                ++count;
            } else {
                count--;
                if (count == 0) {
                    num = arr[i];
                    count = 1;
                }
            }
        }
        // 判断num是不是目标数字
        count = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == num) {
                count++;
            }
        }
        if (count >= arr.length / 2) {
            return num;
        }
        return -1;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326231067&siteId=291194637