如何解决查找列表中所有串联的整数对之和的高效算法
在我的一次面试实践中,我遇到了这个问题,并且除了O(N ^ 2)之外,还具有更好的时间复杂性。在某种程度上,您必须访问列表中的每个元素。我考虑过使用哈希表,但是仍然需要执行哈希表并填充它,然后进行计算。基本上,我的解决方案是嵌套的for循环,我也包含了我的代码,并且它通过了4秒以内的时间异常以外的所有内容。
我的代码:
def concatenationsSum(a):
sum = 0
current_index_looking_at = 0
for i in a:
for x in a:
temp = str(i)+str(x)
sum += int(temp)
return sum
问题描述:
Given an array of positive integers a,your task is to calculate the sum
of every possible a[i] ∘ a[j],where a[i] ∘ a[j] is the concatenation
of the string representations of a[i] and a[j] respectively.
Example
For a = [10,2],the output should be concatenationsSum(a) = 1344.
a[0] ∘ a[0] = 10 ∘ 10 = 1010,a[0] ∘ a[1] = 10 ∘ 2 = 102,a[1] ∘ a[0] = 2 ∘ 10 = 210,a[1] ∘ a[1] = 2 ∘ 2 = 22.
So the sum is equal to 1010 + 102 + 210 + 22 = 1344.
For a = [8],the output should be concatenationsSum(a) = 88.
There is only one number in a,and a[0] ∘ a[0] = 8 ∘ 8 = 88,so the answer is 88.
Input/Output
[execution time limit] 4 seconds (py3)
[input] array.integer a
A non-empty array of positive integers.
Guaranteed constraints:
1 ≤ a.length ≤ 10^5,1 ≤ a[i] ≤ 10^6.
[output] integer64
The sum of all a[i] ∘ a[j]s. It's guaranteed that the answer is less than 2^53.
解决方法
两个整数的串联:
m ∘ n
等于:
10**digit_length(n) * m + n
所以每个列表项具有给定整数的串联总和:
(a[0] ∘ n) + (a[1] ∘ n) + …
等于:
(10**digit_length(n) * a[0] + n) + (10**digit_length(n) * a[1] + n) + …
,您可以将所有 n 放在一侧:
(10**digit_length(n) * a[0]) + (10**digit_length(n) * a[1]) + … + n + n + …
,请注意,数组的每个元素都乘以一个仅取决于 n 的值:
10**digit_length(n) * (a[0] + a[1] + …) + n + n + …
再次简化:
10**digit_length(n) * sum(a) + len(a) * n
sum(a)
不变,所有len(a) * n
中n
的总和为len(a) * sum(a)
:
def concatenationsSum(a):
sum_a = sum(a)
return sum(10**digit_length(n) * sum_a for n in a) + len(a) * sum_a
def digit_length(n):
"""
The number of base-10 digits in an integer.
>>> digit_length(256)
3
>>> digit_length(0)
1
"""
return len(str(n))
当所涉及的整数的上限为常数时,它以线性时间运行。您还可以使用math.log10
来提高digit_length
的速度,只要浮点数学对于所涉及的整数大小足够精确(并且,如果不是,则还有比通过字符串更好的方法来实现它) –但可能没有更短或更可理解的方式。
与其在每个数字前面分别加上每个数字,不如在其前面加上一个和。好吧,然后它只显示为尾部一次,而不是N次,因此只需再增加N-1次(或等效地,总和为N-1次)即可。
d1 = [
OrderedDict([('name','John'),('Score1','2'),('Score2','8'),('Score3','3')]),OrderedDict([('name','Jack'),'4'),'1'),'5')]),'Jill'),'5')])
]
d2 = OrderedDict([('Score1','5')])
运行时为O(N)。 Demo at repl.it仅显示1000个值,输出:
def concatenationsSum(a):
sum_ = sum(a)
return sum(int(str(sum_) + str(x)) for x in a) + (len(a) - 1) * sum_
,
不可能分别有效地生成每个数字。但是,您可以做的是尝试计算结果,而不必生成各个值。
数组中的数字最大为10 ^ 6。这意味着每个数字都有1到7位数字。将所有数字归为一组:在一个组中,应该有数量相同的数字。最多有7个小组。您可以在O(n)中执行此操作(接下来的步骤仅取决于组的大小,而不必实际创建7个数字列表)
考虑数组中的整数X。您将把它与数组中的其余数字连接起来。与具有K个数字的整数Y的级联可以看作是:X * 10 ^ K +Y。 您想要计算级联的总和,更容易计算每个数字实际充当Y的次数(恰好是N-1次,其中N是数组的大小),以及它成为X的次数使用特定的K值(只有7个可能的K,请检查每个组中有多少个整数;例如,如果您考虑K = 4,则其数量等于组4的大小)。您可以在O(1)中做到这一点。
最后一步是使用先前的计算来计算结果。这非常简单,对于数组中的每个数字V,您都将其添加到结果V * Y_V,V * 10 * X_V_1,Y * 100 * Y_V_2,...,其中Y_V等于其中V充当Y的串联数,X_V_K等于级联数,其中V充当X,且整数Y为K。已经计算出所有值,需要O(n)时间。
,比较3个函数(我认为它们全部都是O(n ^ 2),但速度略有不同。
1:
def concatenationsSum(a):
sum = 0
for i in a:
for x in a:
temp = str(i)+str(x)
sum += int(temp)
return sum
2:
def sumAllPermutations(a):
import itertools
allPermutations=list(itertools.product(a,repeat=2))
sum=0
for x in allPermutations:
sum+=int(str(x[0])+str(x[1]))
return sum
3:
def withouIterTools(list):
Sum = sum([int(str(a)+str(b)) for a in list for b in list])
return Sum
from datetime import datetime
a = [10,2,33,4,67,123,444,55556,432,56456,1,12,3,4]
start_time = datetime.now()
for i in range(10000):
Sum=concatenationsSum(a)
print(Sum)
time_elapsed = datetime.now() - start_time
print('Time elapsed (hh:mm:ss.ms) {}'.format(time_elapsed))
#---------------------------------------------------------------
start_time = datetime.now()
for i in range(10000):
Sum=sumAllPermutations(a)
print(Sum)
time_elapsed = datetime.now() - start_time
print('Time elapsed (hh:mm:ss.ms) {}'.format(time_elapsed))
#---------------------------------------------------------------
start_time = datetime.now()
for i in range(10000):
Sum=withouIterTools(a)
print(Sum)
time_elapsed = datetime.now() - start_time
print('Time elapsed (hh:mm:ss.ms) {}'.format(time_elapsed))
次
23021341208
Time elapsed (hh:mm:ss.ms) 0:00:04.294685
23021341208
Time elapsed (hh:mm:ss.ms) 0:00:04.723034
23021341208
Time elapsed (hh:mm:ss.ms) 0:00:04.156921
,
我看不到没有遍历列表的方法,但是您可以通过不存储temp
并通过在列表中计算a[i]°a[j]
和a[j]°a[i]
来提高效率。同时。
def concatenationsSum(a):
sum = 0
for i in range(len(a)):
sum += int(str(a[i])+str(a[i])) ##diagonal
for j in range(i):
sum += int(str(a[i])+str(a[j]))+int(str(a[j])+str(a[i])) ##off-diagonal
return sum
这可能会节省一些毫秒。但我很想看看多少。
编辑:@superb_rain提出的基准测试是一个好主意。我在分配的约束范围内生成了一些随机测试用例,而我提出的优化并没有使其更快。
显然,按索引获取列表元素要比临时存储它们花费更多的时间。因此,我进一步优化了。下面的代码使执行300个测试用例的时间减少了35%-42%。
def concatenationsSum(a):
sum = 0
for i in range(len(a)):
x = str(a[i])
sum += int(x+x) ##diagonal
for j in range(i):
y=str(a[j])
sum += int(x+y)+int(y+x) ##off-diagonal
return sum
再次编辑:我发现了一种更快的方法,它只具有复杂度O(2n)而不是O(n ^ 2)并且不使用str()
函数。
- 首先,请注意有多少个数字和多少个数字。
- 在开头加上所有数字之和的len(a)乘以,因为每个数字恰好是len(a)次的连接整数的末尾。
- 然后,使用数字位数信息将10 **位数乘以每个数字,因为在将数字相加时,每个数字必须位于其他数字的前面。
def concatenationsSum(a):
pnum = [10**p for p in range(6,-1,-1)]
pot = dict(zip(pnum,[0]*7))
for e in a:
for p in pnum:
if e>=p:
pot[p]+=1
break
v=pot.items()
total = sum(a)*len(a)
for e in a:
for p,n in v:
total += n*e*p*10
return total
此算法可在10秒钟内(在我的笔记本电脑上)获取测试案例的结果,这些测试案例具有最多10 ^ 5个值的10 ^ 6个列表元素。因此,我认为它仍未达到标准,但有潜力使其更高效。至少,它不再具有O(n ^ 2)复杂性。
,对于 PHP 开发者 https://github.com/sslawand351/codesignal/tree/master/concatenationsSum
<?php
// Optimised Solution
function concatenationsSum(array $a): int {
if (count($a) == 0) {
return 0;
}
$digitLength = [];
for ($i=0; $i < count($a); $i++) {
if ($a[$i] < 0) {
echo 'Array contains negative integer elements';
return 0;
}
$digitLength[strlen($a[$i])] = ($digitLength[strlen($a[$i])] ?? 0) + 1;
}
$sum = 0;
for ($i=0; $i < count($a); $i++) {
foreach ($digitLength as $length => $count) {
$sum += $a[$i] * (pow(10,$length) + 1) * $count;
}
}
return $sum;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。