给你一个整数数组 nums,请你返回该数组中恰有四个因数的这些整数的各因数之和。
如果数组中不存在满足题意的整数,则返回 0 。
示例:
输入:nums = [21,4,7]
输出:32
解释:
21 有 4 个因数:1, 3, 7, 21
4 有 3 个因数:1, 2, 4
7 有 2 个因数:1, 7
答案仅为 21 的所有因数的和。
提示:
1 <= nums.length <= 10^4
1 <= nums[i] <= 10^5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/four-divisors
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
暴力法,直接统计数组里每个数的因子个数。
时间复杂度:O(Nsqrt(K)), K是max(nums)
空间复杂度:O(1)
class Solution(object):
def sumFourDivisors(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def factor(n):
l = []
for i in range(1, int(n ** 0.5) + 1):
if n % i == 0:
l.append(i)
if n / i != i:
l.append(n / i)
if len(l) > 4:
break
return sum(l) if len(l) == 4 else 0
return sum(map(factor, nums))