[LeetCode] Count and Say

本文介绍了一种特殊的整数序列——计数与说数序列的生成方法,并提供了一个C++实现示例。此外,还讨论了如何在不使用额外空间的情况下将二维矩阵(图像)顺时针旋转90度。

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;
	    }
    }
};




 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值