숫자의 배열을 지정해, 분열하지 않고 다른 번호의 제품의 배열을 반환?

존 :

나는 최근에 전화를 통해 다음과 같은 인터뷰 질문을했다 :

정수 배열을 감안할 때, 그 값이 현재 인덱스를 제외한 다른 모든 정수의 곱이다 어레이를 생성한다.

예:

[4, 3, 2, 8] -> [3 * 8 * 2, 4 * 8 * 2, 4 * 8 3, 4 * 3 * 2 -> [48, 64, 96, 24]

나는 아래의 코드를 함께했다 :

public static BigInteger[] calcArray(int[] input) throws Exception {
    if (input == null) {
        throw new IllegalArgumentException("input is null");
    }
    BigInteger product = calculateProduct(input);
    BigInteger result[] = new BigInteger[input.length];
    for (int i = 0; i < input.length; i++) {
        result[i] = product.divide(BigInteger.valueOf(input[i]));
    }
    return result;
}

private static BigInteger calculateProduct(int[] input) {
    BigInteger result = BigInteger.ONE;
    for (int i = 0; i < input.length; i++) {
        result = result.multiply(BigInteger.valueOf(input[i]));
    }
    return result;
}

복잡성:

Time Complexity: O(n)
Space Complexity: O(n)

우리는이 부문없이 O (n)이 복잡 할 수 있습니까? 또한 사용하는 간단한 정수 배열 프리미티브 경우 공간 복잡도를 줄일 수있는 방법이있다.

SomeDude :

인덱스에있는 요소를 고려한다 i. 그 왼쪽에 봐, 우리는 인덱스까지 요소의 제품을 가지고 있다고 할 수 있습니다 i-1. 를 호출 할 수 있습니다 leftProduct[i]에서 요소의 왼쪽에있는 모든 요소의 제품입니다 i. 마찬가지로 호출 할 수 있습니다 rightProduct[i]에서 요소의 오른쪽에있는 모든 요소의 제품입니다 i. 그런 다음 인덱스에 대한 결과는output[i] = leftProduct[i]*rightProduct[i]

이제 도착하는 방법에 대해 생각 leftProduct. 당신은 단순히 처음부터 배열을 통과하고 실행중인 제품을 계산하고 각 요소의 업데이트에서 leftProduct현재 실행중인 제품과 함께. 마찬가지로 당신은 계산할 수 있습니다 rightProduct끝에서 배열을 통과하여. 여기에서 다시 사용하여 공간을 최적화 leftProduct승산으로 업데이트하여 배열 rightProduct.

코드 아래는이 보여줍니다

public static int[] getProductsExcludingCurrentIndex( int[] arr ) {
     if ( arr == null || arr.length == 0 ) return new int[]{};
     int[] leftProduct = new int[arr.length];
     int runningProduct = 1;
     //Compute left product at each i
     for ( int i = 0; i < arr.length; i++ ) {
       leftProduct[i] = runningProduct;
       runningProduct = runningProduct*arr[i];
    }
    runningProduct = 1;
    //By reverse traversal, we compute right product but at the same time update the left 
    //product, so it will have leftProduct*rightProduct
    for ( int i = arr.length - 1; i >= 0; i-- ) {
        leftProduct[i] = leftProduct[i]*runningProduct;
        runningProduct = runningProduct*arr[i];
    }
    return leftProduct;
}

공간의 복잡성은 O(n)- 우리는 하나 개의 배열을 사용 leftProduct, 시간 복잡도이다 O(n).

  • 우주의 복잡성 편집 :

하지만 출력을 저장하기 위해 사용되는 공간을 고려하지 않는 경우,이는 O(1)우리가 출력을 저장하고 있기 때문에, leftProduct그 자체.

당신이 엄격하게 한 후 여분의 공간을 원하지 않는 경우 수반은 입력 배열을 변경하는 것이다. 당신이가는대로 입력 배열을 수정하여이 문제를 해결하는 것은 내가 아는 한 적어도 전혀 할 수 없습니다.

추천

출처http://43.154.161.224:23101/article/api/json?id=213047&siteId=1