【腾讯热题50-中等】238. 除自身以外数组的乘积

643 篇文章 5 订阅

题目
题目要求不要使用除法!!!
题目要求不要使用除法!!!
题目要求不要使用除法!!!
【代码】”违规操作“,一般思维模式,使用除法进行解题,正确解法,请看下面的方法2
执行用时:56 ms, 在所有 Python3 提交中击败了91.22% 的用户
内存消耗:19.7 MB, 在所有 Python3 提交中击败了68.85% 的用户
通过测试用例:20 / 20

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        cnt=Counter(nums)
        if 0 not in cnt:
            all=1
            for item in cnt:
                all*=item**cnt[item]
            ans=[]
            for item in nums:
                ans.append(all//item)
        else:
            all=1
            for item in cnt:
                if item!=0:
                    all*=item**cnt[item]
            ans=[]
            for item in nums:
                if (item==0 and cnt[item]>=2) or item:
                    ans.append(0)
                elif item==0 and cnt[item]<=1:
                    ans.append(all)
        return ans

【方法2】使用两个列表
时间复杂度O(n)
空间复杂度O(n)

执行用时:92 ms, 在所有 Python3 提交中击败了8.35% 的用户
内存消耗:22.9 MB, 在所有 Python3 提交中击败了15.06% 的用户
通过测试用例:20 / 20

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        cnt=Counter(nums)
        ans_left=[1]*len(nums)
        ans_right=[1]*len(nums)
        for i in range(1,len(nums)):
            ans_left[i]*=ans_left[i-1]*nums[i-1]                
            ans_right[len(nums)-i-1]*=ans_right[len(nums)-i]*nums[len(nums)-i]
        ans=[]
        for x,y in zip(ans_left,ans_right):
            ans.append(x*y)
        return ans

【方法3】
进阶版:空间复杂度O(1)
执行用时:92 ms, 在所有 Python3 提交中击败了8.35% 的用户
内存消耗:19.9 MB, 在所有 Python3 提交中击败了60.37% 的用户
通过测试用例:20 / 20

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        cnt=Counter(nums)
        ans=[1]*len(nums)
        for i in range(1,len(nums)):
            ans[i]*=ans[i-1]*nums[i-1]
        temp=1
        for i in range(len(nums)-1):
            temp*=nums[len(nums)-1-i]
            ans[len(nums)-2-i]*=temp
        return ans
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值