简体   繁体   English

如何在 python 中使这段代码更快(算法问题)

[英]How to make this code faster in python (algorithm question)

Today I was browsing for some questions that I saw this: Algorithm - Air Battle今天我正在浏览一些我看到的问题:算法 - 空战

C ++ time limit: 1 second Java time limit: 2 seconds Python time limit: 10 seconds Memory limit: 256 MB C++时间限制:1秒Java时间限制:2秒Python时间限制:10秒内存限制:256 MB

There are a number of fighters in a line, and all of them have different heights from the ground.排成一排的战斗机有很多,而且它们都离地面有不同的高度。 Each fighter can only target its front fighters, provided that their height are less than the height of the fighter that is Under investigation.每架战斗机只能瞄准它的前部战斗机,前提是它们的高度小于正在调查的战斗机的高度。

The number of fighters that a fighter can target is called a strategic number.战斗机可以瞄准的战斗机数量称为战略数量。 For example, if Fighter A can target 3 fighters, we say that the strategic number of Fighter A is 3.例如,如果战斗机 A 可以针对 3 名战斗机,我们说战斗机 A 的战略数量为 3。

Get the total strategic numbers of all the fighters.获取所有战士的总战略数量。

Entraces: In the first line of input, n appears, which indicates the number of fighters. Entraces:输入的第一行出现n,表示战士的数量。 Then in the next line, the height of the n fighters comes in sequence from h_i.然后在下一行中,n 个战士的高度从 h_i 开始。

    0001≤n≤100 000
    0001≤h≤100 000

Output:输出:

In the output, print the sum of the strategic numbers of all the fighters.在输出中,打印所有战斗机的战略数量之和。

Sample input 1:样本输入 1:

5 5

5 4 3 7 6 5 4 3 7 6

Sample output 1 4样本输出 1 4

I wroted this code for it (in python) but the time limit will be passed in huge numbers:我为它编写了这段代码(在python中),但时间限制将大量传递:

n = int(input())
players = list(map(int, input().split()))
c = 0
for index, player in enumerate(players, 1):
    c += len([num for num in players[index:] if num < player])
print(c)

The approach is largely similar to counting inversions in an array.该方法在很大程度上类似于计算数组中的反转

During the merge step, maintain two pointers (one for each half).在合并步骤中,维护两个指针(每半个指针)。 Let the two elements from each being compared be i (from the left half) and j (right half).让每个被比较的两个元素是i (从左半部分)和j (从右半部分)。 If i<j , i will also be smaller than all elements to the right of j .如果i<ji也将小于j右侧的所有元素。 You can accordingly increment i 's count, and move its pointer.您可以相应地增加i的计数,并移动其指针。 This "hint" should be enough for you to implement a solution.这个“提示”应该足以让您实施解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM