-2

一个有数字的数组,例如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;
}

我试过这个,但它只返回准确的平均值,而不是最接近的值。

4

3 回答 3

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;
}
于 2012-10-23T11:06:39.413 回答
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]);
    }
于 2012-10-23T12:51:07.007 回答
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];
于 2012-10-23T10:48:54.750 回答