Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Top K Elements , Java Patterns, Integer Overflow in Max Heap Comparator for K Closest Points to Origin, problem on LeetCode 973. #21

Open
@Arnab7456

Description

@Arnab7456

The original comparator:
PriorityQueue<int[]> maxHeap = new PriorityQueue<>((a, b) -> getDistance(b) - getDistance(a));
Here,
getDistance(b) - getDistance(a) could result in overflow if the distances are large, causing incorrect behavior or errors.
Proposed Solution:
To avoid the risk of overflow, it is recommended that the comparator be changed to

Integer.compare():


PriorityQueue<int[]> maxHeap = new PriorityQueue<>((a, b) -> Integer.compare(getDistance(b), getDistance(a)));

This change ensures that the distances are compared safely without the risk of overflow.

Steps to Reproduce:
Use the provided solution for the "K Closest Points to Origin" problem on LeetCode 973.
Test the solution with a large number of points (e.g., with coordinates in the range of [-10^4, 10^4]).
Observe that the original comparator could result in integer overflow due to the subtraction of large numbers.

Expected Behavior:
The solution should compare the distances correctly without any risk of overflow. The use of Integer.compare() ensures safe comparisons between distances.

Actual Behavior:
The current implementation can potentially cause overflow when the distances are large.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions


      [8]ページ先頭

      ©2009-2025 Movatter.jp