Re: [閒聊] 每日LeetCode

作者: wu10200512 (廷廷)   2024-02-01 16:29:11
多寫一題
先把0的位置存起來然後再看要乘回去還怎樣的
我看解答有一個左邊乘過去然後再從右邊乘過來的
比我快一倍
但我看不懂 算惹
238. Product of Array Except Self
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
vector<int> zero_pos;
int acc=1;
int n=nums.size();
vector<int> ans(n,0);
for(int i=0; i<n; i++){
if(nums[i]==0){
zero_pos.push_back(i);
}
else{
acc*=nums[i];
}
}
if(zero_pos.size()==1){
ans[zero_pos[0]]=acc;
return ans;
}
else if(zero_pos.size()>1){
return ans;
}
for(int i=0; i<n; i++){
ans[i]=acc/nums[i];
}
return ans;
}
};
作者: JIWP (JIWP)   2024-02-01 16:42:00
那個你模擬一次就知道了

Links booklink

Contact Us: admin [ a t ] ucptt.com