好水的周赛啊,建议改名为Python赛
T1-设计 Goal 解析器
简单的字符串模拟题,别像我一样看到括号就栈栈栈qaq。
我是用Python replace搞的,这样会简洁不少,贴一个lc评论区C++简单模拟的。
Python
class Solution(object):
def interpret(self, command):
command = command.replace('()', 'o')
command = command.replace('(al)', 'al')
return command
C++
class Solution {
public:
string interpret(string command) {
string ans = "";
int i = 0;
int len = command.length();
while(i < len){
if(command[i] == '('){
if(command[i+1] == ')'){
ans += 'o';
i++;
}else {
ans += "al";
i += 3;
}
}else ans += command[i];
i++;
}
return ans;
}
};
// author:https://leetcode-cn.com/u/jh_z/
T2-K 和数对的最大数目
1e5,暴力模拟肯定是超时的,要想更简单的法子。
一种思路是排序双指针。先对整个序列进行排序,然后设左指针l=0,右指针r=nums.size()-1。如果当前nums[l]+nums[r]<k,说明左指针指向的数小了,左指针++,反之右指针++。这样就能准确无误的找到所有和为k的数对。
class Solution {
public:
int maxOperations(vector<int>& nums, int k) {
int ans = 0;
sort(nums.begin(), nums.end());
int l = 0, r = nums.size() - 1;
while(l < r) {
if(nums[l] + nums[r] == k)
ans++, l++, r--;
else if(nums[l] + nums[r] < k) {
l++;continue;
}
else {r--; continue;}
}
return ans;
}
};
T3-连接连续二进制数字
这题正解还没看懂,后续搞明白了会贴在下面。没想到阿里居然没有卡Python的常规直译写法,真是水啊
Python
class Solution(object):
def concatenatedBinary(self, n):
ss = ""
for i in range(1, n+1):
ss += str(bin(i)).replace('0b', '')
return int(ss, 2) % 1000000007