zoukankan      html  css  js  c++  java
  • 最小差

    给定两个整数数组(第一个是数组 A,第二个是数组 B),在数组 A 中取 A[i],数组 B 中取 B[j],A[i] 和 B[j]两者的差越小越好(|A[i] - B[j]|)。返回最小差。
    样例

    给定数组 A = [3,4,6,7], B = [2,3,8,9],返回 0


    public
    class Solution { /** * @param A, B: Two integer arrays. * @return: Their smallest difference. */ public int smallestDifference(int[] A, int[] B) { // write your code here Set<Integer> list = new HashSet<>(); for (int i = 0; i < A.length; i++) { for (int j = 0; j < B.length; j++) { int jueDuizhi = getJueDuizhi(A[i], B[j]); list.add(jueDuizhi); } } int[] array = new int[list.size()]; Iterator iterator = list.iterator(); int i1 =0; while (iterator.hasNext()) { array[i1] = (int) iterator.next(); i1++; } /** * 用于接得到的最小值 */ int te1 = 0; /** * 用一趟排序找出最小值 */ for (int i = 0; i < array.length; i++) { for (int j = 0; j < array.length; j++) { if(array[i] > array[j]) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } } te1 = array[0]; break; } return te1; } /** * 获取两个数差的绝对值 * @param a * @param b * @return */ public static int getJueDuizhi(int a, int b) { if (a - b > 0) { return a - b; } else { return b - a; } } }

     此程序空间复杂度过大。后续会继续优化。

  • 相关阅读:
    query.setXXX预编译赋值 (坑爹的)
    JAVA 预编译执行SQL 之setparameterList用法
    ActiveMQ
    JavaScript DOM日记
    Mysql 详解(三)
    Mysq连接使用
    Mysql详解(二)
    Mysql详解(一)
    Spring MVC 批量导入Excel文件
    《走遍中国》珍藏版(三)
  • 原文地址:https://www.cnblogs.com/zkycode/p/7007295.html
Copyright © 2011-2022 走看看