Majority Element

来源:互联网 发布:查看ip端口是否打开 编辑:程序博客网 时间:2024/05/29 18:35

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.

class Solution {  public:      int majorityElement(vector<int>& nums) {          int count = 0;          int elem = 0;          for(int i = 0;i < nums.size(); i++)          {              if(count == 0)              {                  elem = nums[i];                  count++;              }              else              {                  elem == nums[i]? count++ : count--;              }          }          if(count > 0)          return elem;      }  };  
  • 给定数组必然有某个元素出现的次数占据一半以上,从数组中取出一对不相同的元素。
  • 若这两个元素都不是目标元素,取出它们两个之后,目标元素仍然会占据多一半;若这两个元素中有一个是目标元素,取出它们两个之后,目标元素还是会占据多一半。
  • 重复上一个步骤,不同则删去,最后剩下的元素就是目标元素。
0 0
原创粉丝点击