Leetcode Problem 1471. The k Strongest Values in an Array

1471. The k Strongest Values in an Array

Leetcode Solutions

Two Pointers Approach

  1. Sort the array arr.
  2. Calculate the median m using the formula m = arr[(len(arr) - 1) // 2].
  3. Initialize two pointers, i at the start of the array and j at the end.
  4. Create an empty list result to store the strongest elements.
  5. While the length of result is less than k: a. Compare abs(arr[i] - m) with abs(arr[j] - m). b. If abs(arr[i] - m) is greater, append arr[i] to result and increment i. c. Else, append arr[j] to result and decrement j.
  6. Return the list result containing the k strongest elements.
UML Thumbnail

Use Max Heap

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...