給你一個vector<int> nums,輸出所有vector的乘積除了自己。
- 因為每個答案和除了自己之外,前後的乘積,所以使用two-pass。
- 先計算出自己以外的forward和backward,最後把兩個vector乘起來就是答案。
vector<int> productExceptSelf(vector<int>& nums) {
int sz = nums.size();
vector<int> fw(sz, 1), bw(sz, 1);
for(int i = 1; i < sz; ++i) {
fw[i] = nums[i - 1] * fw[i - 1];
}
for(int i = sz - 2; i >= 0; --i) {
bw[i] = nums[i + 1] * bw[i + 1];
}
vector<int> rtn(sz);
for(int i = 0; i < sz; ++i)
rtn[i] = fw[i] * bw[i];
return rtn;
}
給你一個vector<int>只有binary 0和1,一定要刪除一個element,試找出最長的連續1的subarray。
- 因為一定要刪除一個element,所以等於第i個的前面和後面連續的1的長度總和,所以使用two pass。
- 先計算forward和backward,再找出刪除一個element之後的最長subarray。
int longestSubarray(vector<int>& nums) {
int sz = nums.size();
vector<int> bwd(sz), fwd(sz);
bwd[0] = nums[0];
for(int i = 1; i < sz; ++i) {
if(nums[i]) bwd[i] = bwd[i - 1] + 1;
}
fwd[sz - 1] = nums[sz - 1];
for(int i = sz - 2; i >= 0; --i) {
if(nums[i]) fwd[i] = fwd[i + 1] + 1;
}
int ans{};
for(int i = 0; i < sz; ++i) {
ans = max(ans, (i - 1 >= 0 ? bwd[i - 1] : 0) +
(i + 1 < sz ? fwd[i + 1] : 0));
}
return ans;
}
or
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up
Syntax | Example | Reference | |
---|---|---|---|
# Header | Header | 基本排版 | |
- Unordered List |
|
||
1. Ordered List |
|
||
- [ ] Todo List |
|
||
> Blockquote | Blockquote |
||
**Bold font** | Bold font | ||
*Italics font* | Italics font | ||
~~Strikethrough~~ | |||
19^th^ | 19th | ||
H~2~O | H2O | ||
++Inserted text++ | Inserted text | ||
==Marked text== | Marked text | ||
[link text](https:// "title") | Link | ||
 | Image | ||
`Code` | Code |
在筆記中貼入程式碼 | |
```javascript var i = 0; ``` |
|
||
:smile: | ![]() |
Emoji list | |
{%youtube youtube_id %} | Externals | ||
$L^aT_eX$ | LaTeX | ||
:::info This is a alert area. ::: |
This is a alert area. |
On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?
Please give us some advice and help us improve HackMD.
Syncing