您的位置:首页 > 理论基础 > 数据结构算法

每天坚持Crack Code(Day 3)

2013-09-20 10:17 549 查看
问题:

1.6 Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?

翻译:一张图像NxN矩阵,每个像素为4个字节,写一个方法将图像旋转90度,问可以原地处理不额外开辟新的存储空间?

void Swap(int &a, int &b)
{
//一个整形数异或同一个数字偶次数的值不变
a^=b;
b^=a;
a^=b;
}

//逆时针旋转90度,第一步做对角线上的对称变换,第二步做上下的对称变换。
//画个图可以比较清楚
void rotate(int matrix[][4],int n)
{
for(int i=0;i1.7 Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0.

翻译:写一个方法,对于MxN矩阵,若有一个元素为0,则将其所在的行与列的所有元素置0。

void setZeros(int matrix[m]
,int m, int n)
{
bool row[4]={false};
bool colum[4]={false};
//Store the row and colum index with value 0
for(int i=0;iTime complexity O(M*N) and space complexity O(M+N).

还有改进的空间?(马克一下,之后再改进)

1.8 Assume you have a method isSubstring which checks if one word is a substring of another. Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using
only one call to isSubstring (i.e., “waterbottle” is a rotation of “erbottlewat”).

翻译:假设你有一个方法isSubstring是可以判断一个字符串是否是另一个的字串,如给定两个字符串,s1和s2,判断s2是否是s1的旋转字符串,只能调用一次isSubstring,(例如:waterbottle是erbottlewat的旋转字符串)

bool isSubstring(string s1, string s2){
//s1.find(s2)返回s2在s1中的下标位置,如果没有找到,则返回特别的标志npos
if(s1.find(s2) != string::npos) return true;
else return false;
}

bool isRotation(string s1,string s2)
{
if(s1.length() != s2.length() || s1.length()<=0)
return false;
return isSubstring(s1+s1,s2);
}

int main()
{
string s1="apple";
string s2="pleap";
cout<
2.1 Write code to remove duplicates from an unsorted linked list.

FOLLOW UP

How would you solve this problem if a temporary buffer is not allowed?

翻译:在没有排序的链表中删除重复的项,并且不允许使用临时的缓存,如何解决这个问题?

1.如果可以使用额外的存储空间,我们就可以保存一个元素的出现情况,例如使用哈希表。c++标准库里有哈希表吗?不用哈希表用数组?数组的大小和元素的范围?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息