计数排序及拓展

  1. 在字符串中找出第一个只出现一次的字符。(35)
  2. 对公司员工的年龄进行统计排序。
  3. 计数排序(适用于有边界的数值统计)。

1、思路:

  因为字符只有256个数字,设置一个hashtable只有256*4=1K字节,这样时间复杂度只有O(n)。

FirstNotRepeatingChar
 1 char FirstNotRepeatingChar(char* pString)
 2 {
 3     if(pString == NULL)
 4         return '\0';
 5 
 6     const int tableSize = 256;
 7     unsigned int hashTable[tableSize];
 8     for(unsigned int i = 0; i<tableSize; ++ i)
 9         hashTable[i] = 0;
10 
11     char* pHashKey = pString;
12     while(*(pHashKey) != '\0')
13         hashTable[*(pHashKey++)] ++;
14 
15     pHashKey = pString;
16     while(*pHashKey != '\0')
17     {
18         if(hashTable[*pHashKey] == 1)
19             return *pHashKey;
20 
21         pHashKey++;
22     }
23 
24     return '\0';
25 } 

 

2、思路:

  构建hash,key:age->value:num。根据key值大小排序。

SortAges
 1 #include <stdio.h>
 2 #include <exception>
 3 
 4 void SortAges(int ages[], int length)
 5 {
 6      const int oldestAge = 99;
 7      int hashTable[oldestAge + 1];
 8      for (int i = 0; i <= oldestAge; i++)
 9          hashTable[i] = 0;
10 
11      for (int i = 0; i < length; i++)
12      {
13          int age = ages[i];
14          if (age < 0 || age > oldestAge)
15              throw new std::exception();
16          hashTable[age]++;
17      }
18 
19      int index = 0;
20      for (int i = 0; i <= oldestAge; i++)
21      {
22          for (int j = 0; j < hashTable[i]; j++)
23          {
24              ages[index] = i;
25              index ++;
26          }
27      }
28 }
29 
30 int main()
31 {
32     int ages[] = {17, 23, 12, 23, 45, 88, 45, 23};
33     SortAges(ages, 8);
34     for (int i = 0; i < 8; i++)
35         printf("%d ", ages[i]);
36     printf("\n");
37 }

 

 3、思路:

  相当于大数据中分区段统计一样。

 1 void CounterSort(string str, string &help_str)  
 2 {  
 3     // 辅助计数数组   
 4     int help[26] = {0};  
 5   
 6     // help[index]存放了等于index + 'A'的元素个数   
 7     for (int i = 0; i < str.length(); i++)  
 8     {  
 9         int index = str[i] - 'A';  
10         help[index]++;  
11     }  
12   
13     // 求出每个元素对应的最终位置   
14     for (int j = 1; j < 26; j++)  
15         help[j] += help[j-1];  
16   
17     // 把每个元素放到其对应的最终位置   
18     for (int k = str.length() - 1; k >= 0; k--)  
19     {  
20         int index = str[k] - 'A';  
21         int pos = help[index] - 1;  
22         help_str[pos] = str[k];  
23         help[index]--;  
24     }  
25 }  
CounterSort

 

posted on 2013-03-27 14:41  月moon鸟  阅读(186)  评论(0编辑  收藏  举报

导航