标签:time item length ret 否则 语言 超过 int subject
时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
class Solution { public: int MoreThanHalfNum_Solution(vector<int> numbers) { if(numbers.empty()) return 0; sort(numbers.begin(),numbers.end()); int middle = numbers[numbers.size() / 2]; int count = 0; for(int i = 0;i < numbers.size();i++) { if(numbers[i] == middle) count++; } return (count > numbers.size()/2) ? middle:0; } };
class Solution { public: int MoreThanHalfNum_Solution(vector<int> numbers) { if(numbers.empty()) return 0; //遍历每个元素,并记录次数;若与前一个元素相同,则次数加1,否则次数减一 int result = numbers[0]; int times = 1; for(int i = 1;i < numbers.size();i++) { if(times == 0) { result = numbers[i]; times ++; } else if(numbers[i] == result) { times++; } else times--; } //判断result是否符合条件 times = 0; for(int i = 0;i < numbers.size();i++) { if(numbers[i] == result)times++; } return (times>numbers.size()/2)? result:0; } };
标签:time item length ret 否则 语言 超过 int subject
原文地址:https://www.cnblogs.com/whiteBear/p/12577238.html