我的第五次LeetCode周赛
心情
题目在此
这次题目不难,但是代码一些细节问题,导致我有思路代码老是有问题😭
第一题(作为子字符串出现在单词中的字符串数目)
没啥好说的,就是直接暴力判断,时间充足。
C++代码
class Solution {
public:
int numOfStrings(vector<string>& p, string word) {
int n = p.size();
int res = 0;
for (int i = 0; i < n; i ++){
int le = word.size(),le1 = p[i].size();
if (le < le1)continue;
for (int j = 0; j < le; j ++){
int f = 1;
if (p[i][0]==word[j]){
int k,m;
for (k = 0,m = j; k < le1&&m < le; k ++,m ++){
if (p[i][k]!=word[m]){
f = 0;
break;
}
}
if (k < le1)continue;
if (f){
res++;
break;
}
}
}
}
return res;
}
};
Java代码
C++代码太繁琐了,比赛忘了用Java了,代码少好用
class Solution {
public int numOfStrings(String[] patterns, String word) {
int res = 0;
for (String st:patterns){
if (word.indexOf(st)!=-1)res++;
}
return res;
}
}
第二题(构造元素不等于两相邻元素平均值的数组)
构造题:先排序,然后依次将一个最小的和一个最大的加入数组中
class Solution {
public:
vector<int> rearrangeArray(vector<int>& nums) {
int n = nums.size();
sort(nums.begin(),nums.end());
vector<int> res;
if (n%2==0){
for (int i = 0,j = n-1; i < n/2; i ++,j --){
res.push_back(nums[i]);
res.push_back(nums[j]);
}
}else {
for (int i = 0,j = n-1; i < n/2; i ++,j --){
res.push_back(nums[i]);
res.push_back(nums[j]);
}
res.push_back(nums[n/2]);
}
return res;
}
};
第三题(数组元素的最小非零乘积)
这题暴力找规律,但是我被自己的傻逼坑死了,规律就是(2^p - 2)^( 2^(p-1)-1)*(2 ^ p-1)。我每一步都用的快速幂,最后一步乘我用的是龟速乘,但是结果就是不对,我到现在都不知道为什么。
下面代码用的是其他方式。
typedef long long ll;
const int mod = 1e9+7;
class Solution {
public:
ll fp(ll b, ll p) {
ll r = 1;
while (p > 0) {
if (p & 1) {
r = r*b%mod;
}
p >>= 1;
b = b*b%mod;
}
return r;
}
int minNonZeroProduct(int p) {
ll res = ((1ll << p) - 1)%mod; //位运算
ll cnt = fp(res-1,(1ll << (p-1)) - 1); //用了一次快速幂
return res * cnt % mod; //直接乘
}
};
第四题(你能穿过矩阵的最后一天)
这一题最是无语,赛后写的。
题意:一个二维图,0表示陆地,1表示海洋,人只能在陆地上走,一天能行走在陆地任何地方,就是问你能穿过矩阵的最后一天。
把m写成n了,改了好久。
二分加bfs 类似题目
ps: 是否存在类问题,最好用dfs,找到一种就可以。
class Solution {
public:
int latestDayToCross(int n, int m, vector<vector<int>>& cs) {
int l = 0,r = n * m;
while(l < r){
int mid = (l + r + 1) >> 1;
vector<vector<int>> g(n+1,vector<int>(m+1,0));
vector<vector<int>> vis(n+1,vector<int>(m+1,0));
vector<vector<int>> pos = {{0,-1},{1,0},{0,1},{-1,0}};
queue<pair<int,int>> q;
for (int i = 0; i < mid; i ++){
int x = cs[i][0],y = cs[i][1];
g[x][y] = 1;
}
for (int i = 1; i <= m; i ++){
if (!g[1][i]){
q.push(pair<int,int>(1,i));
vis[1][i] = 1;
}
}
bool ok = false;
while(!q.empty()){
int xx = q.front().first,yy = q.front().second;
if (xx == n)ok = true;
q.pop();
for (int i = 0; i < 4; i ++){//这里我一开始用的是auto一直有2个点超市,快哭死了
int x = xx + pos[i][0],y = yy + pos[i][1];
if (x < 1 || x > n|| y < 1 || y > m)continue;
if (vis[x][y])continue;
if (g[x][y])continue;
q.push(pair<int,int>(x,y));
vis[x][y] = 1;
}
}
if (ok)l = mid;
else r = mid-1;
}
return l;
}
};