From bc242ad7c0a80fffd2b68d1d7746f470e0c13235 Mon Sep 17 00:00:00 2001 From: ScarboroughCoral <3249977074@qq.com> Date: Thu, 4 Jun 2020 09:41:20 +0800 Subject: [PATCH] feat:add typescript, rust, cpp solutions for 238 --- .../Solution.cpp | 23 +++++++++++++++++++ .../Solution.rs | 13 +++++++++++ .../Solution.ts | 11 +++++++++ 3 files changed, 47 insertions(+) create mode 100644 solution/0200-0299/0238.Product of Array Except Self/Solution.cpp create mode 100644 solution/0200-0299/0238.Product of Array Except Self/Solution.rs create mode 100644 solution/0200-0299/0238.Product of Array Except Self/Solution.ts diff --git a/solution/0200-0299/0238.Product of Array Except Self/Solution.cpp b/solution/0200-0299/0238.Product of Array Except Self/Solution.cpp new file mode 100644 index 0000000000000..af9784e5896a7 --- /dev/null +++ b/solution/0200-0299/0238.Product of Array Except Self/Solution.cpp @@ -0,0 +1,23 @@ +class Solution +{ +public: + vector productExceptSelf(vector &nums) + { + vector dpLeft(nums.size(), 1); + vector dpRight(nums.size(), 1); + for (int i = 1; i < nums.size(); i++) + { + dpLeft[i] = dpLeft[i - 1] * nums[i - 1]; + } + for (int i = nums.size() - 2; i >= 0; i--) + { + dpRight[i] = dpRight[i + 1] * nums[i + 1]; + } + vector result; + for (int i = 0; i < nums.size(); i++) + { + result.push_back(dpLeft[i] * dpRight[i]); + } + return result; + } +}; \ No newline at end of file diff --git a/solution/0200-0299/0238.Product of Array Except Self/Solution.rs b/solution/0200-0299/0238.Product of Array Except Self/Solution.rs new file mode 100644 index 0000000000000..5949b992c430d --- /dev/null +++ b/solution/0200-0299/0238.Product of Array Except Self/Solution.rs @@ -0,0 +1,13 @@ +impl Solution { + pub fn product_except_self(nums: Vec) -> Vec { + let mut dp_left=vec![1_i32;nums.len()]; + let mut dp_right=vec![1_i32;nums.len()]; + for i in 1..nums.len(){ + dp_left[i]=dp_left[i-1]*nums[i-1]; + } + for i in (0..(nums.len()-1)).rev(){ + dp_right[i]=dp_right[i+1]*nums[i+1]; + } + dp_left.into_iter().enumerate().map(|(i,x)| x*dp_right[i]).collect() + } +} \ No newline at end of file diff --git a/solution/0200-0299/0238.Product of Array Except Self/Solution.ts b/solution/0200-0299/0238.Product of Array Except Self/Solution.ts new file mode 100644 index 0000000000000..569310acfe5d7 --- /dev/null +++ b/solution/0200-0299/0238.Product of Array Except Self/Solution.ts @@ -0,0 +1,11 @@ +function productExceptSelf(nums: number[]): number[] { + let dpLeft = Array(nums.length).fill(1); + let dpRight = Array(nums.length).fill(1); + for (let i = 1; i < nums.length; i++) { + dpLeft[i] = dpLeft[i - 1] * nums[i - 1]; + } + for (let i = nums.length - 2; i >= 0; i--) { + dpRight[i] = dpRight[i + 1] * nums[i + 1]; + } + return dpLeft.map((x, i) => x * dpRight[i]); +}