712519. Replace elements by its rank in the array
Here is the detailed Markdown blog post for the problem "Replace elements by its rank in the array":
Replace elements by its rank in the array
Summary
Given an array of distinct integers, replace each element with its rank (or index) in the array. For example, if the input array is [1, 3, 2, 4], the output should be [1, 2, 3, 4]. The key concept involved is the sorting and indexing of an array.
Detailed Explanation
To solve this problem, we can use a simple algorithm that involves sorting the input array and then replacing each element with its rank. Here's a step-by-step breakdown:
- Sort the input array in ascending order.
- Create an empty output array.
- Iterate through the sorted input array. For each element, append its index (or rank) to the output array.
The time complexity of this algorithm is O(n log n), where n is the size of the input array, due to the sorting step. The space complexity is O(n), since we need to store the output array.
Here's an ASCII art diagram illustrating the process:
Input: [1, 3, 2, 4]
Sort: [1, 2, 3, 4]
Output: [1, 2, 3, 4]
Optimized Solutions
Java
import java.util.Arrays;
public class ReplaceElementsByRank {
public static int[] replaceElements(int[] arr) {
Arrays.sort(arr);
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
return arr;
}
}