当前位置:网站首页>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));
}
}
边栏推荐
- 小程序 rich-text中图片点击放大与自适应大小问题
- leetCode-1051: 高度检查器
- Safety and food security for teachers and students of the trapped Yingxi middle school
- leetCode-面试题 01.05: 一次编辑
- Appium自动化测试基础 — 移动端测试环境搭建(一)
- JMeter接口测试工具基础— 使用Badboy录制JMeter脚本
- 用扫描的方法分发书稿校样
- Leetcode interview question 01.05: primary editing
- SSM integration
- 卷妹带你学jdbc---2天冲刺Day1
猜你喜欢
随机推荐
分布式 | 如何与 DBLE 进行“秘密通话”
dedecms模板文件讲解以及首页标签替换
使用swiper左右轮播切换时,Swiper Animate的动画失效,怎么解决?
SQL sever基本数据类型详解
1. project environment construction
JMeter接口测试工具基础— 取样器sampler(二)
SQL Sever关于like操作符(包括字段数据自动填充空格问题)
Leetcode interview question 01.05: primary editing
【资源分享】2022年第五届土木,建筑与环境工程国际会议(ICCAEE 2022)
numpy.logical_or
希尔排序图文详解+代码实现
学习使用phpstripslashe函数去除反斜杠
Three ways to use applicationcontextinitializer
包装类型与基本类型的区别
leetCode-面试题 01.05: 一次编辑
学习使用php对字符串中的特殊符号进行过滤的方法
形状变化loader加载jsjs特效代码
学习整理在php中使用KindEditor富文本编辑器
The difference between static link library and dynamic link library
整理接口性能优化技巧,干掉慢代码








