Prompt
Write a function that takes in two non-empty arrays of integers, nds the pair of numbers (one from each array) whose absolute dierence is closest to zero, and returns an array containing these two numbers, with the number from the rst array in the first position.
You can assume that there will only be one pair of numbers with the smallest dierence.
Sample Input
arrayOne = [-1, 5, 10, 20, 28, 3]
arrayTwo = [26, 134, 135, 15, 17]
Sample Output
[28, 26]
Solution
import java.util.*;
class Program {
// O(nlogn + mlogm) time | O(1) space
public static int[] smallestDifference(int[] arrayOne, int[] arrayTwo) {
// Write your code here.
Arrays.sort(arrayOne);//A
Arrays.sort(arrayTwo);
int idxOne = 0;
int idxTwo = 0;
int current = Integer.MAX_VALUE;
int smellest = Integer.MAX_VALUE;
int[] smellestPair= new int[2];//B
while (idxOne < arrayOne.length && idxTwo < arrayTwo.length) {
int firstNum = arrayOne[idxOne];//C
int secondNum = arrayTwo[idxTwo];
if (firstNum > secondNum) {//D
current = firstNum - secondNum;
idxTwo ++;
} else if (firstNum < secondNum) {
current = secondNum - firstNum;
idxOne ++;
} else {
return new int[] {firstNum, secondNum};//E
}
if (current < smellest) {
smellest = current;
smellestPair = new int[] {firstNum, secondNum};
}
}
return smellestPair;
}
}
# A
数组题的思路把这个函数考虑进去, 好想满多都是先排序
# B
数组的定义及初始化
初始化后才能用
# C
这样处理数据,会很简洁,每次都有一个新的firstNum,不用在之后的比较中,纠结数组的index和数组的值的关系
# D
Math.abs();
# E
还是见得少,这种相等的情况,直接就到位了