每天编程2

存在数组A升序,B降序排列
找到A,B两个数组中交集的第k个元素

思路:既然已经是AB都是排好序的了,那么让i从A的最后一个元素遍历,让j从B的第一个元素开始搜寻AB相等的元素。

 1 #include "stdafx.h"
 2 #include <iostream>
 3 #include <vector>
 4 using namespace std;
 5 
 6 int findKnum(vector<int> a, vector<int> b, int k)
 7 {
 8     if (a.empty() || b.empty())
 9         return -1;
10     if (a.size() < k || b.size() < k)
11         return -1;
12     int count = 0;
13     int i = a.size() - 1;
14     int j = 0;
15     while( i >= 0 && j < b.size())
16         {
17             if (a[i] > b[j])
18             {
19                 i--;
20             }
21             else if (a[i] < b[j])
22             {
23                 j++;
24             }
25             else
26             {
27                 ++count;
28                 if (count == k)
29                 {
30                     return a[i];
31                     break;
32                 }
33                 i--;
34                 j++;
35             }
36             
37         }
38     return -1;
39 }
40 
41 int main()
42 {
43     vector<int> a = {1, 2, 4, 5, 7, 9};
44     vector<int> b = {10, 9, 8, 7, 6, 5, 4};
45     cout << findKnum(a, b, 3) << endl;
46     
47     vector<int> a1(0);
48     cout << findKnum(a1, b, 3) << endl;
49 
50     return 0;
51 }
View Code

posted @ 2016-03-25 10:49  秋雨寒破春泥  Views(126)  Comments(0)    收藏  举报