File tree 2 files changed +31
-0
lines changed
2 files changed +31
-0
lines changed Original file line number Diff line number Diff line change 149
149
234|[ Palindrome Linked List] ( ./0234-palindrome-linked-list.js ) |Easy|
150
150
235|[ Lowest Common Ancestor of a Binary Search Tree] ( ./0235-lowest-common-ancestor-of-a-binary-search-tree.js ) |Easy|
151
151
237|[ Delete Node in a Linked List] ( ./0237-delete-node-in-a-linked-list.js ) |Easy|
152
+ 238|[ Product of Array Except Self] ( ./0238-product-of-array-except-self.js ) |Medium|
152
153
242|[ Valid Anagram] ( ./0242-valid-anagram.js ) |Easy|
153
154
263|[ Ugly Number] ( ./0263-ugly-number.js ) |Easy|
154
155
264|[ Ugly Number II] ( ./0264-ugly-number-ii.js ) |Medium|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 238. Product of Array Except Self
3
+ * https://leetcode.com/problems/product-of-array-except-self/
4
+ * Difficulty: Medium
5
+ *
6
+ * Given an integer array nums, return an array answer such that answer[i] is equal to the product
7
+ * of all the elements of nums except nums[i].
8
+ *
9
+ * The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
10
+ *
11
+ * You must write an algorithm that runs in O(n) time and without using the division operation.
12
+ */
13
+
14
+ /**
15
+ * @param {number[] } nums
16
+ * @return {number[] }
17
+ */
18
+ var productExceptSelf = function ( nums ) {
19
+ const emptyResult = new Array ( nums . length ) . fill ( 0 ) ;
20
+ const zeroCount = nums . filter ( n => n === 0 ) . length ;
21
+ if ( zeroCount > 1 ) {
22
+ return emptyResult ;
23
+ }
24
+ const product = nums . reduce ( ( product , n ) => product * ( n === 0 ? 1 : n ) , 1 ) ;
25
+ if ( zeroCount === 1 ) {
26
+ emptyResult [ nums . indexOf ( 0 ) ] = product ;
27
+ return emptyResult ;
28
+ }
29
+ return nums . map ( n => product / n ) ;
30
+ } ;
You can’t perform that action at this time.
0 commit comments