LeetCode Product of Array Except Self

BabbleDay posted @ 2015年7月17日 15:45 in 刷题防身 with tags java leetcode Product of Array Except Self , 1016 阅读

过早优化是万恶之源= =

public class Solution {
    public int[] productExceptSelf(int[] nums) {
        int l = nums.length;
        int[] output = new int[l];
        int[] a = new int[l];
        int[] b = new int[l];
        for(int i=0; i<l; i++){
            a[i] = 1;
            b[i] = 1;
        }
        for(int i=1; i<l; i++){
            int j = l-i-1;
            a[i] *= nums[i-1] * a[i-1];
            b[j] *= nums[j+1] * b[j+1];
        }
        for(int i=0; i<l; i++) output[i] = a[i] * b[i];
        return output;
    }
}

 

优化:用一个变量代替数组

public class Solution {
public int[] productExceptSelf(int[] nums) {
    int n = nums.length;
    int[] res = new int[n];
    res[0] = 1;
    for (int i = 1; i < n; i++) {
        res[i] = res[i - 1] * nums[i - 1];
    }
    int right = 1;
    for (int i = n - 1; i >= 0; i--) {
        res[i] *= right;
        right *= nums[i];
    }
    return res;
}
Avatar_small
remote desktop windo 说:
2019年1月02日 00:52

One could retrieve the credit scores for windows 10 desktop vouchers, with presently promo codes available to retrieve.

Avatar_small
Best PC Optimizer So 说:
2019年7月26日 01:29

Informative article and looking ahead to analyzing more. I'm hoping it is going to be useful for too many people who are searching for this topic.

Avatar_small
CGBSE Question Paper 说:
2022年9月05日 00:19

CG Board Model Paper 2023 Class 9 Pdf Download with Answers for English Medium, Hindi Medium, Urdu Medium & Students for Small Answers, Long Answer, Very Long Answer Questions, and Essay Type Questions to Term1 & Term2 Exams at official website. CGBSE Question Paper Class 9 New Exam Scheme or Question Pattern for Sammittive Assignment Exams (SA1 & SA2): Very Long Answer (VLA), Long Answer (LA), Small Answer (SA), Very Small Answer (VSA), Single Answer, Multiple Choice and etc.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter