一些算法題,歡迎來改進

第一題,關鍵字:字符串翻轉

Reverse the words in a given English sentence (string) in C or C++ without requiring a separate buffer to hold the reversed string (programming)

For example:

Input:  REALLY DOGSDISLIKE MONKEYS

Output: MONKEYS DISLIKEDOGS REALLY

My code is

  1. void reverse_string (char *s, int start, int end)  
  2.     // be sure that start is less than end 
  3.     if (start >= end) 
  4.         return; 
  5.      
  6.     char tmp; 
  7.     while (start < end) { 
  8.         tmp = *(s + start); 
  9.         *(s + start) = *(s + end); 
  10.         *(s + end) = tmp; 
  11.         start++, end--; 
  12.     } 
  13.  
  14. void reverse_sentence (char *s, int n) 
  15.     reverse_string(s, 0, n-1); 
  16.     int start; 
  17.     bool in_word = false
  18.     for (int i=0; i<=n; i++) 
  19.     { 
  20.         if (*(s+i) == ' ' || *(s+i) == '\0')  
  21.         { 
  22.             if (in_word) 
  23.                 reverse_string(s, start, i-1); 
  24.             in_word = false
  25.         } else if (!in_word)  
  26.         { 
  27.             in_word = true
  28.             start = i
  29.         } 
  30.     } 
  31.  
  32. int string_len (const char *s)  
  33.     int i = 0
  34.     while (*(s+i++) != '\0'); 
  35.     return i-1; 
  36.  
  37. void test_reverse_sentence () 
  38.     char s[] = "REALLY DOGSDISLIKE MONKEYS"; 
  39.     reverse_sentence (s, string_len(s)); 
  40.     std::cout << s

 第二題,關於如何洗牌的一道算法題,關鍵字:隨機數生成

Write a program to shuffle a deck of 52 cards, which is stored in an array and print the shuffle result

My Code:

  1. void shuffle_deck () 
  2.     char deck[52]; 
  3.     // Clear the array, set as zero. 
  4.     memset(deck, 0, 52); 
  5.     int loc; 
  6.      
  7.     // Use number 1,2,..52 represent 52 deck cards. 
  8.     for (int i=1; i<=52; i++)  
  9.     { 
  10.         do { 
  11.             loc = rand() % 52; 
  12.         } while (deck[loc] != 0); 
  13.          
  14.         deck[loc] = i; 
  15.     } 
  16.      
  17.      
  18.     // Print the shuffle result. 
  19.     for (int i=0; i<52; i++) { 
  20.         printf ("%d ", deck[i]); 
  21.     } 

第三題,這是微軟電話面試中的一道題,利用一個循環想將一個浮點數增加2^32次,下面的代碼可以實現嗎?


  1. float f = 0.f; 
  2. for (int i=0; i<2^32; i++) { 
  3.     f += 1; 
循環變量i是有符號整型,能夠表示的範圍爲-2^31 ~ 2^31-1,所以這段代碼不可能完成想要完成的任務。

第四題,這是微軟電話面試中的另外一道題,設計一個算法,對給定的任意一個字節實現按比特位翻轉,要求算法的時間複雜度爲O(1)。

實現字節按比特位翻轉的算法不難,難的是滿足時間複雜度爲O(1)。其實思想很簡單,就是用空間換時間,因爲一個比特位要麼是0,要麼是1,因此一個字節8個比特位也就256種可能性,是可枚舉的,只要建立一張包含所有可能的比特位翻轉映射表就可以了。

第五題, 這是在codility種遇到的一個問題,在一個整型數組種找平衡點的問題,具體需要再分析。

第六題,微軟電話面試中的另外一道題,100階樓梯,每階樓梯的高度是不同的,但是是依次遞減的,給2個相同的玻璃小球,小球從高於一定的高度摔下會被摔碎,請設計一種策略,要求嘗試最少的次數就可以找到小球被摔碎的高度閥值。

這個題已有答案,待有時間時再寫分析。

 


 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章