[面试备忘]最大字串 & 升序数组交集

题目一: 线性时间内判断两有序数组是否有相同元素.

题目二: 求数组最大子串(元素全负时返回0)

View Code
 1 #include <iostream>
2 #include <cassert>
3 //判断两已排序数组是否有相同元素
4 bool sameNumber(const int* preArray, int preSize, const int* postArray, int postSize)
5 {
6 assert( preArray && postArray);
7 int preIndex = 0;
8 int postIndex = 0;
9 while (preIndex != preSize && postIndex != postSize) {
10 if (preArray[preIndex] == postArray[postIndex]) {
11 return true;
12 }
13 if (preArray[preIndex] > postArray[postIndex]) {
14 ++postIndex;
15 } else {
16 ++preIndex;
17 }
18 }
19 return false;
20 }
21
22 //求数组中最大子串 普通方法
23 int getMaxSubArrayNormal(const int* array, int size)
24 {
25 assert(array);
26 int max = array[0];
27 for (int outIndex = 0; outIndex != size; ++outIndex) {
28 int tempValue = 0;
29 for (int inIndex = outIndex; inIndex != size; ++inIndex) {
30 tempValue += array[inIndex];
31 if (tempValue > max) {
32 max = tempValue;
33 }
34 }
35 }
36 return max;
37 }
38 //动规方法
39 int getMaxSubArrayDP(const int* array, int size)
40 {
41 assert(array);
42 int max = 0;
43 int tempSum = 0;
44 for (int index = 0; index != size; ++index) {
45 tempSum += array[index];
46 if (tempSum > max) {
47 max = tempSum;
48 } else if (tempSum < 0) {
49 tempSum = 0;
50 }
51 }
52 return max;
53 }
54 int main()
55 {
56 int preArray[] = { 1, 3, 4, 6, 8, 9 };
57 int postArray[] = { 5, 8, 10 };
58 std::cout << std::boolalpha << sameNumber(preArray,
59 sizeof(preArray) / sizeof(*preArray), postArray,
60 sizeof(postArray) / sizeof(*postArray)) << std::endl;
61 int maxSubArray[] = { -1, 3, 5, 6, -5, 3, -2, -1, 16, -1, 2 };
62 std::cout << getMaxSubArrayNormal(maxSubArray, sizeof(maxSubArray) / sizeof(*maxSubArray)) << ' '
63 << getMaxSubArrayDP(maxSubArray, sizeof(maxSubArray) / sizeof(*maxSubArray)) << std::endl;
64 return 0;
65 }

posted @ 2011-08-29 16:56  lifengzhong  阅读(258)  评论(0编辑  收藏  举报