首页 > 代码库 > 169.Majority Element (法1排序法2多数投票)
169.Majority Element (法1排序法2多数投票)
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"); }
169.Majority Element (法1排序法2多数投票)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。