找出数组中的主要元素(leetcode169)

2018-11-24  本文已影响0人  zhouwaiqiang

题目

解题思路1

解题思路2

解题思路3

代码三

class Solution {
    public int majorityElement(int[] nums) {
        Arrays.sort(nums);
        return nums[nums.length/2];
    }
}

解题思路4(参考官方思路,没想到的方法)

代码实现

class Solution {
    public int majorityElement(int[] nums) {
        int candidates = nums[0];
        int times = 0;
        for (int num : nums) {
            if (times == 0) candidates = num;
            times += (num == candidates) ? 1 : -1;
        }
        return candidates;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读