LeetCode 169. Majority Element

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.

 利用了主元素大于一半的条件。每次从数组中取出元素,如果和暂存数组中的数相同就存进暂存数组,不同的话就“两个抵消”,最后剩下的一定是主元素

int majorityElement(int* nums, int numsSize) 
{
    
    int majorityElement=0;
    int *TmpArray;
    int j=-1;
    TmpArray = malloc(sizeof(int)*numsSize);
    for (int i=0; i<numsSize; i++)
    {
        if (j==-1)
        {
            TmpArray[++j] = nums[i];
        }else if (nums[i] == TmpArray[j])
        {
            TmpArray[++j] = nums[i];
        }else if (nums[i] != TmpArray[j])
        {
                TmpArray[j--] = -1;
        }
    }
    majorityElement = TmpArray[0];
    return majorityElement;

}

 

posted @ 2016-04-28 15:30  EvansYang  阅读(104)  评论(0编辑  收藏  举报