题目
力扣
思路一 排序
按攻击值从大到小排序,攻击值相同就按防御值从大到小排序。定义一个变量maxx记录当前最大的防御值。遍历properities,攻击值相同就放在一个组里讨论,用双指针遍历组内成员,如果左指针不是0,而且当前防御值小于maxx,就意味着这是一个弱角色。
代码一
class Solution {
public:
int numberOfWeakCharacters(vector<vector<int>>& properties) {
int n=properties.size(),ans=0,maxx=0;
sort(properties.begin(),properties.end(),[](const vector<int>& v1,const vector<int>& v2){
return v1[0]==v2[0] ? v1[1]>v2[1] : v1[0]>v2[0];
});
int l=0,r=0;
while(r<n){
maxx=max(properties[l][1],maxx);
l=r;
while(r<n && properties[l][0]==properties[r][0]){
if(l!=0 && maxx>properties[r][1])
ans++;
r++;
}
}
return ans;
}
};
另一个排序的思路
按攻击值从大到小排序,攻击值相同就按防御值从小到大排序。维护一个防御值最大的变量maxx。遍历properties,如果当前的防御值大于maxx,就意味着这是一个弱角色。
代码
class Solution {
public:
int numberOfWeakCharacters(vector<vector<int>>& properties) {
int n=properties.size(),ans=0,maxx=0;
sort(properties.begin(),properties.end(),[](const vector<int>& v1,const vector<int>& v2){
return v1[0]==v2[0] ? v1[1]<v2[1] : v1[0]>v2[0];
});
for(auto p:properties){
if(p[1]<maxx)
ans++;
else
maxx=p[1];
}
return ans;
}
};
思路二 单调栈
按攻击值从小到大排序,攻击值相同就按防御值从大到小排序。维护一个单调递增的栈,放入角色的防御值。遍历properities,如果当前角色的防御值大于栈顶元素,就说明这个栈顶元素对应的角色是一个弱角色。
代码二
class Solution {
public:
int numberOfWeakCharacters(vector<vector<int>>& properties) {
sort(properties.begin(),properties.end(),[](const vector<int>& v1,const vector<int>& v2){
return v1[0]==v2[0] ? v1[1]>v2[1] : v1[0]<v2[0];
});
stack<int> s;
int ans=0;
for(auto p:properties){
while(!s.empty() && s.top()<p[1]){
ans++;
s.pop();
}
s.push(p[1]);
}
return ans;
}
};