首页 > 其他 > 详细

Majority Element Leetcode

时间:2017-01-15 09:03:05      阅读:203      评论:0      收藏:0      [点我收藏+]

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.

 

1.

hashmap的方法,此方法需要注意的就是可以在loop里面就判断返回了,不用iterator。因为最后一个加完之后major肯定是大于n/2的。

public class Solution {
    public int majorityElement(int[] nums) {
        HashMap<Integer, Integer> h = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (h.containsKey(nums[i])) {
                h.put(nums[i], h.get(nums[i]) + 1);
            } else {
                h.put(nums[i], 1);
            }
            if (h.get(nums[i]) > nums.length/2) {
                    return nums[i];
            }
        }
        return 0;
    }
}

2.

神奇的算法。。。

public class Solution {
    public int majorityElement(int[] nums) {
        int major = nums[0];
        int count = 1;
        for (int i = 1; i < nums.length; i++) {
            if (count == 0) {
                count++;
                major = nums[i];
            } else if (major == nums[i]) {
                count++;
            } else {
                count--;
            }
        }
        return major;
    }
}

3.

可以排序之后返回中间值。

4.

还有bit manipulation的没做,到时候回顾一下。。。

 

Majority Element Leetcode

原文:http://www.cnblogs.com/aprilyang/p/6286581.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!