2012-10-23 221 views
-3

A具有數字的數組,例如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; 
} 

我試過這個,但它只返回精確值作爲平均值,而不是最接近的值。

+1

它應該返回2號如果平均是3,並且陣列數字是2和4? – WozzeC

+0

不,它應該返回較小的數字,在這種情況下爲2. – Mario

+0

Integer sum = 0; \t整數a = 0;對於(int i = 0; i Mario

回答

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]; 
+0

對不起,但: 1)我沒有遵循你的邏輯,爲什麼試圖找到最接近avarage值,你比較兩個數組與對方的值? 2)你有範圍錯誤,我在你使用的返回語句超出了範圍,因爲它僅在語句 – user902383

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; 
} 
+0

內部定義哦,在此期間進行了一些編輯。如果你想要最小的最接近的數字,你可以添加,如果在與actDistance和minDistance進行比較的情況下,它是相等的,並選擇較小的ret值和act – Drobek

+0

謝謝,我會試試這個 – Mario

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]); 
    }