从网上找到的题目,自己做了一遍
1、二分查找
2、给定一个字符串,得到这个字符串中首先出现两次的那个字符
方法:可以用一个hash_map或者数组来存储字符出现的次数,一旦有一个出现了2次,就返回该字符
3、尝试在以下文本中搜索并打印出包含单词"your"(不区分大小写)的句子,并按照出现次数从高到低排序
Make yourself at home
None of your business
I will be more careful
How about going to a move?
Your life is your own affair
方法:统计每行中your出现的次数,然后 进行排序
代码:
1 #include<iostream> 2 #include<hash_map> 3 #include<vector> 4 #include<string> 5 #include<sstream> 6 #include<algorithm> 7 using std::vector; 8 using std::string; 9 using std::cout; 10 using std::cin; 11 using std::endl; 12 using std::hash_map; 13 using std::istringstream; 14 //题目1:二分查找 15 int bin_search(int num[], int start, int end, int n); 16 int bin_search(int num[],int length,int n) 17 { 18 if (num==0||length<=0) 19 { 20 return false; 21 } 22 23 return bin_search(num, 0, length - 1, n); 24 } 25 26 int bin_search(int num[],int start,int end,int n) 27 { 28 if (num==NULL||start<0||end<start||end<0) 29 { 30 throw std::exception("Invalid input"); 31 } 32 33 if (start==end) 34 { 35 if (num[start] == n) 36 { 37 return start; 38 } 39 else 40 return -1; 41 } 42 43 int mid = start + (end - start) / 2; 44 if (num[mid]==n) 45 { 46 return mid; 47 } 48 else if (num[mid]<n) 49 { 50 return bin_search(num, mid + 1, end, n); 51 } 52 else 53 { 54 return bin_search(num, start, mid - 1, n); 55 } 56 } 57 58 //题目2:字符串中第一次出现2次的字符 59 60 char occur2times(char* ch) 61 { 62 char word = '