查找列表中所有串联的整数对之和的高效算法

如何解决查找列表中所有串联的整数对之和的高效算法

在我的一次面试实践中,我遇到了这个问题,并且除了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) * nn的总和为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 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-