首页 > ACM题库 > 九度OJ > 九度-1534-数组中第K小的数字[解题代码]
2013
12-13

九度-1534-数组中第K小的数字[解题代码]

题目来源:Google面试题

题目描述:

给定两个整型数组A和B。我们将A和B中的元素两两相加可以得到数组C。
譬如A为[1,2],B为[3,4].那么由A和B中的元素两两相加得到的数组C为[4,5,5,6]。
现在给你数组A和B,求由A和B两两相加得到的数组C中,第K小的数字。

输入:

输入可能包含多个测试案例。
对于每个测试案例,输入的第一行为三个整数m,n, k(1<=m,n<=100000, 1<= k <= n *m):n,m代表将要输入数组A和B的长度。
紧接着两行, 分别有m和n个数, 代表数组A和B中的元素。数组元素范围为[0,1e9]。

输出:

对应每个测试案例,
输出由A和B中元素两两相加得到的数组c中第K小的数字。

样例输入:
2 2 3
1 2
3 4
3 3 4
1 2 7
3 4 5
样例输出:
5
6

cpp 代码如下:
#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
typedef long long lld;
const lld M = 100001;
lld arr1[M],arr2[M];
lld m,n,k;

//统计小于等于 mid 的个数
lld cntMin(lld mid){
	lld cnt = 0;
	lld j = n-1;
	for(int i=0; i<m; i++){
		//由于已排序,可直接利用上一次结果
		while(j >= 0 && arr1[i] + arr2[j] > mid) j--;
		cnt += j+1;
	}
	return cnt;
}

lld low,high,mid;
int main() {
	while(scanf("%lld%lld%lld", &m,&n,&k) != EOF){
		for(lld i=0; i<m; i++) scanf("%lld", &arr1[i]);
		for(lld j=0; j<n; j++) scanf("%lld", &arr2[j]);
		sort(arr1, arr1+m);
		sort(arr2, arr2+n);
		 low  = arr1[0] + arr2[0];
		 high = arr1[m-1] + arr2[n-1];
		 lld ans;
		 //二分逼近
		while(low <= high){
			 mid = (low+high)/2;
			lld cnt = cntMin(mid);
			if(cnt >= k){
				ans = mid; //mid有可能是解
				high = mid-1;
			}else
				low = mid+1;
		}
		printf("%lld\n",ans);

	}
	return 0;
}
/**************************************************************
	Problem: 1534
	User: coder
	Language: C++
	Result: Accepted
	Time:830 ms
	Memory:3080 kb
****************************************************************/


  1. Hello Web Admin, I noticed that your On-Page SEO is is missing a few factors, for one you do not use all three H tags in your post, also I notice that you are not using bold or italics properly in your SEO optimization. On-Page SEO means more now than ever since the new Google update: Panda. No longer are backlinks and simply pinging or sending out a RSS feed the key to getting Google PageRank or Alexa Rankings, You now NEED On-Page SEO. So what is good On-Page SEO?First your keyword must appear in the title.Then it must appear in the URL.You have to optimize your keyword and make sure that it has a nice keyword density of 3-5% in your article with relevant LSI (Latent Semantic Indexing). Then you should spread all H1,H2,H3 tags in your article.Your Keyword should appear in your first paragraph and in the last sentence of the page. You should have relevant usage of Bold and italics of your keyword.There should be one internal link to a page on your blog and you should have one image with an alt tag that has your keyword….wait there's even more Now what if i told you there was a simple WordPress plugin that does all the On-Page SEO, and automatically for you? That's right AUTOMATICALLY, just watch this 4minute video for more information at.

  2. 为什么for循环找到的i一定是素数叻,而且约数定理说的是n=p1^a1*p2^a2*p3^a3*…*pk^ak,而你每次取余都用的是原来的m,也就是n

  3. 您没有考虑 树的根节点是负数的情况, 若树的根节点是个很大的负数,那么就要考虑过不过另外一边子树了