Skip to content

Latest commit

 

History

History
29 lines (28 loc) · 771 Bytes

238.md

File metadata and controls

29 lines (28 loc) · 771 Bytes

#238. Product of Array Except Self 题目链接

时间复杂度O(n),空间复杂度O(1)

public class Solution {
    public int[] productExceptSelf(int[] nums) {
        long sum = 1;
        int zeroNum = 0;
        for (int num : nums) {
            if (num == 0) {
                zeroNum++;
                continue;
            }
            sum *= num;
        }
        for (int i = nums.length - 1; i >= 0; i--) {
            if (zeroNum > 1) {
                nums[i] = 0;
            } else if (zeroNum == 1) {
                nums[i] = nums[i] == 0 ? (int) sum : 0;
            } else {
                nums[i] = (int) sum / nums[i];
            }
        }
        return nums;
    }
}