暑假算法7.14,Day13
模拟
第一题
class Solution {
public:
string addBinary(string a, string b) {
int t = 0;
reverse(a.begin(),a.end());
reverse(b.begin(),b.end());
string ans;
for(int i = 0;i < a.length() || i < b.length();i++)
{
if(i < a.length()){
t+=a[i]-'0';
}
if(i < b.length()){
t+=b[i]-'0';
}
if(t >=2)
{
ans += to_string(t%2);
t = 1;
}
else
{
ans += to_string(t);
t = 0;
}
}
if(t) ans+= '1';
reverse(ans.begin(),ans.end());
return ans;
}
};
第二题
这个题目在学校的oj上面也写过,直接把核心代码复制过来了。
不过也改了一些地方,把数组换成了vector容器,也是借鉴了群里一位大佬的博客
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
int top = 0, bottom = m-1, left = 0, right = n-1;
int cnt = m*n;
vector<int> res;
while(cnt>=1){
//从左到右
for(int j=left; j<=right && cnt>=1; j++, cnt--)
res.push_back(matrix[top][j]);
top++;
//从上到下
for(int i=top; i<=bottom && cnt>=1; i++, cnt--)
res.push_back(matrix[i][right]);
right--;
//从右到左
for(int j=right; j>=left && cnt>=1; j--, cnt--)
res.push_back(matrix[bottom][j]);
bottom--;
//从下到上
for(int i=bottom; i>=top && cnt>=1; i--, cnt--)
res.push_back(matrix[i][left]);
left++;
}
return res;
}
};
第三题
这个题太难了太难了,裂开。。
看了别人的代码。。。还不是很懂。
class Solution
{
public:
int robotSim(vector<int>& commands, vector<vector<int>>& obstacles)
{
set<pair<int, int>> st;
for(vector<int>&vec:obstacles)
{
st.insert(pair<int,int>(vec[0],vec[1]));
}
int dx[4]= {0,1,0,-1};
int dy[4]= {1,0,-1,0};
int i=0;
int max_len=0;
int x=0;
int y=0;
for(int& com:commands)
{
if(com==-1)
{
i=(i+1)%4;
}
else if(com==-2)
{
i=(i+3)%4;
}
else
{
for(int s=0; s<com; ++s)
{
if(!st.count(pair<int,int>(x+dx[i],y+dy[i])))
{
x+=dx[i];
y+=dy[i];
max_len=max(max_len,x*x+y*y);
}
else
{
break;
}
}
}
}
return max_len;
}
};
第四题
不说了,上一题整自闭了…摆烂吧…,这题就简单的模拟就行,0和9特判一下,其余的要么++
要么--
。
#include <bits/stdc++.h>
using namespace std;
int main()
{
int N;
cin>>N;
while(N--)
{
int n;
cin>>n;
int a[n+5];
for(int i=0; i<n; i++)
{
cin>>a[i];
}
string str;
for(int i=0; i<n; i++)
{
string str2;
int m;
cin>>m>>str2;
int cnt=a[i];
for(int j=0; j<m; j++)
{
if(str2[j]=='U')
{
cnt--;
if(cnt==-1)
{
cnt=9;
}
}
else
{
cnt++;
if(cnt==10)
{
cnt=0;
}
}
}
str+=cnt+'0';
}
for(int i=0; i<str.size(); i++)
{
cout<<str[i]<<' ';
}
cout<<endl;
}
return 0;
}
今天真的很裂开...摆烂一天,也让自己休息一天吧。
人们总说以后会变好的,可是好的以后也是需要你自己争取来的呀!!