The Smallest Difference
2024-10-18 22:35:30
Given two array of integers(the first array is array A
, the second array is arrayB
), now we are going to find a element in array A which is A[i], and another element in array B which is B[j], so that the difference between A[i] and B[j] (|A[i] - B[j]|) is as small as possible, return their smallest difference.
Example
For example, given array A = [3,6,7,4]
, B = [2,8,9,3]
, return 0。
分析:
首先sort, 然后用两个指针分别指向两个array的头部,谁小移动谁。
public class Solution {
/**
* @param A, B: Two integer arrays.
* @return: Their smallest difference.
*/
public int smallestDifference(int[] A, int[] B) {
Arrays.sort(A);
Arrays.sort(B); int pa = ;
int pb = ; int diff = Integer.MAX_VALUE; while (pa < A.length && pb < B.length) {
if (A[pa] < B[pb]) {
diff = Math.min(diff, Math.abs(A[pa] - B[pb]));
pa++;
} else if (A[pa] == B[pb]) {
return ;
} else {
diff = Math.min(diff, Math.abs(A[pa] - B[pb]));
pb++;
}
}
return diff;
}
}
最新文章
- CSS3与页面布局学习笔记(四)——页面布局大全(负边距、双飞翼、多栏、弹性、流式、瀑布流、响应式布局)
- Ubuntu 安装 mysql 并修改数据库目录
- linux下定时任务的使用
- 夺命雷公狗ThinkPHP项目之----企业网站2之数据库的快速设计
- HDU5780 gcd 欧拉函数
- 函数buf_page_get
- ActiveMQ中的安全机制 [转]
- css部分总结
- 简单的Coretext 图文混排
- 使用 GitHub, Jekyll 打造自己的免费独立博客
- Mac下使用终端连接远程使用ssh协议的git服务器
- mqtt异步publish方法
- .net core下使用Thrift
- vue.js基础
- Java中值传递和引用传递的区别
- SpringMVC中映射路径的用法之请求限制、命名空间
- jsp视频如何播放
- 使用cmd命令导入SQL文件
- 利用SSH上传、下载(使用sz与rz命令)
- mysql中存储过程