【小算法】从有序序列中取出间隔尽量均匀的N个数组成新有序序列输出

输入:一个间隔均匀的有序序列v,整数n

输出:一个有序序列,大小为  n与v.size()的较小者,要求序列元素间隔均匀。

实现:数据结构使用STL提供的vector,算法思想可以用四个字描述--“隔1删除”,具体实现步骤如下:

1、将0,1,2,。。。C-1放入vector

2、记录需要删除的元素个数C-N,和实际删除的元素个数actualDelCount = 0,list迭代器it = vector.begin(),

3、循环进行下面步骤:

    (1) *++it = -1;it++;actualDelCount++;

    (2) 如果actualDelCount大于等于C-N,跳出循环

    (3) 如果迭代器到了末尾( it == vector.end() ) ,删除list中所有值为-1的元素,同时将it重新赋值为vector.begin()

4、删除vector中所有值为-1的元素,所得到的则为所要求的结果

总结:该算法效率一般,提高效率的可能途径有:

1、将vector改为删除效率更高的list

2、省去将元素标记为-1,和删除值为-1的元素这两个步骤

感叹:这么一个很小的算法题,我居然花了半天时间才搞定,而且程序效率还不高,我要好好,好好的学习算法了!!!

最后,贴出程序源代码,以供回顾

 

代码片段
1
2  void WellDistributeVector(vector<int> &v,
3 int count_/* =30 */)
4 {
5 if (v.size() <= count_)
6 {
7 return ;
8 }
9 vector<int> temp;
10 for (int i=0;i<v.size();i++)
11 {
12 temp.push_back(v[i]);
13 }
14
15 const int INVALID_NUM = -1;
16
17 int reduceCount = temp.size() - count_;
18 int reduceActualNum = 0;
19
20 int gap = 1; //间隔gap取数,
21   int index = 0;
22 while (reduceActualNum < reduceCount)
23 {
24 if (index >= temp.size())
25 {
26 index = 0;
27 vector<int>::iterator it = temp.begin();
28 while (it != temp.end())
29 {
30 if (*it == INVALID_NUM)
31 {
32 it = temp.erase(it);
33 }
34 else it++;
35 }
36 }
37 index += gap;
38 if (index < temp.size())
39 {
40 temp[index++] = INVALID_NUM;
41 reduceActualNum ++;
42 }
43 }
44
45 v.clear();
46 for (int i=0;i<temp.size();i++)
47 {
48 if (temp.at(i) != INVALID_NUM)
49 {
50 v.push_back(temp.at(i));
51 }
52 }
53 }

 

 

posted @ 2010-03-22 20:00  stuarts  Views(614)  Comments(1Edit  收藏  举报