跳到正文
产品桌面工具TASTECAD图纸查看TASTEFILES文件管理TASTEFTP文件传输TASTESSH远程工作空间TASTEZIP压缩与解压开发工具TASTECODERust 集成开发环境TASTESTUDIO集成开发与测试环境TASTEETL数据整合(ETL)服务器TASTEREMOTE远程桌面服务器TASTEGEO空间信息服务器TASTEMAIL邮件工作空间开始使用下载文档购买全部产品
市场
资讯
技术资讯今日开发资讯开发文档编程语言RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb 前端框架Next.jsReactVue.js · NuxtSvelteKitAngular服务端框架Spring BootDjangoFastAPIASP.NET CoreNestJS · Express应用与桌面框架TauriFlutterReact NativeElectron算法算法基础核心算法进阶算法实用算法
社区项目开发日志提示词AI 工具问题作品展示社区指南
合作技术传授网站构建桌面应用构建发布与支付流水线销售合作伙伴联系我们
服务远程桌面安装包定制
TASTEDEV
产品

桌面工具

TASTECAD复杂图纸,轻松打开TASTEFILES只要需要的文件,最快送达TASTEFTP让文件往来,干净利落TASTESSH你与服务器之间,连接更牢靠TASTEZIP压得更快,解得更稳

开发工具

TASTECODE在一个窗口中完成 Rust 应用的编辑、构建、调试和测试TASTESTUDIO从编辑到远程测试,再到经批准的 AI 修复TASTEETL边看数值,边搬数据

服务器

TASTEREMOTE在自己的服务器上运行的远程桌面TASTEGEO用 Rust 重新构建兼容 GeoServer 的空间信息服务器TASTEMAIL把邮件的主导权拿回自己手中

开始使用

下载所有产品的最新版本文档各产品使用方法购买订阅与永久许可全部产品一览全部产品
全部产品
市场资讯
技术

资讯

今日开发资讯语言、框架、GitHub 与 AI 官方发布开发文档语言、框架与算法指南

编程语言

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

框架

Web 前端框架Next.jsReactVue.js · NuxtSvelteKitAngular
服务端框架Spring BootDjangoFastAPIASP.NET CoreNestJS · Express
应用与桌面框架TauriFlutterReact NativeElectron

算法

算法基础复杂度分析 · 排序 · 查找 · 基础数据结构 · 树与堆核心算法图遍历 · 最短路径与最小生成树 · 动态规划 · 贪心算法 · 分治法 · 回溯法进阶算法字符串算法 · 数学与数论 · 位运算 · 线段树 · 并查集实用算法编程面试解题策略 · LRU 缓存 · 限流 · 一致性哈希
查看全部开发文档
社区
项目发现开发者与作品开发日志决策与试错提示词可复用的指令AI 工具问题Claude、Codex、Gemini 的问题与变通办法作品展示已完成的成果社区指南我们如何公开构建
合作
技术传授用 Rust 和 egui 打造原生应用网站构建10 种语言、账户、文档与下载桌面应用构建Rust 和 egui,不用 WebView发布与支付流水线签名、MSI、deb、rpm、AppImage、哈希销售合作伙伴推荐即得 30%联系我们开发、合作与投资咨询
服务
远程桌面用浏览器连接你的电脑安装包定制只装需要的,设置预先放好
购买
ZH
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
登录
登录
TASTEDEV

从小工具到更好的开发。

support@tastedev.net支持 TASTEDEV
产品产品线购买文档下载市场客户支持
社区项目开发日志提示词AI 工具问题作品展示
政策隐私政策服务条款订阅条款退款政策社区规范
账户登录注册
访客
今天
012345678901234567890123456789012345678901234567890123456789
昨天
012345678901234567890123456789012345678901234567890123456789
累计浏览
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
公司名称
GXSOFT
法定代表人
CHOI YOUNG GU
营业执照号
853-44-00368
地址
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
电话
+82-10-4404-1523
电子邮件
whitecalvin@tastedev.net
个人信息保护负责人
CHOI YOUNG GU

© 2026 TASTEDEV产品信息以已验证的开发源码为准。已发布·持续改进

排序 文档
排序
Sorting ConceptsHow It WorksImplementationComplexityPractice ProblemsReal-World Use
讨论

排序 指南 · 5/6

Practice Problems

本章目前仅提供英文版。

Most sorting problems are not "implement a sort" but "sort first, then the rest is easy". The four problems below practice sort-then-scan, multi-key ordering, custom comparators and reusing the merge step. Try each one before reading the solution.

Problem 1. Merge room bookings

Room bookings are given as (start, end) pairs of integers in no particular order. Merge bookings that overlap or touch, and return the periods when the room is actually in use, ordered by start time. For [(9, 11), (13, 15), (10, 12), (15, 16)] the answer is [[9, 12], [13, 16]].

Approach: after sorting by start time, a booking can only overlap the last merged period. Scan in order; if the current start is at most the last end, extend that end, otherwise open a new period. Sorting costs O(n log n) and the scan O(n).

def merge_bookings(bookings):
    result = []
    for start, end in sorted(bookings):
        if result and start <= result[-1][1]:
            result[-1][1] = max(result[-1][1], end)
        else:
            result.append([start, end])
    return result

print(merge_bookings([(9, 11), (13, 15), (10, 12), (15, 16)]))  # [[9, 12], [13, 16]]

Problem 2. Contest leaderboard

Each contestant has (name, score, seconds). Rank by score descending, then by time ascending, then by name alphabetically.

Approach: one tuple key expresses all three criteria, and negating the numeric score turns it into descending order. If a criterion that cannot be negated (such as a string) must be descending, run several stable sorts from the least to the most significant criterion. Python's reverse=True preserves stability too.

players = [("lee", 90, 300), ("kim", 95, 410), ("park", 90, 280), ("choi", 90, 300)]

ranked = sorted(players, key=lambda p: (-p[1], p[2], p[0]))
print([p[0] for p in ranked])  # ['kim', 'park', 'choi', 'lee']

# The same result with repeated stable sorts, least significant key first
step = sorted(players, key=lambda p: p[0])
step = sorted(step, key=lambda p: p[2])
step = sorted(step, key=lambda p: p[1], reverse=True)
print([p[0] for p in step])    # ['kim', 'park', 'choi', 'lee']

Problem 3. Largest concatenated number

Given non-negative integers, arrange them so that their concatenation is the largest possible number, and return it as a string. For [3, 30, 34, 5, 9] the answer is "9534330". If all values are zero, return "0".

Approach: sorting numerically or lexicographically fails on pairs like 3 and 30. Instead compare two strings a and b by whichever of a + b and b + a is larger. This comparison is transitive, so it is a valid sort order. Strip leading zeros so that becomes .

对本章有疑问?
上一章Complexity下一章Real-World Use
"000"
"0"
from functools import cmp_to_key

def largest_number(nums):
    words = [str(n) for n in nums]

    def compare(a, b):
        if a + b > b + a:
            return -1   # a goes first
        if a + b < b + a:
            return 1
        return 0

    words.sort(key=cmp_to_key(compare))
    return "".join(words).lstrip("0") or "0"

print(largest_number([3, 30, 34, 5, 9]))  # 9534330
print(largest_number([0, 0]))             # 0

Problem 4. Count out-of-order pairs

Count the pairs i < j with a[i] > a[j] (inversions) in an integer array of up to 200,000 elements. For example, [3, 1, 2] has two: (3, 1) and (3, 2).

Approach: checking every pair is O(n²), far too slow. During the merge step of merge sort, when right[j] is taken, the len(left) - i elements still waiting on the left are all larger and originally came earlier, so each forms an inversion. Adding these counts yields the answer in O(n log n) while sorting.

def count_inversions(a):
    def solve(items):
        if len(items) <= 1:
            return items, 0
        mid = len(items) // 2
        left, x = solve(items[:mid])
        right, y = solve(items[mid:])
        merged, i, j, cross = [], 0, 0, 0
        while i < len(left) and j < len(right):
            if left[i] <= right[j]:
                merged.append(left[i])
                i += 1
            else:
                merged.append(right[j])
                j += 1
                cross += len(left) - i
        merged += left[i:] + right[j:]
        return merged, x + y + cross

    return solve(list(a))[1]

print(count_inversions([3, 1, 2]))        # 2
print(count_inversions([5, 4, 3, 2, 1]))  # 10

Equal values are not inversions, so the left element must be taken on ties (<=). Using < would count equal pairs by mistake.

Summary

  • Interval problems usually start with "sort by start, then scan once".
  • Use tuple keys for multiple criteria, and repeated stable sorts when a criterion cannot be negated.
  • Custom comparators work only when they are consistent (transitive).
  • The merge step of merge sort is a tool for counting order relations such as inversions.

0 条评论

热门评论最新优先

登录 · 登录后即可发表评论。