首页 > 代码库 > Java从一组数组中找出最接近目标值的值

Java从一组数组中找出最接近目标值的值

两种算法:

1.原始数据是乱序的

2.原始数据是有序的

 

1.

 1 package test;
 2 
 3 import java.io.File;
 4 
 5 public class Test {
 6     /**
 7      * 假设原始数据是乱序
 8      */
 9     static int[] src = http://www.mamicode.com/new int[] { 25, 68, 5, 38, 2, 15, 90, 55, 46 };
10     /**
11      * 目标值
12      */
13     static int x = 555;
14 
15     public static void main(String[] args) {
16         System.out.println(getApproximate(x, src));
17     }
18 
19     /**
20      * 获取接近值
21      * 
22      * @param x
23      * @param src
24      * @return
25      */
26     private static int getApproximate(int x, int[] src) {
27         if (src =http://www.mamicode.com/= null) {
28             return -1;
29         }
30         if (src.length == 1) {
31             return src[0];
32         }
33         int minDifference = Math.abs(src[0] - x);
34         int minIndex = 0;
35         for (int i = 1; i < src.length; i++) {
36             int temp = Math.abs(src[i] - x);
37             if (temp < minDifference) {
38                 minIndex = i;
39                 minDifference = temp;
40             }
41         }
42         return src[minIndex];
43     }
44 }

运行结果:I/System.out: 90

2.

package test;

import java.io.File;

public class CopyOfTest {
    /**
     * 假设原始数据是有序
     */
    static int[] src = http://www.mamicode.com/new int[] {  10, 12, 21, 22, 25, 30, 34, 37, 39, 46, 51, 56, 70, 85 };
    /**
     * 目标值
     */
    static int x = 55;

    public static void main(String[] args) {
        System.out.println(getApproximate(x, src));
    }

    /**
     * 获取接近值
     * 
     * @param x
     * @param src
     * @return
     */
    private static int getApproximate(int x, int[] src) {
        if (src =http://www.mamicode.com/= null) {
            return -1;
        }
        if (src.length == 1) {
            return src[0];
        }
        int index = -1;
        for (int i = 0; i < src.length; i++) {
            if (src[i] > x) {
                index = i;
                break;
            } else if (src[i] == x) {
                return x;
            }
        }
        if (index == -1) {
            return src[src.length - 1];
        } else if (index == 0) {
            return src[0];
        } else {
            return x - src[index - 1] < src[index] - x ? src[index - 1] : src[index];
        }
    }
}

运行结果:I/System.out: 56

Java从一组数组中找出最接近目标值的值