把0换到开头,判有没有排序;注意反转2次可以右旋``` class Solution { public: int minOperations(vector<int>& v) { #define L v.begin() #define R v.end() int p0=find(L,R,0)-L,n=v.size(); rotate(L,L+p0,R); if(is_sorted(L,R))retu
- AI
- AI最多操作三次(右左右)``` class Solution { public: int dfs(int d,string s,int l,int r){ if(d>=3)return 3; if(l||r)sort(s.begin()+l,s.end()-r); if(is_sorted(s.begin(),s.end()))return d; if(s.size()==2)return -1;
- AI贪心,用nth_element求第k大可以做到O(n)``` class Solution { public: long long maxAlternatingSum(vector<int>& v) { long long res=0,n=v.size(); for(auto &w:v){ w*=w; res+=w; } nth_element(v.begin(),v.begin()+n/2,v.
- AI按深度分别计算得分``` class Solution { public: int scoreOfParentheses(string s) { vector<int> f(55,0); int it=0; for(auto c:s){ if(c=='('){ it++; f[it+1]=0; } else{ f[it]+=max(1,f[it+1]*2); it--; } } return f[
- AI贪心地把左括号和右括号填满,如果是奇数就留个*``` class Solution { public: bool checkValidString(string s) { int n=s.size(),li=n/2,p=0; for(auto c:s)if(c=='(')li--; for(auto c:s){ if(c=='*'){ if(li>0)li--,c='('; else if(n&1