Reprint Please specify source: Z_zhaojun's Blog
Original address
Title Address
Product of Array Except self
Given an array ofn integerswheren >1, Nums,returnAn array output such thatOutput[i] is Equal to theProduct ofAll theElements ofNums except Nums[i]. Solveit withoutDivision and inchO (n). For example,given[1,2,3,4],return[ -, A,8,6]. Follow up:could You solveit with constant SpaceComplexity? (note:the output Arraydoes not Count asExtraSpace for thePurpose of SpaceComplexity analysis.) Subscribe toSee which companies asked this question
Solution (Java):
Public int[]productexceptself(int[] nums) {//if (Nums = = NULL | | Nums.length < 2) { //return null; // } intFirst = nums[0];intProduct =1;intNumzero =0; for(intVal:nums) {if(val = =0) {numzero++;if(Numzero = =2) { Break; } }Else{Product *= val; }} nums[0] = (Numzero = =2) ?0: (Numzero = =0? Product/first: (First = =0? Product:0)); for(inti =1; i < nums.length; i++) {Nums[i] = (Numzero = =2) ?0: (Numzero = =0? Product/nums[i]: (nums[i] = =0? Product:0)); }returnNums }
leetcode:238. Product of Array Except Self (Java) solution