纯个人理解,可能有错,欢迎指正

class Solution:
    def crackPassword(self, password: List[int]) -> str:
        def quick_sort(l , r):
            if l >= r: return
            i, j = l, r
            while i < j:
                while strs[j] + strs[l] >= strs[l] + strs[j] and i < j: j -= 1
                while strs[i] + strs[l] <= strs[l] + strs[i] and i < j: i += 1
                strs[i], strs[j] = strs[j], strs[i]
            strs[i], strs[l] = strs[l], strs[i]
            quick_sort(l, i - 1)
            quick_sort(i + 1, r)
        
        strs = [str(num) for num in password]
        quick_sort(0, len(strs) - 1)
        return ''.join(strs)

作者Krahets
链接https://leetcode.cn/problems/ba-shu-zu-pai-cheng-zui-xiao-de-shu-lcof/description/
来源力扣LeetCode著作权归作者所有商业转载请联系作者获得授权非商业转载请注明出处

最难理解的应该是那几个循环

举个例子【3,4,2】

while i < j: while strs[j] + strs[l] >= strs[l] + strs[j] and i < j: j -= 1#找到 第一个比基准元素 strs[l] 更“小”的元素,这里是23<32 while strs[i] + strs[l] <= strs[l] + strs[i] and i < j: i += 1#找到 第一个比基准元素 strs[l] 更“大”的元素,这里是43>34 strs[i], strs[j] = strs[j], strs[i]#交换后变成【3,2,4】 strs[i], strs[l] = strs[l], strs[i]#此时变成【2,3,4】

我看到原评论里面有一个问题

img

底下有大佬回答还是看的有点迷惑

img

过了一遍测试用例突然懂了 while strs[j] + strs[l] >= strs[l] + strs[j] and i < j: j -= 1 while strs[i] + strs[l] <= strs[l] + strs[i] and i < j: i += 1

测试用例:password =[15,8,7]

你瞧

【15,8,7】

l i,j

从左往右,此时就会出现15和8调换出错。也就是说,i先移动会导致,它先找到一个比基准值“大”的值,就会挡住 j 的步伐,导致找不到比基准值更”小“/等于的元素,从而导致后续的【8,15,7】


如果,先从右往左遍历,J就能先找到一个比基准值L小的值,再不济找不到也只是和开头的L碰头,自身互换而已