简体   繁体   English

如何优化我的python代码下面给出的?

[英]How I can optimize the given below my python code?

I have an array and given an array of size N containing positive integers and I want to count number of smaller elements on right side of each array.我有一个数组,给定一个包含正整数的大小为 N 的数组,我想计算每个数组右侧的较小元素的数量。

for example:-例如:-

    Input:
    N = 7
    arr[] = {12, 1, 2, 3, 0, 11, 4}
    Output: 6 1 1 1 0 1 0
    Explanation: There are 6 elements right
    after 12. There are 1 element right after
    1. And so on.
    

And my code for this problem is like as :- 
# python code here
    n=int(input())
    arr=list(map(int,input().split()))

    ans=0
    ANS=[]
    for i in range(n-1):
        for j in range(i+1,n):
            if arr[i]>arr[j]:
                ans+=1
        ANS.append(ans)
        ans=0
    ANS.append(0)
    print(ANS)

but the above my code take O(n^2) time complexity and I want to reduce the this.但是上面我的代码需要 O(n^2) 时间复杂度,我想减少这个。 If anyone have any idea to reduce above python code time complexity please help me.如果有人有任何想法减少上述python代码时间复杂度,请帮助我。 Thank you.谢谢你。

This solution is O(n log(n)) as it is three iterations over the values and one sorting.这个解决方案是 O(n log(n)),因为它是对值的三次迭代和一次排序。

arr = [12, 1, 2, 3, 0, 11, 4]

# Gather original index and values
tups = []
for origin_index, el in enumerate(arr):
    tups.append([origin_index, el])

# sort on value
tups.sort(key=lambda t: t[1])

res = []
for sorted_index, values in enumerate(tups):
    # check the difference between the sorted and original index
    # If there is a positive value we have the n difference smaller 
    # values to the right of this index value. 
    if sorted_index - values[0] > 0:
        res.append([values[0], (sorted_index - values[0])])
    elif sorted_index - values[0] == 0:
        res.append([values[0], (sorted_index - values[0]) + 1])
    else:
        res.append([values[0], 0])

origin_sort_res = [0 for i in range(len(arr))]
for v in res:
    # Return the from the sorted array to the original indexing
    origin_sort_res[v[0]] = v[1]

print(origin_sort_res)

try this(nlog2n)试试这个(nlog2n)

def solution(nums):
    sortns = []
    res = []
    for n in reversed(nums):
        idx = bisect.bisect_left(sortns, n)
        res.append(idx)
        sortns.insert(idx,n)
    return res[::-1]

print(solution([12, 1, 2, 3, 0, 11, 4]))
# [6, 1, 1, 1, 0, 1, 0]

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

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