leetcode:238. Product of Array Except Self (Java) solution

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.