首页 > 学院 > 开发设计 > 正文

169. Majority Element--寻找数组中出现次数超过一半的数据

2019-11-08 03:24:49
字体:
来源:转载
供稿:网友

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; }
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表