码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Product of Array Except Self

时间:2015-12-05 07:10:00      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

public class Solution {
    public int[] productExceptSelf(int[] nums) {
        int length = nums.length;
        int[] result = new int[length];
        int tmp = 1;
        for (int i = 0; i < length - 1; i++) {
            tmp *= nums[i];
            result[i] = tmp;
        }
        tmp = 1;
        for (int i = length - 1; i > 0; i--) {
            result[i] = tmp * result[i - 1];
            tmp *= nums[i];
        }
        result[0] = tmp;
        return result;
    }
}

 使用除法的话,要注意一下0

public class Solution {
    public int[] productExceptSelf(int[] nums) {
        int length = nums.length;
        int[] result = new int[length];
        int zero = 0;
        int index = 0;
        int tmp = 1;
        for (int i = 0; i < length; i++) {
            int num = nums[i];
            if (num == 0) {
                if (zero > 0) {
                    return result;
                } 
                zero ++;
                index = i;
            } else {
                tmp *= num;
            }
        }
        if (zero != 0) {
            result[index] = tmp;
            return result;
        }
        for (int i = 0; i < length; i++) {
            result[i] = tmp / nums[i];
        }
        return result;
    }
}

 

[LeetCode]Product of Array Except Self

标签:

原文地址:http://www.cnblogs.com/vision-love-programming/p/5020929.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!