博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
The Smallest Difference
阅读量:4981 次
发布时间:2019-06-12

本文共 1264 字,大约阅读时间需要 4 分钟。

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的头部,谁小移动谁。

1 public class Solution { 2     /** 3      * @param A, B: Two integer arrays. 4      * @return: Their smallest difference. 5      */ 6     public int smallestDifference(int[] A, int[] B) { 7         Arrays.sort(A); 8         Arrays.sort(B); 9         10         int pa = 0; 11         int pb = 0;12         13         int diff = Integer.MAX_VALUE;14         15         while (pa < A.length && pb < B.length) {16             if (A[pa] < B[pb]) {17                 diff = Math.min(diff, Math.abs(A[pa] - B[pb]));18                 pa++;19             } else if (A[pa] == B[pb]) {20                 return 0;21             } else {22                 diff = Math.min(diff, Math.abs(A[pa] - B[pb]));23                 pb++;24             }25         }26         return diff;27     }28 }

 

转载于:https://www.cnblogs.com/beiyeqingteng/p/5657480.html

你可能感兴趣的文章
网站建设常识
查看>>
hashlib加密操作模块
查看>>
C#里的运算符和表达式
查看>>
解决挂载(mount:wrong fs type,bad option,bad superblock on )错误
查看>>
FastReport.Net使用:[20]条码控件使用
查看>>
表空间操作
查看>>
发布功能完成
查看>>
LeetCode: Reverse Nodes in k-Group
查看>>
06_zookeeper_原生API使用2
查看>>
javascript --- 继承初探七日谈 (一)
查看>>
排序算法一:插入排序(Insertion sort)
查看>>
线段树做题总结
查看>>
JAVA基于File的基本的增删改查
查看>>
RocketMQ安装与实例
查看>>
PHP知识库图谱汇总(完善中)
查看>>
大道至简阅读笔记07
查看>>
爬山 启发式合并 / STL
查看>>
[HNOI2004]宠物收养所 题解
查看>>
Nexus3.x帐号权限配置
查看>>
简易版时间封装
查看>>