LeetCode: Rank Transform of an Array
Question
Given an array of integers arr, replace each element with its rank.
The rank represents how large the element is. The rank has the following rules:
- Rank is an integer starting from 1.
- The larger the element, the larger the rank. If two elements are equal, their rank must be the same.
- Rank should be as small as possible.
Solution
dict = {}
arr.sort.uniq.each_with_index do |element, i|
dict[element] = i
end
arr.map { |element| dict[element] + 1 }
Comments