The Smallest Difference
2016-07-10 12:45
204 查看
Given two array of integers(the first array is array
Example
For example, given array A =
分析:
首先sort, 然后用两个指针分别指向两个array的头部,谁小移动谁。
A, the second array is array
B), 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 = 0; int pb = 0; 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 0; } else { diff = Math.min(diff, Math.abs(A[pa] - B[pb])); pb++; } } return diff; } }
相关文章推荐
- caffe 学习系列激活层及其参数
- 校验字符串是否是JSON格式,将不规则展示的json格式的字符串进行规则展示(json格式化)
- caffe 学习系列 视觉层
- NodeJs--url
- NodeJs--url
- caffe 学习系列 数据层介绍
- 【ReactNative】react-native 布局
- angular中$watch踩的坑
- 来看看机智的前端童鞋怎么防盗
- Javascript DOM Document|Element|Attribute对象方法详解
- HTML4 和 HTML5 的10个区别
- HTML5的开发工具
- 剑指offer43--字符串转化成整数
- NodeJs--模块分类
- JavaScript instanceof 运算符深入剖析
- NodeJs--模块分类
- CSS定位中的必须深究的常用技法
- 那些年用node接入微信走过的坑之(一)---成为开发者
- (转)前端不为人知的一面--前端冷知识集锦
- 前端工程师技能之photoshop巧用系列扩展篇——自动切图