数组-多数元素

231 阅读1分钟

给定一个大小为 n 的数组 nums ,返回其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。 你可以假设数组是非空的,并且给定的数组总是存在多数元素。

来源:力扣(LeetCode) 链接:leetcode.cn/problems/ma… 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

排序法

public static int majorityElement(){
    int[] ints = {2,2,1,1,1,2,2};
    Arrays.sort(ints);
    int index = ints.length/2;
    return ints[index];
}

投票法:相同加一,不同减一,票数为零切换候选人

public static int majorityElement() {
    int[] ints = {2, 1, 1, 1, 1, 2, 2};
    int vote = 1;
    int candidate = ints[0];
    for (int value : ints) {
        if (value == candidate) {
            vote++;
        } else if (--vote == 0) {
            candidate = value;
            vote = 1;
        }
    }
    return candidate;
}