Smallest Difference

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

还是见得少,这种相等的情况,直接就到位了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值