简体   繁体   English

在排序数组中找到第 k 个最小分数的算法的时间复杂度

[英]Time complexity of algorithm to find kth smallest fraction in a sorted array

Am I right to say that the time complexity of this alg is O(n^2 + nlogn)?我可以说这个算法的时间复杂度是 O(n^2 + nlogn) 吗? My reasoning is that the nested for loop will have a time complexity of O(n^2) because we iterate through each element in the array provided twice.我的理由是嵌套的 for 循环将具有 O(n^2) 的时间复杂度,因为我们遍历提供的数组中的每个元素两次。 However I'm a little confused as to how the use of sorted() affects the overall complexity.但是,对于 sorted() 的使用如何影响整体复杂性,我有点困惑。 I currently think that since sorted is not nested in any of the for loops, we simply add its complexity of nlogn to the complexity of n^2.我目前认为,由于 sorted 没有嵌套在任何 for 循环中,我们只需将它的 nlogn 复杂度添加到 n^2 的复杂度中。 Is this correct?这个对吗?

def kthSmallestPrimeFraction(arr: List[int], k: int) -> List[int]:
    dictionary = defaultdict(list)
    for i in range(len(arr)):
        for j in range(i + 1, len(arr)):
            dictionary[arr[i] / arr[j]] = [arr[i], arr[j]]
    sorted_results = sorted(dictionary.keys())
    # return dictionary.get(sorted_results[k-1])
    return dictionary[sorted_results[k - 1]]

Yes, your reasoning is correct.是的,你的推理是正确的。

In big-O notation only fastest growing term is considered, while irrelevant ones are omitted.在大 O 表示法中,仅考虑增长最快的项,而忽略不相关的项。 So this algorithm is O(n^2) - ie for really big n (n log n) term is not relevant.所以这个算法是 O(n^2) - 即对于非常大的 n (n log n) 项是不相关的。 https://en.wikipedia.org/wiki/Big_O_notation https://en.wikipedia.org/wiki/Big_O_notation

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

相关问题 在二维数组上查找第 K 个最小元素(或中值)的最快算法? - Fastest algorithm for Kth smallest Element (or median) finding on 2 Dimensional Array? 程序超出时间限制 - 找到第 K 个最小元素 - Time limit excedded for program - find Kth smallest element 使用QuickSelect的第k个最小元素排序矩阵 - kth smallest element sorted matrix using QuickSelect 多重排序 arrays 中的第 K 个最小元素 - Kth Smallest Element in multiple sorted arrays 给定一个随机顺序的数字列表,编写一个算法,该算法在 O(nlog(n)) 中工作以找到列表中第 k 个最小的数字 - Given a list of numbers in random order, write an algorithm that works in O(nlog(n)) to find the kth smallest number in the list 如何在BST中找到第k个最小的节点? (重访) - How to find the kth smallest node in BST? (revisited) 在排序数组的并集中查找第k个最小元素 - Finding the kth-smallest element in union of sorted arrays 排序容器的时间复杂度 - Time complexity for a sorted container 如果输入是排序的数据库还是未排序的,输入大小对算法时间复杂度是否重要? - Does the input size matter for algorithm time complexity if the input is a sorted database versus non-sorted? 如何提高算法的时间复杂度以找到数组中整数的最长连续子序列 - How to improve time complexity of algorithm to find the longest consecutive subsequence of integers in an array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM