【Leetcode】Product of Array Except Self
  iVhBmnbWORLX 2023年11月02日 98 0


题目链接:https://leetcode.com/problems/product-of-array-except-self/

题目:

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

Solve it without division and in O(n).

[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

思路:

1、规避除法。用两个数组描述元素左、右边乘积,结果就是该元素左右乘积之积。空间复杂度为O(n)

2、在上述思路基础上减少数组的使用,用result代替右边的乘积,再用一个常数表示元素左边乘积。

算法1:

public int[] productExceptSelf(int[] nums) {
		int right[] = new int[nums.length]; //元素右边乘积
		int left[] = new int[nums.length];//
		int result[] = new int[nums.length];
		for (int i = nums.length - 1; i >= 0; i--) {
			if (i == nums.length - 1) {
				right[i] = 1;
			} else {
				right[i] = right[i + 1] * nums[i + 1];
			}
		}
		for (int i = 0; i < nums.length; i++) {
			if (i == 0) {
				left[i] = 1;
			} else {
				left[i] = left[i - 1] * nums[i - 1];
			}
		}
		for (int i = 0; i < nums.length; i++) {
			result[i] = right[i] * left[i];
		}
		return result;
	}




算法2:

public int[] productExceptSelf(int[] nums) {
		int result[] = new int[nums.length];
		for (int i = nums.length - 1; i >= 0; i--) { //元素右边乘积
			if (i == nums.length - 1) {
				result[i] = 1;
			} else {
				result[i] = result[i + 1] * nums[i + 1];
			}
		}
		int left = 0;//左边乘积
		for (int i = 0; i < nums.length; i++) {
			if (i == 0) {
				left = 1;
			} else {
				left= left * nums[i - 1];
				result[i] = result[i] * left;
			}
		}
		return result;
	}




【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  gBkHYLY8jvYd   2023年12月06日   48   0   0 #includecii++
  gBkHYLY8jvYd   2023年12月09日   29   0   0 cii++数据
  gBkHYLY8jvYd   2023年12月06日   23   0   0 cii++依赖关系
  lh6O4DgR0ZQ8   2023年11月24日   17   0   0 cii++c++
  gBkHYLY8jvYd   2023年11月22日   22   0   0 ioscii++
  zLxnEsMLk4BL   2023年11月19日   29   0   0 数组字符串数组名
  X5zJxoD00Cah   2023年11月19日   18   0   0 数组单引号字符串
  gBkHYLY8jvYd   2023年12月10日   22   0   0 #include数组i++
  gBkHYLY8jvYd   2023年12月08日   20   0   0 #includecii++
iVhBmnbWORLX