6 15 1 2 4 7 11 15
4 11
题目中输入的数据时有序递增的,而且是找两个数,很快想到快速排序的算法,一般这种有序的数都可以借鉴排序算法(三个while循环):
1首先我们判断array[low] + array[height] < k,那么low就一直加1,并且保证low < height
2然后判断array[low]+array[height] > k,那么height就一直减1,并且保证 low < height
3判段 array[low] + array[height] == k,等于就返回1,表示找到了,否则继续
呵呵,是不是和快排的思想一样。
下面是代码:
#include <stdio.h> #include <stdlib.h> #define MaxSize 1000000 int Array[MaxSize]; int findMinTwoNumber(int vK, int vN, int *vLeft, int *vRight) { if (vN < 2) return 0; int Low, Hight; Low = 0; Hight = vN-1; while (Low < Hight) { while (Array[Low] + Array[Hight] < vK && Low < Hight) ++Low; while (Array[Low] + Array[Hight] > vK && Low < Hight) --Hight; if (Array[Low] + Array[Hight] == vK && Low < Hight) { *vLeft = Low; *vRight = Hight; return 1; } } return 0; } int main() { int K, N, i, Ret, Left, Right; while (scanf("%d %d", &N, &K) != EOF) { for (i = 0; i < N; ++i) { scanf("%d", &Array[i]); } Ret = findMinTwoNumber(K, N, &Left, &Right); if (Ret) { printf("%d %d\n", Array[Left], Array[Right]); } else { printf("-1 -1\n"); } } //system("pause"); return 0; }http://blog.csdn.net/xiaoliangsky/article/details/40901373
原文地址:http://blog.csdn.net/xiaoliangsky/article/details/40901373