# 寻找多数元素（leetcode169）

    int candidate(vector<int>& nums, int m)
{
int j = m, n = nums.size(), cnt = 1, c = nums[m];
while(j < n-1 && cnt > 0)
{
j++;
if(nums[j] == c) cnt++;
else cnt--;
}
if(j == n-1)  return c;
else return candidate(nums, j+1);
}
int majorityElement(vector<int>& nums) {
return candidate(nums, 0);
}

    int majorityElement(vector<int>& nums) {
int res, cnt = 0;
for(int num: nums)
{
if(cnt == 0)
{
res = num;
cnt = 1;
}
else
{
if(num == res) cnt++;
else cnt--;
}
}
return res;
}

    int majorityElement(vector<int>& nums) {
int res = 0, n = nums.size();
for (int i = 0; i < 32; ++i) {
int ones = 0, zeros = 0;
for (int num : nums) {
if (ones > n / 2 || zeros > n / 2) break;
if (num & (1 << i)) ++ones;
else ++zeros;
}
if (ones > zeros) res |= (1 << i);
}
return res;
}

    int majorityElement(vector<int>& nums) {
unordered_map<int, int>mp;
int n = nums.size();
for(int i = 0;i < n;i++)
{
int tmp = ++mp[nums[i]];
if(tmp > n/2) return nums[i];
}
return -1;
}

posted @ 2020-03-14 13:22  Rogn  阅读(205)  评论(0编辑  收藏