首页 > 其他 > 详细

[LeetCode]Product of Array Except Self

时间:2015-12-05 07:09:49      阅读:155      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!