中级农民
- 积分
- 100
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2021-2-28
- 最后登录
- 1970-1-1
|
第一题有0的情况写一个:
- class Solution {
- public:
- vector<int> productExceptSelf(vector<int>& nums) {
- int n = nums.size();
-
- vector<int> result(n, 0); //default all zero
- int left_zero_idx = -1, right_zero_idx = -1;
- int left = 1, right = 1;
-
- for (int i = 0; i < n; i++) {
- if (nums[i] == 0) {
- left_zero_idx = i;
- break;
- }
-
- left = left * nums[i];
- }
-
- for (int i = n - 1; i >= 0; i--) {
- if (nums[i] == 0) {
- right_zero_idx = i;
- break;
- }
-
- right = right * nums[i];
- }
-
- if (left_zero_idx != right_zero_idx) //two "0" found
- return result;
-
- int total;
- if (left_zero_idx != -1) //one "0" found
- total = 0;
- else
- total = left; //no "0" found
-
- for (int i = 0; i < n; i++) {
- if (nums[i] == 0) //If we come here, then we are sure there is only one "0"
- result[i] = left * right;
- else
- result[i] = total / nums[i];
- }
-
- return result;
- }
- };
复制代码
|
|