35

我有一组正/负整数

int[] numbers = new int[10];
numbers[0] = 100;
numbers[1] = -34200;
numbers[2] = 3040;
numbers[3] = 400433;
numbers[4] = 500;
numbers[5] = -100;
numbers[6] = -200;
numbers[7] = 532;
numbers[8] = 6584;
numbers[9] = -945;

现在,我想针对这个数组测试另一个 int,并返回最接近 int 的数字。

例如,如果我使用数字490我会从数字中取回第 4 项,500那么做这样的事情的最佳方法是什么?

int myNumber = 490;
int distance = 0;
int idx = 0;
for(int c = 0; c < numbers.length; c++){
    int cdistance = numbers[c] - myNumber;
    if(cdistance < distance){
        idx = c;
        distance = cdistance;
    }
}
int theNumber = numbers[idx];

那是行不通的。关于这样做的好方法有什么建议吗?

4

13 回答 13

49
int myNumber = 490;
int distance = Math.abs(numbers[0] - myNumber);
int idx = 0;
for(int c = 1; c < numbers.length; c++){
    int cdistance = Math.abs(numbers[c] - myNumber);
    if(cdistance < distance){
        idx = c;
        distance = cdistance;
    }
}
int theNumber = numbers[idx];

始终使用您正在考虑的第一个元素初始化您的最小/最大函数。Integer.MAX_VALUE使用or之类的东西Integer.MIN_VALUE是获得答案的幼稚方式;MAX_LONG如果您稍后更改数据类型(哎呀,并且MAX_INT非常不同!)或者如果您将来想要为任何min/max数据类型编写通用方法,它就不能很好地支持。

于 2012-11-10T02:52:19.143 回答
31

Java 8中:

List<Integer> list = Arrays.stream(numbers).boxed().collect(Collectors.toList());

int n = 490;

int c = list.stream()
            .min(Comparator.comparingInt(i -> Math.abs(i - n)))
            .orElseThrow(() -> new NoSuchElementException("No value present"));

最初,您可以使用 aList而不是 an Array(列表具有更多功能)。

于 2018-01-07T12:52:01.487 回答
4

你很亲密。我认为'distance'的初始值应该是一个大数字而不是0。并使用cdistance的绝对值。

于 2012-11-10T02:47:17.233 回答
3

cdistance = numbers[c] - myNumber. 您没有采用差异的绝对值。如果myNumber远大于numbers[c]或如果numbers[c]为负,则比较将记录为“最小差异”。

以 的情况为例numbers[c] = -34200numbers[c] - myNumber然后将是 -34690,比distance.

此外,您应该初始化distance为一个较大的值,因为一开始还没有找到解决方案。

于 2012-11-10T02:48:03.397 回答
2

您可以调整旧的二进制搜索并有效地实现它。

Arrays.sort(numbers);
nearestNumber = nearestNumberBinarySearch(numbers, 0, numbers.length - 1, myNumber);

private static int nearestNumberBinarySearch(int[] numbers, int start, int end, int myNumber) {
    int mid = (start + end) / 2;
    if (numbers[mid] == myNumber)
        return numbers[mid];
    if (start == end - 1)
        if (Math.abs(numbers[end] - myNumber) >= Math.abs(numbers[start] - myNumber))
            return numbers[start];
        else
            return numbers[end];
     if(numbers[mid]> myNumber)
        return nearestNumberBinarySearch(numbers, start,mid, myNumber);
     else
         return nearestNumberBinarySearch(numbers,mid, end, myNumber);

}
于 2018-11-04T12:48:43.637 回答
2
int valueToFind = 490;

Map<Integer, Integer> map = new HashMap();

for (int i = 0, i < numbers.length; i++){
    map.put(Math.abs(numbers[i] - valueToFind), numbers[i]);
}

List<Integer> keys = new ArrayList(map.keySet());
Collections.sort(keys);

return map.get(keys.get(0));
于 2019-09-02T10:09:56.717 回答
1

一个语句块来初始化和设置最接近的匹配。此外,如果没有找到最接近的匹配项(空数组),则返回 -1。

 protected int getClosestIndex(final int[] values, int value) {
    class Closest {
        Integer dif;
        int index = -1;
    };
    Closest closest = new Closest();
    for (int i = 0; i < values.length; ++i) {
        final int dif = Math.abs(value - values[i]);
        if (closest.dif == null || dif < closest.dif) {
            closest.index = i;
            closest.dif = dif;
        }
    }
    return closest.index;
}
于 2016-12-29T18:22:39.533 回答
1
public int getClosestToTarget(int target, int[] values) {

    if (values.length < 1)
        throw new IllegalArgumentException("The values should be at least one element");
    if (values.length == 1) {
        return values[0];
    }
    int closestValue = values[0];
    int leastDistance = Math.abs(values[0] - target);
    for (int i = 0; i < values.length; i++) {
        int currentDistance = Math.abs(values[i] - target);
        if (currentDistance < leastDistance) {
            closestValue = values[i];
            leastDistance = currentDistance;
        }
    }
    return closestValue;
}
于 2017-04-05T10:44:54.437 回答
1

Kotlin 很有帮助

fun List<Int>.closestValue(value: Int) = minBy { abs(value - it) }

val values = listOf(1, 8, 4, -6)

println(values.closestValue(-7)) // -6
println(values.closestValue(2)) // 1
println(values.closestValue(7)) // 8

列表不需要排序 BTW

于 2020-06-27T19:24:47.917 回答
0

我把它作为我的课程的作业,我用 Ready to Program Java 编写了它,如果它有点混乱,很抱歉。

// The "Ass_1_B_3" class.
import java.awt.*;
import hsa.Console;

public class Ass_1_B_3
{
    static Console c;           // The output console

    public static void main (String[] args)
    {
        c = new Console ();

        int [] data = {3, 1, 5, 7, 4, 12, -3, 8, -2};
        int nearZero = 0;
        int temp = 0;
        int temp2 = data[0];

        for (int i = 0; i < data.length; i++)
        {
            temp = Math.abs (data[i]);
            nearZero = temp2;   
            if (temp < temp2)
            {
                temp2 = temp;
                nearZero = data[i];
            }


        }

        c.println ("The number closest to zero is: " + nearZero);

        // Place your program here.  'c' is the output console
    } // main method
} // Ass_1_B_3 class
于 2016-02-19T03:09:56.460 回答
0

Kotlin -TreeSet lower方法返回此集合中严格小于给定元素的最大元素,如果没有这样的元素,则返回 null。

import java.util.*

fun printLowest(number: Int) {
    val numbers = listOf(100, 90, 50, -100, -200, 532, 6584, -945)
    val lower = TreeSet(numbers).lower(number)
    println(lower)
}

printLowest(100) // Prints 90
于 2020-12-23T11:03:32.643 回答
-1
public class Main    
{
    public static void main(String[] args)
    {   
        int[] numbers = {6,5,10,1,3,4,2,14,11,12};

        for(int i =0; i<numbers.length; i++)
        {
            sum(numbers, i, numbers[i], 12, String.valueOf(numbers[i]));
        }
    }

    static void sum(int[] arr, int i, int sum, int target, String s)
    {

        int flag = 0;

        for(int j = i+1; j<arr.length; j++)
        {

            if(arr[i] == target && flag==0)
            {
                System.out.println(String.valueOf(arr[i]));
                flag =1;

            }
            else if(sum+arr[j] == target)
            { 
                System.out.println(s+" "+String.valueOf(arr[j]));

            }
            else
            {
                sum(arr, j, sum+arr[j], target, s+" "+String.valueOf(arr[j]));
            }
        }        
    }
}
于 2018-02-03T02:40:27.350 回答
-7

这是我做的事情......

import javax.swing.JOptionPane;

public class NearestNumber {

public static void main(String[] arg)
{
    int[] array={100,-3420,3040,400433,500,-100,-200,532,6584,-945};

    String myNumberString =JOptionPane.showInputDialog(null,"Enter the number to test:");
    int myNumber = Integer.parseInt(myNumberString);

    int nearestNumber = findNearestNumber(array,myNumber);

    JOptionPane.showMessageDialog(null,"The nearest number is "+nearestNumber);
}

public static int findNearestNumber(int[] array,int myNumber)
{

    int min=0,max=0,nearestNumber;

    for(int i=0;i<array.length;i++)
    {
        if(array[i]<myNumber)
        {
            if(min==0)
            {
                min=array[i];
            }
            else if(array[i]>min)
            {
                min=array[i];
            }
        }
        else if(array[i]>myNumber)
        {
            if(max==0)
            {
                max=array[i];
            }
            else if(array[i]<max)
            {
                max=array[i];
            }
        }
        else
        {
            return array[i];
        }
    }

    if(Math.abs(myNumber-min)<Math.abs(myNumber-max))
    {
        nearestNumber=min;
    }
    else
    {
        nearestNumber=max;
    }

    return nearestNumber;
}

}

于 2012-11-10T10:06:18.110 回答