当前位置:网站首页>Leetcode interview question 16.06: minimum difference
Leetcode interview question 16.06: minimum difference
2022-06-24 10:23:00 【Ugly and ugly】
Title Description
Given two arrays of integers a and b, Calculate a pair of values with the absolute value of the minimum difference ( Take one value from each array ), And return the difference of the logarithm
Example
Example 1:
Input :{1, 3, 15, 11, 2}, {23, 127, 235, 19, 8}
Output :3, That is, the value pair (11, 8)
The problem solving process
Ideas and steps
(1) Sort + Double pointer ;
(2)left The pointer loops through the array a,right The pointer loops through the array b, Record diff Is the difference between the data pointed to by the current two pointers ;
(3) If diff > 0,right The pointer increases by itself , If diff < 0,left The pointer increases by itself ;
(4) Each cycle compares the current diff The absolute value of and the final result result Size , Assign the small party to result;
(5) It should be noted that diff Need to be defined as long Type of , Otherwise, the result will be wrong , such as [-2147483648,1] Numerical pair ,diff by -2147483649, If defined as int You'll cross the line .
Code display
public class SmallestDifference {
public int smallestDifference(int[] a, int[] b) {
Arrays.sort(a);
Arrays.sort(b);
int left = 0;
int right = 0;
int result = Integer.MAX_VALUE;
while (left < a.length && right < b.length) {
long diff = a[left] - b[right];
long diffAbs = Math.abs(diff);
result = (int)Math.min(diffAbs, result);
if(diff > 0) {
right++;
} else {
left++;
}
}
return result;
}
public static void main(String[] args) {
int[] a = {
-2147483648,1};
int[] b = {
0,2147483647};
System.out.println(new SmallestDifference().smallestDifference(a, b));
}
}
边栏推荐
猜你喜欢

H5网页如何在微信中自定义分享链接

numpy. linspace()

正规方程、、、

使用swiper左右轮播切换时,Swiper Animate的动画失效,怎么解决?

canvas无限扫描js特效代码

p5.js实现的炫酷交互式动画js特效

Record the range of data that MySQL update will lock

CVPR 2022 Oral | 英伟达提出自适应token的高效视觉Transformer网络A-ViT,不重要的token可以提前停止计算

Juul, the American e-cigarette giant, suffered a disaster, and all products were forced off the shelves

分布式事务原理以及解决分布式事务方案
随机推荐
JMeter接口测试工具基础— 取样器sampler(二)
1.项目环境搭建
SSM整合
What are the characteristics of EDI local deployment and cloud hosting solutions?
tf. contrib. layers. batch_ norm
TP5 using post to receive array data times variable type error: solution to array error
SQL Server AVG function rounding
24. 图像拼接大作业
植物生长h5动画js特效
牛客-TOP101-BM28
上升的气泡canvas破碎动画js特效
leetCode-1089: 复写零
Status of the thread pool
Engine localization adaptation & Reconstruction notes
Learning to organize using kindeditor rich text editor in PHP
2022-06-23: given a nonnegative array, select any number to make the maximum cumulative sum a multiple of 7, and return the maximum cumulative sum. N is larger, to the 5th power of 10. From meituan. 3
百度网盘下载一直请求中问题解决
numpy. logical_ or
leetCode-面试题 16.06: 最小差
leetCode-498: 对角线遍历