假设我们有一个称为nums的数字列表。我们必须找到以数字为单位的每对数字的每个串联的总和。在这里,对(i,j)和对(j,i)被认为是不同的。
因此,如果输入类似于nums = [5,3],则输出将为176,因为我们有以下串联:(nums [0] + nums [0])=(5 concat 5)= 55,( nums [0] + nums [1])=(5 concat 3)= 53(nums [1] + nums [0])=(3 concat 5)= 35,(nums [0] + nums [0]) =(3 concat 3)= 33,则总和为55 + 53 + 35 + 33 = 176
为了解决这个问题,我们将按照以下步骤操作:
memo := a new map nums1 := nums temp := 0 c := sum of all elements in nums1 a := size of nums for i in range 0 to a, do if nums[i] is same as 0, then temp := temp + c otherwise, if nums[i] is present in memo, then temp := temp + memo[nums[i]] otherwise, b := 0 for j in range 0 to a, do b := b + integer of (nums[i] concatenate nums1[j]) memo[nums[i]] := b temp := temp + memo[nums[i]] return temp
让我们看下面的实现以更好地理解:
class Solution:
def solve(self, nums):
memo = {}
nums1 = nums
temp = 0
c = sum(nums1)
a = len(nums)
for i in range(a):
if nums[i] == 0:
temp += c
else:
if nums[i] in memo:
temp += memo[nums[i]]
else:
b = 0
for j in range(a):
b += int(str(nums[i]) + str(nums1[j]))
memo[nums[i]] = b
temp += memo[nums[i]]
return temp
ob = Solution()nums = [5, 3]
print(ob.solve(nums))[5, 3]
输出结果
176