2016-01-20 31 views
0

我有一個int[]數組,其中x值(x可以由用戶定義),這些值是1到9之間的隨機整數。現在我想創建另一個數組的值,並且新數組的每個值都是來自另一個數組的所有值的乘積,除了相同的索引。Java - 將數組值乘到另一個數組

因此,例如:

  • 數組1:{4,3,5,7}
  • 數組2:{3*5*7, 4*5*7, 4*3*7, 4*3*5} = {105, 140, 84, 60}

這是我有:

public static int[] multiplyArrayValues (int [] values) { 

    int array[] = new int[values.length]; 

    for (int y = 0; y < array.length; y++) { 
     array[y] = 1; 
    } 

    /*for (int i = 0; i < array.length; i++) {  // wrong       
     for (int z = 0; z < x; z++) {       
      if (z != i) {             
       array[i] = array[i] * values[z];           
      }    
     }   
    }*/ 

    return array; 
} 

的困難是,我必須避免爲了性能而在循環中循環。這就是爲什麼這一塊被註釋掉了。分割是不允許的。

+0

允許'1'嗎?您不能從乘法結果中「排除」它:{1,1,2,3} => {1 * 2 * 3,1 * 2 * 3,1 * 1 * 3,1 * 1 * 2 } = {6,6,3,2}' –

+0

@SimonKraemer這些數字是隨機的,只是在1到9之間的atm。稍後,負數和/或用戶輸入將被添加。所以是的,1是允許的,即使它在你離開時沒有改變。 – abrjak01

回答

4

這更多的是關於要使用的算法的問題。你可以乘以原始數組的所有數字,讓我們打電話給這個p。現在新陣列中位置i的數字是p/values[i]

如果您不能使用除法,您可以設置兩個臨時數組,其中一個包含索引值較小或相等的值的乘積,另一個包含索引較大或相等的值的乘積。

s[i] = product of v[j] where j <= i 
l[i] = product of v[j] where j >= i 

兩個數組都可以用一個簡單的循環來設置。

現在您可以計算array[i]作爲s[i-1] * l[i+1],特別注意邊界值。這也需要一個簡單的循環。

使用這些想法,並做一些優化,導致下面的代碼

public static int[] multiplyArrayValues (int [] values) { 
    int[] a = new int[values.length]; 
    int p = 1; 
    for (int i = values.length - 1; i >= 0; i--) { 
     a[i] = p; 
     p *= values[i]; 
    } 
    p = 1; 
    for (int i = 0; i < values.length; i++) { 
     a[i] *= p; 
     p *= values[i]; 
    } 
    return a; 
} 
+0

我認爲要完整回答這個採訪問題,您應該將s/l包裝到源/目標數組對中(應該可以填充目標前進和腐敗源向後)。 OP應該詢問面試官是否允許額外的陣列以及腐蝕源是否正常。 –

2

首先乘以數組中的所有元素。然後遍歷所有元素並將之前計算的乘法除以當前項目。

1

即可成倍的所有號碼,並保存它的變量(比如產品),現在在陣列上使用單迴路迭代,並劃分產品按每個指數的數量(產品/ a [i])計算。

但是,由於您使用的是整數,如果數組的大小很大,並且數組值很大,則產品可能會溢出int。

考慮使用大整數我會說。

0
import java.util.Arrays; 

public class Main { 

    static int[] multiplyArrayValues(int[] values) { 
     int product = 1; 
     for(int i = 0; i < values.length; i++){ 
      product *= values[i]; 
     } 
     int[] result = new int[values.length]; 
     for (int i = 0; i < result.length; i++) { 
      result[i] = product/values[i]; 
     } 
     return result; 
    } 

    static void testMultiplyArrayValues(int[] values) 
    { 
     System.out.println(Arrays.toString(values) + " => " + Arrays.toString(multiplyArrayValues(values))); 
    } 


    public static void main(String[] args) { 
     testMultiplyArrayValues(new int[] {1,1,2,3}); 
     testMultiplyArrayValues(new int[] {4,3,5,7}); 
     testMultiplyArrayValues(new int[] {9,9,9,9}); 
     testMultiplyArrayValues(new int[] {1,1,1,1}); 
     testMultiplyArrayValues(new int[] {1,2,3,4}); 
    } 

} 

輸出:

[1, 1, 2, 3] => [6, 6, 3, 2] 
[4, 3, 5, 7] => [105, 140, 84, 60] 
[9, 9, 9, 9] => [729, 729, 729, 729] 
[1, 1, 1, 1] => [1, 1, 1, 1] 
[1, 2, 3, 4] => [24, 12, 8, 6] 

如果可能的值的範圍變化,你可能要改變的product的數據類型和multiplyArrayValues返回值。 也沒有檢查值爲負值或無效值。零將導致崩潰。

+0

由於分割是不允許的,我不能使用你的解決方案,但它會工作,非常感謝你! – abrjak01

+0

好的,我錯過了你的編輯... –

相關問題