Saturday, January 3, 2015

Majority Element

Q:
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.

A:
就是每次dump两个不同的数字。

public class Solution {
    public int majorityElement(int[] num) {
        int a = num[0], aCount = 1; // first let b point to a value NOT a
        for(int i = 1;i<num.length;i++){
            if(num[i]==a){
                aCount++;
            }else{ // if these two are not equal
                aCount--;
                if(aCount==0){
                    i++;
                    a=num[i]; // because it must exist, so num[i] is within range
                    aCount=1;
                }
            }
        }
        return a;
    }
}

用两个地址,记录不同的位置

public class Solution {
    public int majorityElement(int[] nums) {
        int i1= 0;
        for(int i2=0; i2 < nums.length;i2++){
            if(nums[i2] != nums[i1]){
                int val = nums[i1];
                i1++;
                // i1 till not equal
                while(i1<= i2 && nums[i1] != val){
                    i1++;
                }
            }
        }
        return nums[i1];
    }
}


Mistakes:















No comments:

Post a Comment