美文网首页
169. Majority Element

169. Majority Element

作者: DrunkPian0 | 来源:发表于2017-07-20 23:17 被阅读6次

我用了O(nlogn)的方法。
或者可以用Hashmap记录出现次数。

据说有更好的方法叫投票法。

    //先sort,再遍历,遇到个数大于n了,返回它
    public int majorityElement(int[] nums) {
        if (nums.length == 1) return nums[0];
        Arrays.sort(nums);
        int count = 1;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] != nums[i - 1]) {
                count = 1;
            } else {
                count++;
            }
            if (count > nums.length / 2) return nums[i];
        }
        return -1;
    }

相关文章

网友评论

      本文标题:169. Majority Element

      本文链接:https://www.haomeiwen.com/subject/fjfskxtx.html