LeetCode 955. Delete Columns to Make Sorted II
考点 | 难度 |
---|---|
Greedy | Easy |
题目
You are given an array of n strings strs, all of the same length.
We may choose any deletion indices, and we delete all the characters in those indices for each string.
For example, if we have strs = [“abcdef”,“uvwxyz”] and deletion indices {0, 2, 3}, then the final array after deletions is [“bef”, “vyz”].
Suppose we chose a set of deletion indices answer such that after deletions, the final array has its elements in lexicographic order (i.e., strs[0] <= strs[1] <= strs[2] <= … <= strs[n - 1]). Return the minimum possible value of answer.length.
思路
用counter记录每个数的个数。sort array,从最小的数x开始,如果是正数找x*2,其他情况找x/2,如果没有返回false。
答案
class Solution(object):
def canReorderDoubled(self, arr):
cnt = Counter(arr)
arr.sort()
for x in arr:
if cnt[x] == 0: continue
if x < 0 and x % 2 != 0: return False
y = x * 2 if x > 0 else x // 2
if cnt[y] == 0: return False
cnt[x] -= 1
cnt[y] -= 1
return True