面试题66:构建乘积数组

这道题真是扩展思维啊,我服了:

import java.util.Arrays;

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(Arrays.toString(s.multiply(new int[]{1, 2, 3, 4, 5, 6})));
    }

    public int[] multiply(int[] arr) {
        int[] res = new int[arr.length];
        res[0] = 1;

        for (int i = 1; i < arr.length; i++) {
            res[i] = res[i - 1] * arr[i - 1];
        }

        int temp = arr[arr.length - 1];
        for (int i = arr.length - 2; i >= 0; i--) {
            res[i] *= temp;
            temp *= arr[i];
        }

        return res;
    }
}
posted @ 2018-03-25 12:00  optor  阅读(103)  评论(0编辑  收藏  举报