AC代码:
#include<cstdio> #include<vector> #include<algorithm> using namespace std; class Gift { public: int getValue(vector<int> gifts, int n) { if(gifts.size()==0 || n<=0) return 0; // if(gifts.size()!=n) return 0; // 此语句有无,在牛客网oj上均能通过,按道理应加上的... sort(gifts.begin(),gifts.end()); int countMid=0, res; for(int i=0; i<gifts.size();i++) { if(gifts[i] >= gifts[n/2]) countMid++; } if(countMid>n/2) res=gifts[n/2]; else res=0; return res; } }; // 以下为测试 int main() { Gift sol; int n1=5; vector<int> gifts1={1,2,3,2,2}; int res1=sol.getValue(gifts1, n1); printf("%d\n",res1); return 0; }
AC代码:
#include<cstdio> #include<vector> #include<algorithm> using namespace std; class Gift { public: int getValue(vector<int> gifts, int n) { if(gifts.size()==0 || n<=0) return 0; // if(gifts.size()!=n) return 0; // 此语句有无,在牛客网oj上均能通过,按道理应加上的... sort(gifts.begin(),gifts.end()); int countMid=0, res; for(int i=0; i<gifts.size();i++) { if(gifts[i] >= gifts[n/2]) countMid++; } if(countMid>n/2) res=gifts[n/2]; else res=0; return res; } }; // 以下为测试 int main() { Gift sol; int n1=5; vector<int> gifts1={1,2,3,2,2}; int res1=sol.getValue(gifts1, n1); printf("%d\n",res1); return 0; }
提交网址: https://leetcode.com/problems/majority-element/
Total Accepted: 113359 Total Submissions: 273577 Difficulty: Easy Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
AC代码:
class Solution { public: int majorityElement(vector<int>& numbers) { int len=numbers.size(); if(len==0) return 0; sort(numbers.begin(),numbers.end()); int countMid=0, res; for(int i=0; i<numbers.size();i++) { if(numbers[i] == numbers[len/2]) countMid++; } if(countMid>len/2) res=numbers[len/2]; else res=0; return res; } };