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. 方法一、由于出现一半的数字,则即寻找第middle大的数字,可以基于快速排序的partition的思想,然后找出第Middle大的数字,代码此处省略; 方法二、hash的方法; 方法三、基于出现次数超过一半的数据的特征,代码如下:
int majorityElement(vector<int>& nums) { if(nums.size()<=0) return -1; int count = 1; int result = nums[0]; for(int i = 1; i < nums.size(); i++){ if(count == 0){ result = nums[i]; count = 1; } else if(nums[i] == result){ count++; } else{ count--; } } return result; }新闻热点
疑难解答