944. Delete Columns to Make Sorted [简单算法]

We are given an array A of N lowercase letter strings, all of the same length.

Now, we may choose any set of deletion indices, and for each string, we delete all the characters in those indices.

For example, if we have an array A = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, then the final array after deletions is["bef", "vyz"], and the remaining columns of A are ["b","v"], ["e","y"], and ["f","z"]. (Formally, the c-th column is [A[0][c], A[1][c], ..., A[A.length-1][c]].)

Suppose we chose a set of deletion indices D such that after deletions, each remaining column in A is in non-decreasing sorted order.

Return the minimum possible value of D.length.

Example 1:

Input: ["cba","daf","ghi"]

Output: 1

Explanation: After choosing D = {1}, each column ["c","d","g"] and ["a","f","i"] are in non-decreasing sorted order. If we chose D = {}, then a column ["b","a","h"] would not be in non-decreasing sorted order.

Example 2:

Input: ["a","b"]

Output: 0

Explanation: D = {}

Example 3:

Input: ["zyx","wvu","tsr"]

Output: 3

Explanation: D = {0, 1, 2}

Note:

1 <= A.length <= 100

1 <= A[i].length <= 1000

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/delete-columns-to-make-sorted

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

该题目就是统计有多少列字符不是`非递减`的.

class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
​
        # 基本方法     
        l = len(A[0])
        count = 0
        for i in range(l):
            last = None
            for item in A:
                if last is not None:
                    if last > item[i]:  # 出现非递增的列, 不满足要求
                        count += 1
                        break
                last = item[i]
        return count
        
​
        # 语法强, 思路简单的方法 (速度慢, 因为中间没有了上面的break)
        return sum((any(column[i] > column[i+1] for i in range(len(column) - 1)) for column in zip(*A)))
        # i**2 for i in 1..10 返回1,4,9..100
        # any 是否至少存在1个True
        # sum 统计True的数量
​
        # 新思想 + 语法
        res = 0
        for i in zip(*A):
            if list(i) != sorted(i):
                res += 1
        return res
        # >>> a = ['abc', 'def', 'ghi']
        # >>> list(zip(*a))
        # [('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]
        # >>> list(zip(a[0],a[1],a[2]))
        # [('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]
        # >>> list(zip(a))
        # [('abc',), ('def',), ('ghi',)]
        # 由此可知, *的作用是传参时, 把列表展开
        # zip把每个参数的第1项打包成一个元组, 第2项打包成一个元组, ...
        # 然后对对打包成的元组排序, 返回新list, 将新list与原元组直接转成的list进行比较
        # 如果相等就+1
​
​
发布了80 篇原创文章 · 获赞 22 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/u010099177/article/details/100183033