指针从头出发
- 快排的一种实现。(详见Sort)
- 输入一个正数sum,打印出所有和为sum的连续正数序列(至少含有两个数)。
- 输入两个字符串,从第一个字符串中删除第二个字符串中的所有字符。(详见String)
1、思路:
将随机base放在尾部,设置small和big指针从头有先后的前进。每次big前进,判断是否小于base:如果小于base,那么small和big需要互换,然后small++;如若不然则跳过。
Partition
1 int Partition(int* data, int length, int start, int end) 2 { 3 if (data == NULL || length <= 0 || start < 0 || end >= length) 4 throw new std::exception(); 5 int index = Random(start, end); 6 Swap(&data[index], &data[end]); 7 int small = start; 8 for (index = start; index < end; index++) 9 { 10 if (data[index] < data[end]) 11 { 12 Swap(&data[small], &data[index]); 13 small++; 14 } 15 } 16 Swap(&data[small], &data[end]); 17 return small; 18 }
2、思路:
注意要连续数列和为n,那么起始数一定不会超过n/2。所以初始化1和2两个前后指针,当和小于s的时候,向后移动后指针;当和大于s的时候,向后移动前指针。知道前指针移动到n/2的位置,循环结束。
FindContinuousSequence
1 FindContinuousSequence 2 void FindContinuousSequence(int sum) 3 { 4 if (sum < 3) return; 5 int small = 1; 6 int big = 2; 7 int mid = (1 + sum) / 2; 8 int curSum = small + big; 9 10 while (small < mid) 11 { 12 if (curSum == sum) 13 PrintContinuousSequence(small, big); 14 while (curSum > sum && small < mid) 15 { 16 curSum -= small; 17 small++; 18 if (curSum == sum) 19 PrintContinuousSequence(small, big); 20 } 21 big++; 22 curSum += big; 23 } 24 }