假设,我们选择了一组删除索引 D
,那么在执行删除操作之后,A
中所剩余的每一列都必须是 非降序 排列的,然后请你返回 D.length
的最小可能值。
示例 1:
输入:["cba", "daf", "ghi"] 输出:1 解释: 当选择 D = {1},删除后 A 的列为:["c","d","g"] 和 ["a","f","i"],均为非降序排列。 若选择 D = {},那么 A 的列 ["b","a","h"] 就不是非降序排列了。
示例 2:
输入:["a", "b"] 输出:0 解释:D = {}
示例 3:
输入:["zyx", "wvu", "tsr"] 输出:3 解释:D = {0, 1, 2}
提示:
1 <= A.length <= 100
1 <= A[i].length <= 1000
第一种思路:
丑陋的暴力解。
class Solution(object):
def minDeletionSize(self, A):
"""
:type A: List[str]
:rtype: int
"""
m, n = len(A), len(A[0])
res = 0
for i in range(0, n):
temp = list()
flag = 1 # 1 代表非降序 0 代表降序
for j in range(0, m):
if not temp:
temp.append(A[j][i])
elif A[j][i] < temp[-1]:
flag = 0
break
else:
temp.append(A[j][i])
if not flag:
res +=1
return res
第二种思路:
从评论区学会的 zip(*A)
对于输入:
["cba", "daf", "ghi"]
["zyx", "wvu", "tsr"]
zip(*A)可以非常快地求出列:
[(u'c', u'd', u'g'), (u'b', u'a', u'h'), (u'a', u'f', u'i')]
[(u'z', u'w', u't'), (u'y', u'v', u's'), (u'x', u'u', u'r')]
class Solution(object):
def minDeletionSize(self, A):
"""
:type A: List[str]
:rtype: int
"""
res = 0
# print zip(*A)
for col in zip(*A):
if sorted(col) != list(col):
res += 1
return res