主元素

原題

  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.算法

題目大意

  給定一個數組,找這個數組中的主元素,主元素是元素出現次數大於⌊ n/2 ⌋的元素。
  假設給定的數組非空,主元素都存在。數組

解題思路

  用一個標記cnt記錄某個元素出現的次數,若是後面的元素和它相同就加一,有一個元素和他不相同就減一,當cnt小於等於0時從新記錄新的元素。app

代碼實現

算法實現類spa

public class Solution {
    public int majorityElement(int[] num) {
        int main = num[0]; // 用於記錄主元素,假設第一個是主元素
        int count = 1; // 用於抵消數的個數

        for (int i = 1; i < num.length; i++) { // 從第二個元素開始到最後一個元素
            if (main == num[i]) { // 若是兩個數相同就不能抵消
                count++; // 用於抵消的數據加1
            } else {
                if (count > 0) { // 若是不相同,而且有能夠抵消的數
                    count--; // 進行數據抵消
                } else { // 若是不相同,而且沒有能夠抵消的數
                    main = num[i]; // 記錄最後不能夠抵消的數
                }
            }
        }

        // 對於數組中可能沒有主元素的狀況,題中說明存在,此步能夠省略。
//        count = 0;
//        for (int a : num) {
//            if (a == main) {
//                count++;
//            }
//        }
//
//        if (count >= num.length / 2) {
//            return main;
//        } else {
//            throw new RuntimeException("No majority element");
//        }

        return main;
    }
}
相關文章
相關標籤/搜索