數(shù)組中出現(xiàn)次數(shù)超過一般的數(shù)字

//數(shù)組中出現(xiàn)次數(shù)超過一般的數(shù)字
public class MoreThanHalfNum {

// 判斷數(shù)組是否為空
public static boolean checkInvalidArray(int[] numbers) {
    if (numbers == null || numbers.length == 0)
        return true;
    return false;
}

// 基于快速排序算法的partition函數(shù)
public static int partition(int[] numbers, int left, int right) {
    int result = numbers[left];
    if (left > right) {
        return -1;
    }
    while (left < right) {
        while (left < right && numbers[right] >= result) {
            right--;
        }
        numbers[left] = numbers[right];
        while (left < right && numbers[left] < result) {
            left++;
        }
        numbers[right] = numbers[left];
    }
    numbers[left] = result;
    return left;
}

// 判斷中間的元素出現(xiàn)的次數(shù)是否超過數(shù)組長度的一半
public static boolean checkMoreThanHalf(int[] numbers, int length, int result) {
    int times = 0;
    for (int i = 0; i < length; i++) {
        if (numbers[i] == result) {
            times++;
        }
    }
    if (times * 2 > length)
        return true;
    return false;
}

// 找出數(shù)組的中位數(shù),并放到中間位置 基于Partition函數(shù)的O(n)算法
public static int moreThanHalfNum(int[] numbers) {
    if (checkInvalidArray(numbers))
        return 0;
    int length = numbers.length;
    int middle = length / 2;
    int start = 0;
    int end = length - 1;
    int index = partition(numbers, start, end);
    while (index != middle) {
        if (index > middle) {
            end = index - 1;
            index = partition(numbers, start, end);
        } else {
            start = index + 1;
            index = partition(numbers, start, end);
        }

    }
    int result = numbers[middle];
    if (!checkMoreThanHalf(numbers, length, result)) {
        return 0;
    }
    return result;

}

// 根據(jù)數(shù)組特點(diǎn)求出O(n)的算法
public static int moreThanHalfNum2(int[] numbers) {
    if (checkInvalidArray(numbers))
        return 0;
    int result = numbers[0];
    int times = 1;
    for (int i = 1; i < numbers.length; i++) {
        if (times == 0) {
            result = numbers[i];
            times = 1;
        } else {
            if (numbers[i] == result) {
                times++;
            } else {
                times--;
            }
        }
    }
    if (!checkMoreThanHalf(numbers, numbers.length, result)) {
        return 0;
    }
    return result;
}

public static void main(String[] args) {
    int[] numbers = { 3, 3, 3, 3, 2, 2, 1 };
    System.out.println(moreThanHalfNum(numbers));
    System.out.println(moreThanHalfNum2(numbers));
}

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容