classSolution{public:intcountElements(vector<int>& nums){sort(nums.begin(), nums.end());int n = nums.size();if(n <=2)return0;if(nums[0]== nums[n -1])return0;int ans = n -2;for(int i =1; i < n; i++){if(nums[i]== nums[0]) ans--;}for(int i = n -2; i >=0; i--){if(nums[i]== nums[n -1]) ans--;}return ans;}};
2.双指针模拟
classSolution{public:
vector<int>rearrangeArray(vector<int>& nums){int zheng =0, fu =0;int n = nums.size();
vector<int> ans;for(int i =0; i < n; i++){if(nums[i]>0){
zheng = i;break;}}for(int i =0; i < n; i++){if(nums[i]<0){
fu = i;break;}}//cout << zheng << " " << fu << endl;int need =1;while(zheng < n || fu < n){if(need ==1){
ans.push_back(nums[zheng]);
zheng++;while(zheng < n && nums[zheng]<0) zheng++;
need =-1;}else{
ans.push_back(nums[fu]);
fu++;while(fu < n && nums[fu]>0) fu++;
need =1;}}return ans;}};
3.哈希表
classSolution{public:
vector<int>findLonely(vector<int>& nums){int n = nums.size();
vector<int> ans;if(n ==1)return nums;
unordered_map<int,int> m;for(auto& x : nums){
m[x]++;}for(auto x : m){if(x.second ==1&&!m.count(x.first -1)&&!m.count(x.first +1)) ans.push_back(x.first);}return ans;}};
4.枚举
typedef pair<int,int> PII;classSolution{public:int ff =0;int n;
vector<vector<int>> state;boolcheck(int man, vector<int>& s){for(int j =0; j < n; j++){if(state[man][j]!=2){if(state[man][j]!= s[j])returnfalse;}}returntrue;}voiddfs(vector<int> s,int start,int sum){if(ff)return;if(sum ==0){for(int i =0; i < n; i++){if(s[i]==1){if(!check(i, s))return;}}
ff =1;return;}for(int i = start; i < n; i++){
s[i]=1;dfs(s, i +1, sum -1);
s[i]=0;}}intmaximumGood(vector<vector<int>>& statements){
state = statements;
n = statements.size();
vector<int>d(n,0);
vector<int>s(n,0);for(int nn = n; nn >=0; nn--){dfs(s,0, nn);if(ff ==1)return nn;}return0;}};