Majority Element

Majority Element(169)

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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

Subscribe to see which companies asked this question.

Show Tags

Show Similar Problems

思路:摩尔投票算法

public class Solution {
    public int majorityElement(int[] nums) {
        if(nums.length==1) return nums[0]; 
        int tmp=nums[0] ;
        int count=1;
        for(int i=1;i

Majority Element II(229)

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

Subscribe to see which companies asked this question.

public class Solution {
    public List majorityElement(int[] nums) {
        if (nums == null || nums.length == 0)
            return new ArrayList();
        int x=nums[0];
        int y=nums[0];
        int cx=0;
        int cy=0;
        for(int i=0;i list=new ArrayList();
        if(cx>nums.length/3)
            list.add(x);
        if(cy>nums.length/3)
            list.add(y);
        return list;
        
    }
}

you can just use an array if it is a n/k question. it will be something like this...

public class Solution {
    public List majorityElement(int[] nums) {
        int n = nums.length, k = 3;  //in this question, k=3 specifically
        List result = new ArrayList();
        if (n==0 || k<2) return result;
        int[] candidates = new int[k-1];
        int[] counts = new int[k-1];
        for (int num: nums) {
            boolean settled = false;
            for (int i=0; i 0) ? (counts[i]-1) : 0;
        }
        Arrays.fill(counts, 0);
        for (int num: nums) {
            for (int i=0;in/k) result.add(candidates[i]);
        return result;
    }
}

你可能感兴趣的:(Majority Element)