日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

最接近原点的 k 个点_第K个最接近原点的位置

發(fā)布時(shí)間:2023/11/29 编程问答 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 最接近原点的 k 个点_第K个最接近原点的位置 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

最接近原點(diǎn)的 k 個(gè)點(diǎn)

In this article, I will be explaining to you one of the problems that you may find when tackling questions in data structures and algorithm. You will need some basic knowledge of data structures in order to understand the optimized solution to the problem. The code in this article will be based on Python (note that Python is zero-indexed)!

在這篇文章中,我會(huì)向你解釋的問題之一是解決在數(shù)據(jù)結(jié)構(gòu)和算法的問題時(shí),你可能會(huì)發(fā)現(xiàn)。 您將需要一些數(shù)據(jù)結(jié)構(gòu)的基礎(chǔ)知識(shí),以了解針對(duì)該問題的優(yōu)化解決方案。 本文中的代碼將基于Python(請(qǐng)注意,Python的索引為零)!

Difficulty: ???????💛Ingredient: Priority Queue (or Heap)

難度 :???????💛 成分 :優(yōu)先隊(duì)列(或堆)

At one point of your life, you may have come across an algorithm and data structures question that goes like this:

在人生的某個(gè)時(shí)刻,您可能遇到過這樣的算法和數(shù)據(jù)結(jié)構(gòu)問題:

Given a non-ordered (unsorted) array of coordinates and the value of k, find the kth nearest point to the origin. The coordinates given can be be in 1D, 2D or 3D space.

給定一個(gè)無序(未排序)的坐標(biāo)數(shù)組和k的值,找到離原點(diǎn)最近的第k個(gè)點(diǎn)。 給定的坐標(biāo)可以在1D,2D或3D空間中。

For instance, if you have an array of 2D coordinates,

例如,如果您有2D坐標(biāo)數(shù)組,

[ (1,2), (1,0), (9,8), (6,8), (3,3) ]

and also given the value of k,

并給定k的值

k = 3

You are supposed to find the 3rd set of coordinates closest to the origin (0, 0). Let’s approach this step by step.

您應(yīng)該找到最接近原點(diǎn)(0,0)的第三組坐標(biāo) 。 讓我們逐步解決這個(gè)問題。

蠻力 (Brute Force)

One of the possible questions you may ask yourself, instead of kth element, how do I get the 1st element closest to the origin (where k = 1)? To simplify the problem, what if I am given 1D coordinates instead of 2D or 3D?

您可能會(huì)問自己一個(gè)可能的問題,而不是第k個(gè)元素,我如何使第一個(gè)元素最接近原點(diǎn)(其中k = 1)? 為了簡(jiǎn)化問題,如果給我1D坐標(biāo)而不是2D或3D怎么辦?

For instance, given the following array

例如,給定以下數(shù)組

[ 2, 3, 1, 5, 7, 6]

How do I get the closest value to origin 0 (in layman terms, smallest value) for 1D case? There are 2 distinct way of doing so,

對(duì)于一維情況,如何獲得最接近原點(diǎn)0的值(以外行術(shù)語而言,最小值)? 有兩種不同的方法,

  • Sort the array from smallest to largest value, and take the first value, or

    從最小值到最大值對(duì)數(shù)組進(jìn)行排序,然后取第一個(gè)值, 或者

  • Go through every single element in the array, and record the smallest you have seen. This is as good as remembering k number of elements closest to the origin, and replace if necessary.

    遍歷數(shù)組中的每個(gè)元素,并記錄最小的元素。 這與記住k個(gè)最接近原點(diǎn)的元素以及在必要時(shí)進(jìn)行替換一樣好。

  • Both solutions actually works! But there are notable difference in the runtime complexity versus space complexity (see Big O Notation).

    兩種解決方案均有效! 但是,運(yùn)行時(shí)復(fù)雜度與空間復(fù)雜度之間存在顯著差異(請(qǐng)參閱Big O Notation )。

    蠻力—方法1:排序 (Brute Force — Method 1: Sorting)

    In the first method, it is very straightforward. You sort the array,

    在第一種方法中,它非常簡(jiǎn)單。 您對(duì)數(shù)組進(jìn)行排序,

    [ 1, 2, 3, 5, 6, 7]

    And to get the smallest element (k = 1), just get the index 0 element. What about second (k = 2) element? It will be the element at index 1.

    而要獲得最小的元素(k = 1),只需獲取索引為0的元素即可。 第二個(gè)(k = 2)元素呢? 它將是索引1處的元素。

    The code (written as a function) will look something like this:

    該代碼(作為函數(shù)編寫)將如下所示:

    def kthClosestPoint(k: int, array: list):
    if k < 1:
    raise Exception('Invalid k') return sorted(array)[k-1]

    Depending on the sorting algorithm, you will have a typical runtime complexity of O(n log n). Unlike the above code that obtains a new sorted array behind the hood which will give you a space complexity of O(n), if you sort in-place, you will have a space complexity of O(1) instead.

    根據(jù)排序算法,運(yùn)行時(shí)復(fù)雜度通常為O(n log n) 。 與上面的代碼在幕后獲得一個(gè)新的排序數(shù)組不同,這將為您提供O(n)的空間復(fù)雜度,如果就地排序,則將具有O(1)的空間復(fù)雜度。

    But is there any possibility of further improving this method in terms of runtime complexity? Probably not.

    但是是否有可能在運(yùn)行時(shí)復(fù)雜性方面進(jìn)一步改進(jìn)此方法? 可能不是。

    蠻力—方法2:記住k個(gè)元素 (Brute Force — Method 2: Remember k number of elements)

    Now, instead of doing a sort, what if you just keep track of k number of elements closest to the origin?

    現(xiàn)在,不進(jìn)行排序,而只是跟蹤最接近原點(diǎn)的k個(gè)元素怎么辦?

    Back to the same 1D example and given k = 1,

    回到相同的一維示例,給定k = 1,

    [ 2, 3, 1, 5, 7, 6]

    You will pick up every element in the array one by one, and remember the smallest you have seen so far! Similarly for k = 2, you will remember only the 2 smallest you have seen.

    您將一個(gè)接一個(gè)地拾取數(shù)組中的每個(gè)元素,并記住到目前為止所看到的最小元素! 同樣,對(duì)于k = 2,您將只記得所見過的最小的2。

    Now, if you are familiar with priority queue or heap queue (I will be using heapq for Python), then you will realize that you can actually make use of this data structure to obtain k smallest elements.

    現(xiàn)在,如果您熟悉優(yōu)先級(jí)隊(duì)列或堆隊(duì)列(我將在Python中使用heapq ),那么您將意識(shí)到,您實(shí)際上可以利用此數(shù)據(jù)結(jié)構(gòu)來獲取k個(gè)最小的元素。

    import heapqdef kthClosestPoint(k: int, array: list):
    if k < 1:
    raise Exception('Invalid k') # Convert array into heap
    heapq.heapify(array) return heapq.nsmallest(k, array)

    If your array length (a.k.a. heap queue) is n, using this method, you will end up with a worse case runtime complexity of O(n log n), since pushing and popping an element to a heap takes O(log n). The space complexity is O(n) if you duplicate the array or in this example code, O(1) since I am doing it in place.

    如果使用此方法,如果數(shù)組長(zhǎng)度(也就是堆隊(duì)列)為n ,則最終將導(dǎo)致運(yùn)行時(shí)復(fù)雜度為O(n log n) ,因?yàn)閷⒃赝迫牒蛷棾龅蕉阎行枰狾(log n) 。 如果您復(fù)制數(shù)組,則空間復(fù)雜度為O(n) ,或者在此示例代碼中為O(1),因?yàn)槲以谠貓?zhí)行了此操作。

    優(yōu)化 (Optimization)

    You can actually further improve the runtime complexity of this method by limiting the heap queue to k instead of the whole array length n:

    您實(shí)際上可以通過將堆隊(duì)列限制為k而不是整個(gè)數(shù)組長(zhǎng)度n來進(jìn)一步提高此方法的運(yùn)行時(shí)復(fù)雜度:

    import heapqdef kthClosestPoint(k: int, array: list):
    if k < 1:
    raise Exception('Invalid k') k_elements = [] for num in array:
    heappush(k_elements, -num) if len(k_elements) > k:
    heappop(k_elements) return [-num for num in k_elements]

    Note that since heappop only removes the smallest element, one possibility is to invert the polarity of the elements i.e. positive integers will be negative and negative integers will be positive. This will force all large integers to appear small, hence only large integers will be removed from the heap queue.

    請(qǐng)注意,由于heappop僅刪除最小的元素,因此一種可能性是反轉(zhuǎn)元素的極性,即正整數(shù)將為負(fù),負(fù)整數(shù)將為正。 這將強(qiáng)制所有大整數(shù)看起來很小,因此只有大整數(shù)將從堆隊(duì)列中刪除。

    The typical runtime complexity will be O(n log k), since you will be heappush-ing and heappop-ing every single element of the array, while the heap queue length is at most k. This is as bad as having the worse case scenario!

    典型的運(yùn)行時(shí)復(fù)雜度為O(n log k) ,因?yàn)槟鷮?duì)數(shù)組的每個(gè)單個(gè)元素進(jìn)行強(qiáng)制和堆彈出,而堆隊(duì)列長(zhǎng)度最多為k。 這和更糟的情況一樣糟糕!

    進(jìn)一步優(yōu)化 (Further Optimization)

    Can we further improve this for typical case? Instead of placing every element into the heap queue and removing them, can we check before we do it? Yes we can!

    對(duì)于典型案例,我們可以進(jìn)一步改進(jìn)嗎? 除了將每個(gè)元素放入堆隊(duì)列并刪除它們之外,我們還能在執(zhí)行之前檢查一下嗎? 我們可以!

    If we already have a heap queue of size k, we should peek at the “l(fā)argest” element in the heap queue and see if our current element is larger or smaller than that, before we push an element in. If the heap queue is still smaller than length k, we can continue to push elements into it!

    如果我們已經(jīng)有大小為k的堆隊(duì)列,我們應(yīng)該在堆隊(duì)列中的“最大”元素偷看 ,看看我們目前的元素比更大或更小,我們?cè)谕频脑刂?#xff0c;如果堆隊(duì)列仍小于長(zhǎng)度k ,我們可以繼續(xù)將元素推入其中!

    import heapqdef kthClosestPoint(k: int, array: list):
    if k < 1:
    raise Exception('Invalid k') k_elements = [] for num in array: if len(k_elements) < k or k_elements[0] < -num:
    heappush(k_elements, -num) if len(k_elements) > k:
    heappop(k_elements) return [-num for num in k_elements]

    Similarly, if you are dealing with 2D or even 3D data, you can modify this code to accommodate them, using the exact same method.

    同樣,如果要處理2D甚至3D數(shù)據(jù),則可以使用完全相同的方法修改此代碼以容納它們。

    求解2D數(shù)據(jù) (Solving for 2D Data)

    Assuming you have data points in an array looking like this:

    假設(shè)數(shù)組中的數(shù)據(jù)點(diǎn)如下所示:

    [ (1, 2), (3, 5), (6, 7)]

    The distance for each point to origin (0, 0) is simply expressed using Pythagoras theorem in its reduced form:

    每個(gè)點(diǎn)到原點(diǎn)的距離(0,0)可以使用畢達(dá)哥拉斯定理以其簡(jiǎn)化形式簡(jiǎn)單表示:

    distance = x**2 + y**2

    Nothing beats looking code so by modifying the previous 1D code:

    修改前面的一維代碼,沒有什么比看代碼更好的了:

    import heapqdef kthClosestPoint(k: int, array: list):
    if k < 1:
    raise Exception('Invalid k') k_elements = [] for x, y in array: dist = x**2, y**2 if len(k_elements) < k or k_elements[0][0] < -dist:
    heappush(k_elements, (-dist, x, y)) if len(k_elements) > k:
    heappop(k_elements) return [[x, y] for dist, x, y in k_elements]

    If you have any feedback or anything that you wish to share, feel free to drop a comment 👇!

    如果您有任何反饋或希望分享的任何內(nèi)容,請(qǐng)隨時(shí)發(fā)表評(píng)論👇!

    翻譯自: https://medium.com/@kevingxyz/kth-closest-points-to-origin-899c762885e0

    最接近原點(diǎn)的 k 個(gè)點(diǎn)

    總結(jié)

    以上是生活随笔為你收集整理的最接近原点的 k 个点_第K个最接近原点的位置的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。