LeetCode[238] Product of Array Except Self

来源:互联网 发布:sublime java高亮显示 编辑:程序博客网 时间:2024/06/07 05:44

Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements ofnums except nums[i].

Solve it without division and in O(n).

For example, given [1,2,3,4], return [24,12,8,6].

Follow up:
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)

这个题比较坑,要考虑有0的情况,如果nums只有一个0,那result 除了nums为0的位置是其他所有数的乘积以外其余的位置均为0,如果有两个及以上的0,整个数组全为0

class Solution {public:vector<int> productExceptSelf(vector<int>& nums) {int product = 1, zeroCount = 0;for (int i = 0; i < nums.size(); i++){if (nums[i] == 0){zeroCount++;continue;}product *= nums[i];}if (zeroCount == 0){vector<int> result;for (int i = 0; i < nums.size(); i++)result.push_back(product / nums[i]);return result;}else{vector<int> result(nums.size(), 0);if (zeroCount == 1){for (int i = 0; i < nums.size(); i++){if (nums[i] == 0)result[i] = product;}}return result;}}};

0 0
原创粉丝点击