Count and Say:
The count-and-say sequence is the sequence of integers beginning as follows:
1,
11, 21, 1211, 111221, ...
1 is
read off as "one
1" or 11.
11 is
read off as "two
1s" or 21.
21 is
read off as "one
2, then one
1" or 1211.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
只会用模拟法了 ,用了两个指针来优化。class Solution {
public:
string countAndSay(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
assert(n>=1);
string s1("1");
string s2;
string* ans=&s1;
string* tmp=&s2;
for(int i=2;i<=n;i++)
{
(*tmp).clear();
char pre=(*ans)[0];
int time=1;
int len=(*ans).length();
for(int j=1;j<len;j++)
{
if ( (*ans)[j]==pre)
time++;
else
{
(*tmp).push_back(time+'0');
(*tmp).push_back(pre);
pre=(*ans)[j];
time=1;
}
}
(*tmp).push_back(time+'0');
(*tmp).push_back(pre);
string* tt=ans;
ans=tmp;
tmp=tt;
}
return *ans;
}
};
Rotate Image:
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
class Solution {
public:
void rotate(vector<vector<int> > &mat) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int n=mat.size();
int startX=0,startY=0;
int Width=n,Height=n;
while(Width>=1&&Height>=1)
{
for(int i=0;i<Width-1;i++)
{
int tmp=mat[startX][startY+i];
swap(mat[startX+Height-1-i][startY],mat[startX][startY+i]);
swap(mat[startX+Height-1][startY+Width-1-i],mat[startX+Height-1-i][startY]);
swap(mat[startX+i][startY+Width-1],mat[startX+Height-1][startY+Width-1-i]);
mat[startX+i][startY+Width-1]=tmp;
}
startX+=1;
startY+=1;
Width-=2;
Height-=2;
}
}
};
本文介绍了一种特殊的整数序列——计数与说数序列的生成方法,并提供了一个C++实现示例。此外,还讨论了如何在不使用额外空间的情况下将二维矩阵(图像)顺时针旋转90度。
494

被折叠的 条评论
为什么被折叠?



