一些算法题,欢迎来改进

第一题,关键字:字符串翻转

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个相同的玻璃小球,小球从高于一定的高度摔下会被摔碎,请设计一种策略,要求尝试最少的次数就可以找到小球被摔碎的高度阀值。

这个题已有答案,待有时间时再写分析。

 

 

 

你可能感兴趣的:(算法交流)