thảo luận Leetcode mỗi ngày

  • Người tạo chủ đề Người tạo chủ đề _Gia_Cat_Luong_
  • Ngày bắt đầu Ngày bắt đầu
Trạng thái
Không mở để trả lời thêm.
C++:
class Solution {
public:
    vector<vector<char>> rotateTheBox(vector<vector<char>>& box) {
        int m = box.size(), n = box[0].size();
        vector<vector<char>> res(n,vector<char>(m,'.'));
        for (int i = 0; i < m; i++) {
            int cur_empty = n - 1;
            for (int j =  n - 1; j >= 0; j--) {
                if (box[i][j] == '*') {
                    res[j][m-1-i] = '*';
                    cur_empty = j - 1;
                }
                else if (box[i][j] == '#') {
                    res[cur_empty][m-1-i] = '#';
                    cur_empty--;
                }
            }
        }
        return res;
    }
};
 
Java:
class Solution {
    fun rotateTheBox(box: Array<CharArray>): Array<CharArray> {
        val m = box.size
        val n = box.first().size
        val result = Array(n) {
            CharArray(m) { '.' }
        }
        for (i in 0 until m) {
            val col = m - i - 1
            var lastIdx = n - 1
            for (k in n - 1 downTo 0) {
                when (box[i][k]) {
                    '*' -> {
                        result[k][col] = '*'
                        lastIdx = k
                    }

                    '#' -> {
                        if (result[lastIdx][col] != '.') --lastIdx
                        result[lastIdx][col] = '#'
                    }
                }
            }
        }
        return result
    }
}
 
Ban đầu đọc đề tưởng nó sẽ bắt rotate n lần. :whistle:
C#:
public class Solution
{
    public char[][] RotateTheBox(char[][] box)
    {
        int rows = box.Length;
        int cols = box[0].Length;
        
        char[][] result = new char[cols][];
        for (int i = 0; i < cols; i++)
        {
            char[] fill = new char[rows];
            Array.Fill(fill, '.');
            result[i] = fill;
        }

        for (int row = 0; row < rows; row++)
        {
            int desCol = cols;
            for (int col = cols - 1; 0 <= col; col--)
            {
                char obj = box[row][col];
                if (obj == '.')
                {
                    result[col][^(row + 1)] = '.';
                    continue;
                }

                if (obj == '*')
                {
                    desCol = col;
                    result[col][^(row + 1)] = '*';
                    continue;
                }

                result[desCol - 1][^(row + 1)] = '#';
                desCol = desCol - 1;
            }
        }

        return result;
    }
}
 
Java:
class Solution {
    public char[][] rotateTheBox(char[][] box) {
        int m = box.length;
        int n = box[0].length;
        int[][] temp = new int[m][n+1];
        char[][] ans = new char[n][m];
        for(int i =0;i<m;i++){
            int cnt=0;
            for(int j=0;j<n;j++){
                ans[j][m-1-i]='.';
                if(box[i][j]=='#') cnt++;
                if(box[i][j]=='*'){
                    ans[j][m-1-i]='*';
                    temp[i][j] = cnt;
                    cnt=0;
                }
                if(j==n-1 && box[i][j]!='*' ){
                    temp[i][j+1] = cnt;
                }
                
            }
        }
        for(int i =0;i<m;i++){
            for(int j=n;j>=1;j--){
                if(temp[i][j]>0){
                    for(int k = 1;k<=temp[i][j];k++){
                        ans[j-k][m-1-i]='#';
                    }
                    j=j-temp[i][j];
                }
            }
        }
        return ans;
    }
}
 
Java:
class Solution {
    public char[][] rotateTheBox(char[][] box) {
        int m = box.length;
        int n = box[0].length;
        char[][] rotatedBox = new char[n][m];

        for(int i = 0; i < n; i++) {
            for(int j = 0; j < m; j++) {
                rotatedBox[i][j] = box[m - 1 - j][i];
            }
        }


        for(int j = m-1; j >= 0; j--) {
            int lowest = n - 1;
            for(int i = n-1; i >= 0; i--) {
                if(rotatedBox[i][j] == '#') {
                    rotatedBox[i][j] = '.';
                    rotatedBox[lowest][j] = '#';
                    lowest--;
                }

                if(rotatedBox[i][j] == '*') {
                    lowest = i-1;
                }
            }
        }

        return rotatedBox;
    }
}
 
JavaScript:
var rotateTheBox = function (box) {
    for (const r of box) {
        for (let i = 0, k = 0; i <= r.length; i++) {
            if (i === r.length || r[i] === '*') {
                for (let j = i - 1; k > 0; j--, k--) {
                    r[j] = '#';
                }
            } else if (r[i] === '#') {
                k++;
                r[i] = '.';
            }
        }
    }
    box = _.zip(...box.reverse());
    return box;
};
 
JavaScript:
var rotateTheBox = function(box) {
    const m = box.length;
    const n = box[0].length;
    const rotated = Array.from({length: n}, () => Array(m).fill("."));

    for(let i = 0; i < n; i++){
        for(let j = 0; j < m; j++){
            rotated[i][j] = box[m - 1 - j][i]
        }
    }

    for(let i = n - 1; i >= 0; i--){
        for(let j = 0; j < m; j++){
            if(rotated[i][j] === "#"){
                rotated[i][j] = ".";
                let iDown = i + 1;
                while(iDown < n && rotated[iDown][j] === "."){
                    iDown++;
                }
                rotated[iDown - 1][j] = "#";
            }
        }
    }
    
    return rotated;
};
 
C++:
class Solution {
public:
vector<vector<char>> rotateTheBox(vector<vector<char>>& a) {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int row=a.size();
    int col=a[0].size();
    vector<vector<char>> res(col, vector<char>(row, '.'));
    for (int rIndex=0; rIndex<row; rIndex++) {
        int stone=0;
        for (int i=0; i<col; i++) {
            if (a[rIndex][i]=='#') {
                stone++;
                a[rIndex][i]='.';
            }
            else if (a[rIndex][i]=='*') {
                for (int index=i-1; index>=i-stone; index--) {
                    a[rIndex][index]='#';
                }
                stone=0;
            }
            if (i==col-1 and stone>0 and a[rIndex][i]!='*') {
                for (int index=i; index>=i-stone+1; index--) {
                    a[rIndex][index]='#';
                }
                stone=0;
            }
        }
    }
    for (int i=0; i<row; i++) {
        for (int j=0; j<col; j++) {
            res[j][row-i-1]=a[i][j];
        }
    }
    return res;
}
};
 
Swift:
class Solution {
    func rotateTheBox(_ box: [[Character]]) -> [[Character]] {
        var result = Array(repeating:[Character](), count:box[0].count)
        for row in box.reversed() {
            var index = 0
            var stoneCount = 0
            func addStone() {
                if stoneCount > 0 {
                    for _ in 0..<stoneCount {
                        result[index].append("#")
                        index += 1
                    }
                    stoneCount = 0
                }
            }
            for cell in row {
                if cell == "#" {
                    stoneCount += 1
                } else {
                    if cell == "*" {
                        addStone()
                    }
                    result[index].append(cell)
                    index += 1
                }
            }
            addStone()
        }
        return result
    }
}
 
Python:
class Solution:
    def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:
        def process_row(row):
            counts = []
            cnt = 0
            for i, c in enumerate(row):
                if c == ".":
                    cnt += 1
                elif c == "*" :
                    counts.append(cnt)          
                    cnt = 0
            counts.append(cnt)
            res = ["0"] * len(row)
            j = 0
            for i, c in enumerate(row):
                if c == "*":
                    res[i] = "*"
                    j += 1
                    continue
          
                if counts[j]:
                    counts[j] -= 1
                    res[i] = "."
                else:
                    res[i] = "#"
            return res
          
        return zip(*[process_row(row) for row in box][::-1])

Python:
class Solution:
    def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:
        def process_row(row):
            space = 0
            for i in reversed(range(len(row))):
                if row[i] == ".": space += 1
                elif row[i] == "*": space = 0
                else: row[i], row[i + space] = ".", "#"
            return row
        return zip(*[process_row(row) for row in box[::-1]])
 
Sửa lần cuối:
PHP:
class Solution {
    const STONE = '#';
    const STANTIONARY_OBSTACLE = '*';
    const EMPTY = '.';

    /**
     * @param String[][] $box
     * @return String[][]
     */
    function rotateTheBox($box) {
        // re-arrange the stones in the original box
        for ($r=count($box)-1; $r >= 0 ; $r--) {
            $queue = new SplQueue();
            for ($c=count($box[$r])-1; $c >=0 ; $c--) {
                if ($box[$r][$c] == self::EMPTY) {
                    $queue->enqueue($c);
                } elseif ($box[$r][$c] == self::STANTIONARY_OBSTACLE) {
                    $queue = new SplQueue();
                } else {
                    if ($queue->isEmpty()) continue;
                    $index = $queue->dequeue();
                    $box[$r][$c] = self::EMPTY;
                    $queue->enqueue($c);
                    $box[$r][$index] = self::STONE;
                }
            }
        }
       
        // rotate the box.
        $rotatedBox = [];
        for ($c=0; $c<count($box[0]); $c++) {
            for ($r=count($box)-1; $r >= 0 ; $r--) {
                $rotatedBox[$c][$r] = $box[$r][$c];
            }
        }
        return $rotatedBox;
    }
}
 
Sửa lần cuối:
Nếu ko làm bisearch sao pass đc fen, nhưng mà fence có thể xài bisect_right luôn chứ ko cần bisect_left
bọn nó có cách ko dùng binary search mà bác

Python:
class Solution(object):
    def numMatchingSubseq(self, S, words):
        word_dict = defaultdict(list)
        count = 0
  
        for word in words:
            word_dict[word[0]].append(word)     
  
        for char in S:
            words_expecting_char = word_dict.pop(char, [])
            for word in words_expecting_char:
                if len(word) == 1:
                    # Finished subsequence!
                    count += 1
                else:
                    word_dict[word[1]].append(word[1:])
  
        return count

Thường người ta sẽ duyệt các word, nhưng nó lại duyệt s rồi collect đồng thời hết các subsequence của các words trong các lần duyệt s

như vậy cácv ví dụ
Input: s = "abcde", words = ["a","bb","acd","ace"]
duyệt đến a là nó duyệt luôn 'a' của 'a', 'acd, 'ace' rồi nên chữ a đấy ko bị lặp lại,

nếu mình duyệt bruforce loop words trước thì lặp lại chữ 'a' ở mỗi lần s

hình như độ phức tạp sẽ là len(s) + (tổng toàn bộ chữ cái trong words) = 50k + 5k * 50 = 300k

còn của mình sẽ là (tổng toàn bộ chữ cái trong words) * log(len(s)) = 250k * log(50k) to hơn nó
uxby0Nl.gif
 
Sửa lần cuối:
Sao nay quyết tâm cày Leetcode thế sư huynh, khuya vl rồi mà. Mới bị reject interview à :beat_brick:
Python:
class Solution:
    def numberOfPairs(self, nums1: List[int], nums2: List[int], k: int) -> int:
        count1 = defaultdict(int)
        count2 = defaultdict(int)
        n = len(nums1)
        m = len(nums2)
        for i in range(max(n, m)):
            if i < n:
                count1[nums1[i]] +=1

            if i < m:
                count2[nums2[i]] += 1

        ans = 0
        for key, value in count1.items():
            if key % k != 0:
                continue
           
            key//=k
            for i in range(1, int(sqrt(key)) + 1):
                if key%i != 0:
                    continue

                ans += value * count2[i]
                if i != key//i:
                    ans += value * count2[key//i]
        return ans
đúng rùi bác, trái ngành chuyển sinh thành thợ code :go:
 
bọn nó có cách ko dùng binary search mà bác

Python:
class Solution(object):
    def numMatchingSubseq(self, S, words):
        word_dict = defaultdict(list)
        count = 0
  
        for word in words:
            word_dict[word[0]].append(word)     
  
        for char in S:
            words_expecting_char = word_dict.pop(char, [])
            for word in words_expecting_char:
                if len(word) == 1:
                    # Finished subsequence!
                    count += 1
                else:
                    word_dict[word[1]].append(word[1:])
  
        return count

Thường người ta sẽ duyệt các word, nhưng nó lại duyệt s rồi collect đồng thời hết các subsequence của các words trong các lần duyệt s

như vậy cácv ví dụ
Input: s = "abcde", words = ["a","bb","acd","ace"]
duyệt đến a là nó duyệt luôn 'a' của 'a', 'acd, 'ace' rồi nên chữ a đấy ko bị lặp lại,

nếu mình duyệt bruforce loop words trước thì lặp lại chữ 'a' ở mỗi lần s

hình như độ phức tạp sẽ là len(s) + (tổng toàn bộ chữ cái trong words) = 50k + 5k * 50 = 300k

còn của mình sẽ là (tổng toàn bộ chữ cái trong words) * log(len(s)) = 250k * log(50k) to hơn nó
uxby0Nl.gif
Thấy cách này nó quá khó để nghĩ ra mà nó cũng kiểu chỉ fit cho câu hỏi này. Làm bisearch là intuitive nhất
zFNuZTA.gif


via theNEXTvoz for iPhone
 
Python:
class Solution:
    def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:
        m, n = len(box), len(box[0])
        result = [['.'] * m for _ in range(n)]

        for i in range(m):
            lowRow = n - 1
            for j in range(n - 1, -1, -1):
                if box[i][j] == '#':
                    result[lowRow][m - i - 1] = '#'
                    lowRow -= 1
                if box[i][j] == '*':
                    result[j][m - i - 1] = '*'
                    lowRow = j - 1
        return result
 
Sao nay quyết tâm cày Leetcode thế sư huynh, khuya vl rồi mà. Mới bị reject interview à :beat_brick:
Python:
class Solution:
    def numberOfPairs(self, nums1: List[int], nums2: List[int], k: int) -> int:
        count1 = defaultdict(int)
        count2 = defaultdict(int)
        n = len(nums1)
        m = len(nums2)
        for i in range(max(n, m)):
            if i < n:
                count1[nums1[i]] +=1

            if i < m:
                count2[nums2[i]] += 1

        ans = 0
        for key, value in count1.items():
            if key % k != 0:
                continue
          
            key//=k
            for i in range(1, int(sqrt(key)) + 1):
                if key%i != 0:
                    continue

                ans += value * count2[i]
                if i != key//i:
                    ans += value * count2[key//i]
        return ans
câu này ảo thế nhỉ, thay vì đếm theo len thì đếm theo value ko tràn
JkpvuKo.png
 
Ảo gì, skill cả :shame:


via theNEXTvoz for iPhone
câu này nghĩ cả ngày hôm qua chưa ra vì tính cặp thì nó sẽ O(N^2) không thể chơi loop 2 vòng nums1 và nums2 được.
Nãy vừa bình tĩnh thử thêm cách tính divisors (hàm tính divisor bảo chatGPT gen hộ) hoá ra chạy được

quan trọng là ko biết cái thuật toán tính số lượng divisors là (SQRT(N)), làm độ phức tạp chỉ còn NSQRT(N)


Python:
class Solution:
    def numberOfPairs(self, nums1: List[int], nums2: List[int], k: int) -> int:
        nums1 = [num//k for num in nums1 if num % k == 0]
        c1 = Counter(nums1)
        c2 = Counter(nums2)
        res = 0
      
        def find_divisors(n):
            divisors = []
            for i in range(1, int(n**0.5) + 1):
                if n % i == 0:
                    divisors.append(i)
                    if i != n // i:
                        divisors.append(n // i)
            return divisors

        for num1 in c1:
            for d in find_divisors(num1):
                res += c1[num1] * c2[d]
          
        return res
 
Sao nay quyết tâm cày Leetcode thế sư huynh, khuya vl rồi mà. Mới bị reject interview à :beat_brick:
Python:
class Solution:
    def numberOfPairs(self, nums1: List[int], nums2: List[int], k: int) -> int:
        count1 = defaultdict(int)
        count2 = defaultdict(int)
        n = len(nums1)
        m = len(nums2)
        for i in range(max(n, m)):
            if i < n:
                count1[nums1[i]] +=1

            if i < m:
                count2[nums2[i]] += 1

        ans = 0
        for key, value in count1.items():
            if key % k != 0:
                continue
           
            key//=k
            for i in range(1, int(sqrt(key)) + 1):
                if key%i != 0:
                    continue

                ans += value * count2[i]
                if i != key//i:
                    ans += value * count2[key//i]
        return ans

bọn nó có cách nhanh hơn tính divisor mới ác :waaaht:
 
Trạng thái
Không mở để trả lời thêm.

Thống kê chủ đề

Ngày tạo
_Gia_Cat_Luong_,
Người trả lời cuối
Vipluckystar,
Trả lời
17.755
Lượt xem
1.214.659
Quay lại
Lên đầu trang