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;
}
}

最新文章

  1. CSS3与页面布局学习笔记(四)——页面布局大全(负边距、双飞翼、多栏、弹性、流式、瀑布流、响应式布局)
  2. Ubuntu 安装 mysql 并修改数据库目录
  3. linux下定时任务的使用
  4. 夺命雷公狗ThinkPHP项目之----企业网站2之数据库的快速设计
  5. HDU5780 gcd 欧拉函数
  6. 函数buf_page_get
  7. ActiveMQ中的安全机制 [转]
  8. css部分总结
  9. 简单的Coretext 图文混排
  10. 使用 GitHub, Jekyll 打造自己的免费独立博客
  11. Mac下使用终端连接远程使用ssh协议的git服务器
  12. mqtt异步publish方法
  13. .net core下使用Thrift
  14. vue.js基础
  15. Java中值传递和引用传递的区别
  16. SpringMVC中映射路径的用法之请求限制、命名空间
  17. jsp视频如何播放
  18. 使用cmd命令导入SQL文件
  19. 利用SSH上传、下载(使用sz与rz命令)
  20. mysql中存储过程

热门文章

  1. YQCB冲刺第二周第五天
  2. Daily Scrum - 11/25
  3. Java编写准备数据源
  4. 组件 --BreadCrumb--面包屑
  5. 浅谈|WEB 服务器 -- Caddy
  6. [你必须知道的异步编程]C# 5.0 新特性——Async和Await使异步编程更简单
  7. JSP 获取真实IP地址的代码
  8. Go匿名函数
  9. MySQL 主从复制详解
  10. CodeForces - 707C