牛客编程巅峰赛水题

Powered by:AB_IN 局外人

真的挺适合我这种小白的。

循环右移

记一下按权相加法

class Solution {
public:
    long long rotateRight(string str, int k) {
        // write code here
        long long ans=0;
        int n=str.size();
        for(int i=n-k;i<n;i++){
            ans=ans*2+(str[i]-'0');
        }
        for(int i=0;i<n-k;i++){
            ans=ans*2+(str[i]-'0');
        }
        return ans;
    }
};

如果想调用类,可以这样

Solution solution;
cout<<solution.rotateRight("01111",2);

牛牛的01游戏

一个的操作,先进后出。
注意的是调用类:

在我们定义函数和类的时候,在第一个参数的位置默认应该添加 s e l f self ,例如 s o l v e ( s e l f , s t r ) solve(self , str ) ,然后我们在调用的时候应该首先实例化这个类,如 S o l u t i o n ( ) . s o l v e ( s ) Solution().solve(s) ,而非直接调用 S o l u t i o n . s o l v e ( s ) Solution.solve(s)

class Solution:
    def solve(self , str ):
        # write code here
        lst=[str[0]]
        for i in str[1:]:
            if i=='0':
                if lst and lst[-1]=='0':
                    lst.pop()
                    if lst and lst[-1]=='1':
                        lst.pop()
                    else:
                        lst.append("1")
                else:
                    lst.append("0")
            else:
                if lst and lst[-1]=='1':
                    lst.pop()
                else:
                    lst.append("1")      
        return "".join(lst)
print(Solution().solve("00110"))

牛牛爱奇数

s e t set 去重并标记即可。
当然也可以用 m a p map 标记。

class Solution:
    def solve(self , n , a ):
        s = set()
        for i in a:
            while i%2==0 and i not in s:
                s.add(i)
                i = i>>1
        return len(s)

也可以用堆。

class Solution
{
	public:
		int solve(int n,vector<int> &a)
		{
			priority_queue<int> q;
			int t=0;
			for(int i=0;i<n;i++)
                if(a[i]%2==0)
                    q.push(a[i]);
			while(!q.empty())
			{
				int p=q.top();
				while(q.top()==p&&!q.empty())
                    q.pop();
				p/=2;
				t++;
				if(p%2==0) q.push(p);
			}
			return t;
		}
};

猜你喜欢

转载自blog.csdn.net/qq_45859188/article/details/108006997
今日推荐