Monday, December 10, 2018

955. Delete Columns to Make Sorted II

Version #1 Straightforward

[2ND TRY]
It is much more clearer this time. If the column doesn't have any char[row - 1][col]  > char[row][col] for all unsorted rows, then this column can be picked up
If we have unsorted rows, it must satisfy that it has the same prefix to its previous row(or larger -> for the initial case)
Otherwise the row won't be selected

66.70 %
class Solution {
    public int minDeletionSize(String[] A) {
// For given column j, we need char[i-1][j] <= char[i][j] -> to keep this column
// if char[i-1][j] < char[i][j] then this row is sorted
// aba
// aac
// baa
// we don't care the sorted rows
int count = 0;
boolean[] sorted = new boolean[A.length];
int cols = A[0].length();
for (int col = 0; col < cols; col++) {
int row = 0;
for (row = 1; row < A.length; row++) {
if (sorted[row]) {
continue;
}
if (A[row].charAt(col) < A[row  - 1].charAt(col)) {
break;
}
}
if (row != A.length) {
count++;
} else {
for (row = 1; row < A.length; row++) {
if (!sorted[row] && A[row].charAt(col) > A[row - 1].charAt(col)) {
sorted[row] = true;
}
}
}
}
return count;
}
}

[1ST TRY]
class Solution {
    public int minDeletionSize(String[] A) {
        boolean[] sorted = new boolean[A.length];
        sorted[0] = true;
        int count = 0;
        for (int col = 0; col < A[0].length(); col++) {
            int word = 1;
            for (word = 1; word < A.length; word++) {
                if (sorted[word]) {
                    continue;
                }
                if (A[word - 1].charAt(col) > A[word].charAt(col)) {
                    count++;
                    break;
                }
            }
            if (word == A.length) {
                for (word = 1; word < A.length; word++) {
                    if (!sorted[word] && A[word - 1].charAt(col) < A[word].charAt(col)) {
                        sorted[word] = true;
                    }
                }
            }
        }
        return count;
    }
}

["doeeqiy","yabhbqe","twckqte"]
["bbjwefkpb","axmksfchw"]
["doeeqiy","yabhbqe","twckqte"]

No comments:

Post a Comment