問題:
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;i
1.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][n],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;i
Time 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++標準庫裏有哈希表嗎?不用哈希表用數組?數組的大小和元素的範圍?