[leetcode]Divide and Conquer-169. Majority Element

Posted chenhan05

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode]Divide and Conquer-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.

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

 

int majorityElement(int* nums, int numsSize) {  
    if(numsSize == 0||numsSize == 1)  
        return *nums;  
      
    int x = majorityElement(nums,numsSize / 2);  
    int y = majorityElement(nums + numsSize / 2,numsSize - numsSize / 2);  
      
    if(x == y)  
        return x;  
      
    else  
    {  
        int countX = 0;  
        int countY = 0;  
          
        for(int i = 0;i < numsSize;i++)  
        {  
            if(*(nums + i) == x)  
                countX++;  
              
            else if(*(nums + i) == y)  
                countY++;  
        }  
          
        return countX > countY ? x : y;  
    }  
      
}  

 


以上是关于[leetcode]Divide and Conquer-169. Majority Element的主要内容,如果未能解决你的问题,请参考以下文章

[Leetcode] Binary search, Divide and conquer--240. Search a 2D Matrix II

[Leetcode] Heap, Divide and conquer--215. Kth Largest Element in an Array

#Leetcode# 29. Divide Two Integers

[LeetCode] 29. Divide Two Integers

LeetCode-29-Divide Two Integers

LeetCode每天一题Divide Two Integers(两整数相除)