题目地址:https://leetcode-cn.com/problems/delete-columns-to-make-sorted/submissions/
给你由 n 个小写字母字符串组成的数组 strs,其中每个字符串长度相等。这些字符串可以每个一行,排成一个网格。 例如,strs = ["abc", "bce", "cae"] 可以排列为:abc bce cae 你需要找出并删除 不是按字典序升序排列的 列。 在上面的例子(下标从 0 开始)中,列 0('a', 'b', 'c')和列 2('c', 'e', 'e')都是按升序排列的,而列 1('b', 'c', 'a')不是,所以要删除列 1 。 返回你需要删除的列数。 https://leetcode-cn.com/problems/delete-columns-to-make-sorted/submissions/
示例 1:
输入:strs = ["cba","daf","ghi"]
输出:1
解释:网格示意如下: cba daf ghi 列 0 和列 2 按升序排列,但列 1 不是,所以只需要删除列 1 。
示例 2:
输入:strs = ["a","b"]
输出:0
解释:网格示意如下: a b 只有列 0 这一列,且已经按升序排列,所以不用删除任何列。
示例 3:
输入:strs = ["zyx","wvu","tsr"]
输出:3
解释:网格示意如下: zyx wvu tsr 所有 3 列都是非升序排列的,所以都要删除。
https://leetcode-cn.com/problems/delete-columns-to-make-sorted/submissions/
提示:
n == strs.length
1 <= n <= 100
1 <= strs[i].length <= 1000
strs[i] 由小写英文字母组成
https://leetcode-cn.com/problems/delete-columns-to-make-sorted/submissions/
这一题的爆破法非常简单,用双层循环即可,外层循环下标,内层循环不同的字符串,对比前一个字符必须比后一个字符大即可。
一、爆破法
执行结果如下:
85 / 85 个通过测试用例
状态:通过
执行用时: 10 ms
内存消耗: 38.3 MB
public int minDeletionSize(String[] strs) {
int strsLen = strs.length;
int strLen = strs[0].length();
int ans = 0;
for (int j = 0; j < strLen; j++) {
for (int i = 0; i < strsLen - 1; i++) {
if(strs[i].charAt(j) > strs[i+1].charAt(j)) {
ans++;
break;
}
}
}
return ans;
}
但是,爆破法虽然内存占用很低,时间却高达10ms,只战胜了30%,这可不是我们胜负怪的所图。(虽然和官方答案的答案一毛一样,但是还是太垃圾了)
二、评论区大佬法
执行结果如下:
85 / 85 个通过测试用例
状态:通过
执行用时: 9 ms
内存消耗: 38.4 MB
public int minDeletionSize(String[] A) {
int count = 0;
for (int j = 0; j < A[0].length(); j++) {
char lst = A[0].charAt(j);
for (int i = 0; i < A.length; i++) {
if (lst > A[i].charAt(j)) {
count++;
break;
}
lst = A[i].charAt(j);
}
}
return count;
}
评论区大佬得到了双80%,偏科生的我需要借鉴一下,似乎是因为大佬每次都暂存了值,所以没有做String[i+1]这种操作,比我的效率高了一些
评论区和其他解答方式都和我的爆破法差不多。只是细枝末节我还是要注意,路漫漫其修远兮。