|
| 1 | +(* |
| 2 | +Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. |
| 3 | +
|
| 4 | +The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. |
| 5 | +
|
| 6 | +You must write an algorithm that runs in O(n) time and without using the division operation. |
| 7 | +
|
| 8 | +Example 1: |
| 9 | +
|
| 10 | +Input: nums = [1,2,3,4] |
| 11 | +Output: [24,12,8,6] |
| 12 | +Example 2: |
| 13 | +
|
| 14 | +Input: nums = [-1,1,0,-3,3] |
| 15 | +Output: [0,0,9,0,0] |
| 16 | +
|
| 17 | +Constraints: |
| 18 | +
|
| 19 | +2 <= nums.length <= 105 |
| 20 | +-30 <= nums[i] <= 30 |
| 21 | +The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. |
| 22 | +
|
| 23 | +Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.) |
| 24 | +*) |
| 25 | + |
| 26 | +(* |
| 27 | +time O(n) |
| 28 | +space O(1) |
| 29 | +*) |
| 30 | +let product_except_self (nums : int array) : int array = |
| 31 | + let nums_length = Array.length nums in |
| 32 | + |
| 33 | + let suffix, _, _ = |
| 34 | + Array.fold_right |
| 35 | + (fun num (suffix, i, product) -> |
| 36 | + suffix.(i) <- product; |
| 37 | + (suffix, i - 1, product * num)) |
| 38 | + nums |
| 39 | + (Array.make nums_length 0, nums_length - 1, 1) |
| 40 | + in |
| 41 | + |
| 42 | + let nums, _, _ = |
| 43 | + Array.fold_left |
| 44 | + (fun (nums, i, product) num -> |
| 45 | + nums.(i) <- product * suffix.(i); |
| 46 | + (nums, i + 1, product * num)) |
| 47 | + (nums, 0, 1) nums |
| 48 | + in |
| 49 | + nums |
| 50 | + |
| 51 | +(* |
| 52 | +time O(n) |
| 53 | +space O(1) |
| 54 | +*) |
| 55 | +let product_except_self_2 (nums : int array) : int array = |
| 56 | + let nums_length = Array.length nums in |
| 57 | + let suffix = Array.make nums_length 0 in |
| 58 | + |
| 59 | + let product = ref 1 in |
| 60 | + for i = nums_length - 1 downto 0 do |
| 61 | + suffix.(i) <- !product; |
| 62 | + product := !product * nums.(i) |
| 63 | + done; |
| 64 | + |
| 65 | + let product = ref 1 in |
| 66 | + for i = 0 to nums_length - 1 do |
| 67 | + let num = nums.(i) in |
| 68 | + nums.(i) <- !product * suffix.(i); |
| 69 | + product := !product * num |
| 70 | + done; |
| 71 | + |
| 72 | + nums |
| 73 | + |
| 74 | +let () = |
| 75 | + Printf.printf "v1: example 1: %b\n" |
| 76 | + (product_except_self [| 1; 2; 3; 4 |] = [| 24; 12; 8; 6 |]); |
| 77 | + |
| 78 | + Printf.printf "v1: example 2: %b\n" |
| 79 | + (product_except_self [| -1; 1; 0; -3; 3 |] = [| 0; 0; 9; 0; 0 |]); |
| 80 | + |
| 81 | + Printf.printf "v2: example 1: %b\n" |
| 82 | + (product_except_self_2 [| 1; 2; 3; 4 |] = [| 24; 12; 8; 6 |]); |
| 83 | + |
| 84 | + Printf.printf "v2: example 2: %b\n" |
| 85 | + (product_except_self_2 [| -1; 1; 0; -3; 3 |] = [| 0; 0; 9; 0; 0 |]) |
0 commit comments