Code Interview Guide for Programmers Chapter 8 Arrays and Matrix Questions that do not contain multiplicative arrays of values in this position

topic

不包含本位置值的累乘数组

java code

package com.lizhouwei.chapter8;

/**
 * @Description: 不包含本位置值的累乘数组
 * @Author: lizhouwei
 * @CreateDate: 2018/5/9 21:11
 * @Modify by:
 * @ModifyDate:
 */
public class Chapter8_22 {

    public int[] product(int[] arr) {
        int[] res = new int[arr.length];
        int product = 1;
        for (int i = 0; i < arr.length; i++) {
            res[i] = product * arr[i];
            product = product * arr[i];
        }
        product = 1;
        for (int i = arr.length - 1; i > 0; i--) {
            res[i] = res[i - 1] * product;
            product = product * arr[i];
        }
        res[0] = product;
        return res;
    }

    //测试
    public static void main(String[] args) {
        Chapter8_22 chapter = new Chapter8_22();
        int[] arr = {2, 3, 1, 4};
        int[] res = chapter.product(arr);
        for (int i = 0; i < res.length; i++) {
            System.out.print(res[i] + " ");
        }
    }
}

result

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326611640&siteId=291194637