题目
题目要求不要使用除法!!!
题目要求不要使用除法!!!
题目要求不要使用除法!!!
【代码】”违规操作“,一般思维模式,使用除法进行解题,正确解法,请看下面的方法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