More than half of the number of digital leetcode 1517 array appears

There are a number of array number that appears more than half the length of the array, find the numbers (assuming that the figure was k).

O (n) approach: setting a target, if the array is equal to the value of the target, then count ++, otherwise count--, if the count is 0 update this value.

So we assume the worst case, each time the count is 0, at least half of k and k are other than offset, then the last must also exist a k can be marked as target.

 1 class Solution {
 2 public:
 3     int majorityElement(vector<int>& nums) {
 4       int target;
 5       int count=0;
 6       for(int i=0;i<nums.size();i++)
 7       {
 8           if(count==0)
 9           {
10               target=nums[i];
11           }
12           if(nums[i]==target)
13            count++;
14            else
15            count--;
16       }
17       return target;
18     }
19 };

 

Guess you like

Origin www.cnblogs.com/Carits/p/12391546.html