求整数数组两两之差绝对值最小的值
2017-10-22 本文已影响0人
DataNerd
无聊打开了自己很久以前下的《微软、谷歌、百度等公司经典面试 100 题》的PDF文件。
1、有一个整数数组,请求出两两之差绝对值最小的值,
记住,只要得出最小值即可,不需要求出是哪两个数。
解法思路:
- 将数组排序。
- 遍历数组,找出数组相邻值之差绝对值最小的数值。
Java代码:
import java.util.Arrays;
public class Solution{
public int minSub(Integer[] array){
Arrays.sort(array);
int minSub = Integer.MAX_VALUE;
int sub = Integer.MAX_VALUE;
for(int i = 0;i < array.length - 1;i ++){
sub = Math.abs(array[i + 1] - array[i]);
minSub = (sub < minSub) ? sub : minSub;
}
return minSub;
}
}
测试
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.Before;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
@RunWith(Parameterized.class)
public class Test1{
private Integer[] testArray = null;
private Integer testMinSub = Integer.MAX_VALUE;
private Solution solution = null;
@Before
public void initialize(){
solution = new Solution();
}
@Parameterized.Parameters
public static Collection testData(){
return Arrays.asList(new Object[][]{
{new Integer[]{23, 3, 4, 6, 9, 154}, 1},
{new Integer[]{23, 21, 28, 76, 39, 154}, 2},
{new Integer[]{23, 5, 10, 43}, 5}
});
}
@Test
public void testMinSub(){
System.out.println("test_input: " + testArray.toString());
assertEquals((long) testMinSub, (long)solution.minSub(testArray));
}
public Test1(Integer[] array, Integer testMinSub){
this.testArray = array;
this.testMinSub = testMinSub;
}
public static void main(String[] args){
Result result = JUnitCore.runClasses(Test1.class);
for(Failure failure:result.getFailures()){
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}