AtCoder Beginner Contest 212 C - Min Difference

C - Min Difference

Problem Statement

You are given two sequences: A=(A1,A2,…,AN) consisting of N positive integers, and B=(B1,…,BM) consisting of M positive integers.

Find the minimum difference of an element of A and an element of B, that is, min1≤i≤N min1≤j≤M |Ai−Bj|.

Constraints

1≤N,M≤2×10^5
1≤Ai≤10^9
1≤Bi≤10^9
All values in input are integers.

Input

Input is given from Standard Input in the following format:
N M
A1 A2 … AN
B1 B2 … BM

Output

Print the answer.

Sample Input 1

2 2
1 6
4 9

Sample Output 1

2

Here is the difference for each of the four pair of an element of A and an element of B: |1−4|=3, |1−9|=8, |6−4|=2, and |6−9|=3. We should
print the minimum of these values, or 2.

Sample Input 2

1 1
10
10

Sample Output 2

0

Sample Input 3

6 8
82 76 82 82 71 70
17 39 67 2 45 35 22 24

Sample Output 3

3

题目大意:

给定数组a和数组b,数组a长度为n,数组b长度为m,你可以从数组a和数组b中各选一个数,问这两个数差值的绝对值最小是多少。

题解:

首先我们会想到暴力的方法,直接二重循环枚举每一个数对,复杂度是O(nm),这样时间复杂度太高了,会超时。

我们可以先将a和b数组排序,然后用两个指针i和j分别指向a[0]和b[0],循环过程中保证i < n且j < m。
如果abs(a[i] - b[j])比记录的最小值小,就更新当前的最小值。
如果a[i] > b[j],就j ++,因为如果i ++,差值只会越来越大。
同理如果a[i] < b[j]就i ++。
如果a[i] == b[j],那么最小差就是0,直接退出循环,因为最小差不会小于0。

这样我们只用了一重循环,O(n)的时间复杂度就可以实现最小差的计算。

AC代码:

#include <iostream>
#include <algorithm> 
using namespace std;
typedef long long ll;
const int N = 1e6 + 5;
const int INF = 0x3f3f3f3f;
ll a[N], b[N];
int main() {
    ios::sync_with_stdio(false);
	ll n, m;
	cin >> n >> m;
	for (ll i = 0; i < n; i ++) cin >> a[i];
	for (ll i = 0; i < m; i ++) cin >> b[i];
	sort(a, a + n); // 先排序 
	sort(b, b + m);
	ll mn = INF; // 初始化最小值 
	for (ll i = 0, j = 0; i < n && j < m; ) { 
		ll t = abs(a[i] - b[j]);  
		if (t < mn) mn = t; // 更新最小值 
		if (a[i] > b[j]) j ++; // 如果i ++只会让差值变大,所以j ++ 
		else if (a[i] < b[j]) i ++;
		else { // 如果a[i] = b[j], 最小差一定是0 
			mn = 0;
			break; 
		}
	}
	cout << mn << '\n';
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值