码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]Divide and Conquer-169. Majority Element

时间:2018-01-13 21:01:18      阅读:18      评论:0      收藏:0      [点我收藏+]

标签:special   ++   appears   use   span   may   edits   array   edit   

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

标签:special   ++   appears   use   span   may   edits   array   edit   

原文地址:https://www.cnblogs.com/chenhan05/p/8280257.html

(0)
(0)
   
举报
评论 一句话评论(0
0条  
登录后才能评论!
© 2014 mamicode.com 版权所有 京ICP备13008772号-2
迷上了代码!