当前位置:  首页>> 技术小册>> 数据结构与算法(中)

难度: Medium

内容描述

  1. 给定n个整数的数组nums,其中n>1,返回一个数组输出,使得输出[i]等于nums[i]之外的所有nums元素的乘积。
  2. Example:
  3. Input: [1,2,3,4]
  4. Output: [24,12,8,6]
  5. Note: Please solve it without division and in O(n).
  6. Follow up:
  7. Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)

解题方案

思路 1
**- 时间复杂度: O(N)**- 空间复杂度: O(N)**

前缀积和后缀积, 懒得实现了

Follow up:

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

思路 1
**- 时间复杂度: O(N)**- 空间复杂度: O(1)**

还是一样的思想,只不过不记录下来,而是采用边循环边更新的方式

beats 100.00%

  1. class Solution {
  2. public int[] productExceptSelf(int[] nums) {
  3. int[] res = new int[nums.length];
  4. for (int i = 0; i < nums.length; i++) {
  5. res[i] = 1;
  6. }
  7. int left = 1;
  8. for (int i = 0; i < nums.length - 1; i++) {
  9. left *= nums[i];
  10. res[i+1] *= left;
  11. }
  12. int right = 1;
  13. for (int i = nums.length - 1; i > 0; i--) {
  14. right *= nums[i];
  15. res[i-1] *= right;
  16. }
  17. return res;
  18. }
  19. }

该分类下的相关小册推荐: