求整数数组两两之差绝对值最小的值

无聊打开了自己很久以前下的《微软、谷歌、百度等公司经典面试 100 题》的PDF文件。
1、有一个整数数组,请求出两两之差绝对值最小的值,
记住,只要得出最小值即可,不需要求出是哪两个数。
解法思路:

  1. 将数组排序。
  2. 遍历数组,找出数组相邻值之差绝对值最小的数值。
    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());
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 第一章数和数的运算 一概念 (一)整数 1整数的意义 自然数和0都是整数。 2自然数 我们在数物体的时候,用来表示...
    meychang阅读 2,651评论 0 5
  • 1.把二元查找树转变成排序的双向链表 题目: 输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。 要求不...
    曲终人散Li阅读 3,357评论 0 19
  • 1、用C语言实现一个revert函数,它的功能是将输入的字符串在原串上倒序后返回。 2、用C语言实现函数void ...
    希崽家的小哲阅读 6,350评论 0 12
  • 本文出自 Eddy Wiki ,转载请注明出处:http://eddy.wiki/interview-code.h...
    eddy_wiki阅读 9,365评论 0 30
  • 天边的云朵儿哟 你为什么那么羞涩 可是盼着那心爱的大山 巍峨的大山哟 你为何这般目不斜视 可是怕惊扰了林中栖身的雀...
    蒙山小道阅读 232评论 0 0