LeetCode实战:除自身以外数组的乘积

背景


题目英文

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

Example:

Input:  [1,2,3,4]
Output: [24,12,8,6]

Note: Please solve it without division and in 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.)


题目中文

给定长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output,其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积。

示例:

输入: [1,2,3,4]
输出: [24,12,8,6]

说明: 请不要使用除法,且在 O(n) 时间复杂度内完成此题。

进阶

你可以在常数空间复杂度内完成这个题目吗?( 出于对空间复杂度分析的目的,输出数组不被视为额外空间。)


算法实现

public class Solution
{
    public int[] ProductExceptSelf(int[] nums)
    {
        int len = nums.Length;
        int[] output1 = new int[len];//正向乘积
        int[] output2 = new int[len];//反向乘积
        output1[0] = 1;
        output2[len - 1] = 1;
        for (int i = 1; i < len; i++)
        {
            output1[i] = output1[i - 1]*nums[i - 1];
            output2[len - i - 1] = output2[len - i]*nums[len - i];
        }
        for (int i = 0; i < len; i++)
        {
            output1[i] *= output2[i];
        }
        return output1;
    }
}

实验结果

  • 状态:通过
  • 17 / 17 个通过测试用例
  • 执行用时: 304 ms, 在所有 C# 提交中击败了 100.00% 的用户
  • 内存消耗: 34.6 MB, 在所有 C# 提交中击败了 100.00% 的用户

提交结果


相关图文

1. “数组”类算法

2. “链表”类算法

3. “栈”类算法

4. “队列”类算法

5. “递归”类算法

6. “位运算”类算法

7. “字符串”类算法

8. “树”类算法

9. “哈希”类算法

10. “排序”类算法

11. “搜索”类算法

12. “动态规划”类算法

13. “回溯”类算法

14. “数值分析”类算法

发布了573 篇原创文章 · 获赞 327 · 访问量 129万+

猜你喜欢

转载自blog.csdn.net/LSGO_MYP/article/details/101151177
今日推荐