LeetCode 题解工作台

数组序号转换

给你一个整数数组 arr ,请你将数组中的每个元素替换为它们排序后的序号。 序号代表了一个元素有多大。序号编号的规则如下: 序号从 1 开始编号。 一个元素越大,那么序号越大。如果两个元素相等,那么它们的序号相同。 每个数字的序号都应该尽可能地小。 示例 1: 输入: arr = [40,10,20…

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

我们先复制一个数组 ,然后对其进行排序并去重,得到一个长度为 且严格单调递增的数组。 然后我们遍历原数组 ,对于其中的每个元素 ,我们利用二分查找得到 在 中的位置,那么该位置加一就是 的排名。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 arr ,请你将数组中的每个元素替换为它们排序后的序号。

序号代表了一个元素有多大。序号编号的规则如下:

  • 序号从 1 开始编号。
  • 一个元素越大,那么序号越大。如果两个元素相等,那么它们的序号相同。
  • 每个数字的序号都应该尽可能地小。

 

示例 1:

输入:arr = [40,10,20,30]
输出:[4,1,2,3]
解释:40 是最大的元素。 10 是最小的元素。 20 是第二小的数字。 30 是第三小的数字。

示例 2:

输入:arr = [100,100,100]
输出:[1,1,1]
解释:所有元素有相同的序号。

示例 3:

输入:arr = [37,12,28,9,100,56,80,5,12]
输出:[5,3,4,2,8,6,7,1,3]

 

提示:

  • 0 <= arr.length <= 105
  • -109 <= arr[i] <= 109
lightbulb

解题思路

方法一:离散化

我们先复制一个数组 tt,然后对其进行排序并去重,得到一个长度为 mm 且严格单调递增的数组。

然后我们遍历原数组 arrarr,对于其中的每个元素 xx,我们利用二分查找得到 xxtt 中的位置,那么该位置加一就是 xx 的排名。

时间复杂度 O(n×logn)O(n \times \log n),空间复杂度 O(n)O(n)。其中 nn 是数组 arrarr 的长度。

1
2
3
4
5
class Solution:
    def arrayRankTransform(self, arr: List[int]) -> List[int]:
        t = sorted(set(arr))
        return [bisect_right(t, x) for x in arr]
speed

复杂度分析

指标
时间O(N \cdot \log N)
空间O(N)
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate is familiar with sorting and hash tables.

  • question_mark

    The candidate efficiently implements the solution with minimal complexity.

  • question_mark

    The candidate can handle arrays with duplicate elements correctly.

warning

常见陷阱

外企场景
  • error

    Not handling duplicates properly and giving them different ranks.

  • error

    Misunderstanding the requirement to rank based on sorted order rather than the array index.

  • error

    Not optimizing the solution by using a hash table for quick lookup of ranks.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if the array contains negative numbers?

  • arrow_right_alt

    What if the array has a very large size, like 100,000 elements?

  • arrow_right_alt

    How would you handle ranking based on descending order instead of ascending?

help

常见问题

外企场景

数组序号转换题解:数组·哈希·扫描 | LeetCode #1331 简单