Le migliori 150 intervisteFacile

K Punti più vicini all'origine

Guida dettagliata e implementazione Python per il problema "K punti più vicini all'origine".

Dichiarazione del problema

Facile

Dato un array di punti in cui punti[i] = [xi, yi] rappresenta un punto sul piano X-Y e un intero k, restituire i k punti più vicini all'origine (0, 0).

La distanza tra due punti sul piano X-Y è la distanza euclidea (ovvero sqrt((x1 - x2)^2 + (y1 - y2)^2)).

Puoi restituire la risposta in qualsiasi ordine. È garantito che la risposta sia univoca (ad eccezione dell'ordine in cui si trova).

Scrivi una funzione kClosest(points: List[List[int]], k: int) -> List[List[int]].

Vincoli
  • 1 <= k <= len(points) <= 10^4
  • -10^4 <= xi, yi <= 10^4

Esempi

Example 1
Input
points = [[1,3],[-2,2]], k = 1
Output
[[-2,2]]
Explanation

The distance from (1, 3) to the origin is sqrt(10). The distance from (-2, 2) to the origin is sqrt(8). Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.

Example 2
Input
points = [[3,3],[5,-1],[-2,4]], k = 2
Output
[[3,3],[-2,4]]
Explanation

The closest two points are (3, 3) and (-2, 4). (Order of elements in the output does not matter).

Need a Hint?
Prendi in considerazione l'utilizzo di strutture dati specifiche per heap/coda di priorità come set o heap.
Edge Cases to Watch
  • Strutture di input vuote
  • Ingressi a elemento singolo
  • Grandi limiti numerici

Pronto a risolvere?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Apri nell'editor
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

Risorse Python consigliate

Espandi le tue conoscenze con tutorial interattivi, foglietti illustrativi e confronti di codici correlati.