题目
1亿个球有1000种颜色,其中有一半的球是同一种颜色,采用一种方式能尽快的选出这个颜色。
思路
按照不同色的抵消思路,1亿个球放在A桶,B桶是个空桶,将A桶的球一个一个转移到B桶,如果放进桶里颜色的球不同,就清除该色的球,剩余的桶里的球就是这个颜色
解法
#include <iostream>
#include <vector>
using namespace std;
int getColor(vector<int> boll) {
if (boll.size() == 0) return -1;
int color = -1, colorCnt = 0;
for (int i = 0; i < boll.size(); i++) {
if (colorCnt == 0) {
color = boll[i];
colorCnt++;
} else {
if (color != boll[i]) {
colorCnt--;
}
}
}
return color;
}
int main() {
vector<int> boll{1,2,3,4,5,1,1,1,1,1,1,1,6,7,8,6,6,6,6,6,6,6,6,6,6,66,6,6,6,6,6,6,6,6};
cout << getColor(boll) << endl;
return 0;
}