在数组中查找最接近的数字

时间:2012-10-23 10:37:44

标签: java

包含数字的数组,例如1,2,3,4,5

我需要返回与整个数组的平均值具有最接近值的元素。 例如,

1+2+3+4+5=15
15/5=3

结果应该是数字3.

如果没有与平均值相同的数字,则结果应该是数组中最接近的数字。

我只需要返回该值的方法。

Integer sum = 0; 
Integer a = 0;
for(int i=0; i<array.getLength();i++)
{
   a = array.get(i); sum=sum+a; 
}
 Integer average= sum/array.getLength();
 return average;
}

我尝试了这个,但它只返回精确值作为平均值,而不是最接近的值。

3 个答案:

答案 0 :(得分:1)

这是一个简单的解决方案。可能会使用一些更聪明的算法来从数组中获取最接近的值(如果它已排序)。 如果有两个最接近平均值的数字,则选择在数组中首先出现的数字。

编辑更改了比较,因此最接近平均值的最低数字是foud。

public static Integer nearestToAverage(int[] res) {
    if (res.length < 1) {
        return null; //if there is no array return null;
    }
    int sum = 0; //variable to sum up the array
    for (int i = 0; i < res.length; i++) {
        int act = res[i];
        sum += act; //adding elements of array to sum
    }
    int avg = sum / res.length; //computing the average value
    int minDistance = Integer.MAX_VALUE; //set distance to integer max so it is higher than any of values in array
    Integer ret = null; //setting return value to null it will be replaced with value from array
    for (int i = 0; i < res.length; i++) {
        int act = res[i];
        int actDistance = Math.abs(act - avg); //computing distance of actual value and average
        if ((actDistance < minDistance) || ((actDistance == minDistance) && (act < ret))) { //if it is less than actual minimal distance or it is the same and act number is lower than return value
            minDistance = actDistance; //the distance is set to new
            ret = act; //also is return value
        }
    }
    return ret;
}

答案 1 :(得分:1)

void findelement()
    {
        int[] arr = {1,2,3,4,5};
        int a`enter code here`ve = 3, elem=0;
        long tempi=0, tempdiff;
        long diff=-1;
        for(int i=0; i<arr.length;i++)
        {
            tempdiff = (long)arr[i]-(long)ave;
            tempdiff = (tempdiff < 0 ? -tempdiff : tempdiff);
            diff = (diff==-1)?tempdiff : diff;
            if(diff>tempdiff){
                diff = tempdiff;
                elem = i;
            }
        }
        System.out.println("hi element is "+elem+" and value near to average is "+arr[elem]);
    }

答案 2 :(得分:0)

试试这个::

int[] arr = {1,2,3,4,5};
double closeDiff = 0;
double arravg = getAverage(arr); // write a method which will return the average
int resultIndex = 0;

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

  if(arr[i-1] > arr[i])
  tempDiff = (arr[i-1] - arr[i]);
  else
    tempDiff = (-arr[i-1] + arr[i]);
  if(tempDiff<closeDiff)
   resultIndex = i;
}
return arr[i];