Given an array of size n, find the majority element. Themajority element is the element that appears more than ? n/2
? times.
You may assume that the array is non-empty and the majority element alwaysexist in the array.
Credits:
Special thanks to @ts for adding this problem and creating all testcases.
HideTags
Divide and Conquer Array Bit
Manipulation
#pragma once #include<iostream> #include<vector> #include<algorithm> using namespace std; //法1:排序,返回中间数 int majorityElement1(vector<int> &num) { sort(num.begin(), num.end()); return num[num.size() / 2]; } //法2:多数投票,每找到一对不同的数,就成对删除。 int majorityElement2(vector<int> &num) { int count = 1; int element = num[0];//题设num非空 for (int i = 1; i < num.size(); i++) { if (count == 0) { element = num[i]; count = 1; continue; } if (num[i] == element) count++; else count--; } return element; } void main() { vector<int> v = { 1,1,1,1,2,2,2 }; //vector<int>::iterator begain, end; /*sort(v.begin(), v.end()); for (int i = 0; i < v.size(); i++) cout << v[i] << ' ';*/ cout << majorityElement2(v) << endl; system("pause"); }
时间: 2024-11-10 01:18:53