主元素

原题

  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;
    }
}
相关文章
相关标签/搜索