[LeetCode] Product of Array Except Self

简介: The first answer in this link has a nice illustrative explanation. Suppose the given array is like [nums[0], nums[1], nums[2], nums[3]].

The first answer in this link has a nice illustrative explanation.

Suppose the given array is like [nums[0], nums[1], nums[2], nums[3]]. Then the result array is simply the product of corresponding terms (with the same color) of these two arrays:

[                 1,        nums[0], nums[0] * nums[1], nums[0] * nums[1] * nums[2]]

[nums[1] * nums[2] * nums[3], nums[2] * nums[3],        nums[3],                  1]

Have you noticed the regularities :-)

The code is as follows.

 1 class Solution {
 2 public:
 3     vector<int> productExceptSelf(vector<int>& nums) {
 4         int n = nums.size();
 5         vector<int> prod(n, 1);
 6         for (int i = 1; i < n; i++)
 7             prod[i] = prod[i - 1] * nums[i - 1];
 8         for (int i = n - 1, r = 1; i >= 0; r *= nums[i--])
 9             prod[i] *= r;
10         return prod;
11     }
12 };

 

目录
相关文章
|
10月前
Leetcode Find Minimum in Rotated Sorted Array 题解
对一个有序数组翻转, 就是随机取前K个数,移动到数组的后面,然后让你找出最小的那个数,注意,K有可能是0,也就是没有翻转。
37 0
|
算法
LeetCode 330. Patching Array
给定一个已排序的正整数数组 nums,和一个正整数 n 。从 [1, n] 区间内选取任意个数字补充到 nums 中,使得 [1, n] 区间内的任何数字都可以用 nums 中某几个数字的和来表示。请输出满足上述要求的最少需要补充的数字个数。
66 0
LeetCode 330. Patching Array
|
存储 Python
LeetCode 315. Count of Smaller Numbers After Self
给定一个整数数组 nums,按要求返回一个新数组 counts。数组 counts 有该性质: counts[i] 的值是 nums[i] 右侧小于 nums[i] 的元素的数量。
89 0
LeetCode 315. Count of Smaller Numbers After Self
LeetCode 238. Product of Array Except Self
给定长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output ,其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积。
77 0
LeetCode 238. Product of Array Except Self
LeetCode 189. Rotate Array
给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
71 0
LeetCode 189. Rotate Array
|
算法
LeetCode Find Minimum in Rotated Sorted Array II
假设按照升序排序的数组在预先未知的某个点上进行了旋转。 ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 请找出其中最小的元素。 注意数组中可能存在重复的元素。
78 0
LeetCode Find Minimum in Rotated Sorted Array II
LeetCode 153. Find Minimum in Rotated Sorted Array
假设按照升序排序的数组在预先未知的某个点上进行了旋转。 ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 请找出其中最小的元素。 你可以假设数组中不存在重复元素。
99 0
LeetCode 153. Find Minimum in Rotated Sorted Array
LeetCode 88. Merge Sorted Array
题意是给定了两个排好序的数组,让把这两个数组合并,不要使用额外的空间,把第二个数组放到第一个数组之中.
75 0
LeetCode 88. Merge Sorted Array
|
索引
LeetCode 81. Search in Rotated Sorted Array II
假设按升序排序的数组在事先未知的某个枢轴处旋转。 (例如, [0,0,1,2,2,5,6] 可能变成 [2,5,6,0,0,1,2]). 给定一个要搜索的目标值T, 如果该目标值能在数组中找到则返回true,否则返回false。
81 0
LeetCode 81. Search in Rotated Sorted Array II
LeetCode 80 Remove Duplicates from Sorted Array II
给定排序的数组nums,就地删除重复项,使重复项最多出现两次并返回新的长度. 不要为另一个数组分配额外的空间,必须通过使用O(1)复杂度的额外空间来修改输入数组,从而实现此目的.
63 0
LeetCode 80 Remove Duplicates from Sorted Array II