756. 蛇形矩阵
题解:
蛇形矩阵走法:右 -> 下 ->左 ->上
坐标变化:(x2,y2) = (x1,y1) + (dx[d] + dy[d])
d步数变化:d = (d + 1)%4
dx[4],dy[4] 分别用来存放xy偏移量,d初始值为0,在两种情况下会+1:
1)撞墙
2)走过走过的点
#include "iostream"
using namespace std;
int arr[101][101];
int main(){
int n,m;
cin >> n >> m; // n x m
int dx[4] = {0,1,0,-1} , dy[4] = {1,0,-1,0}; // x,y 按顺序的偏移量
int x = 0 , y = 0 , d = 0;
for(int num = 1 ; num <=m*n ; num ++ ){
arr[x][y] = num;
int x_next = x + dx[d] , y_next = y + dy[d];
// 判断是否撞墙? 走过走过的点
if (x_next<0 || x_next >=n || y_next<0 || y_next>=m || arr[x_next][y_next]){
d = (d+1)%4;
x_next = x + dx[d];
y_next = y + dy[d];
}
x = x_next;
y = y_next;
}
for (int i = 0 ; i < n; i++){
for (int j = 0 ; j < m; j++){
cout << arr[i][j] << ' ';
}
cout << '\n';
}
return 0 ;
}
772. 只出现一次的字符
题解:用字符转int存在数组里面记录出现次数
#include <iostream>
#include <string.h>
using namespace std;
int alp[200];
int main(){
string s;
cin >> s;
int len = s.size();
for (int i = 0; i<len; i++){
alp[(int)(s[i] - 'a')] ++ ;
}
for (int i = 0; i<len; i++){
if(alp[s[i]-'a']==1){
cout << s[i];
return 0;
}
}
cout << "no";
}