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ơm thêm contest 14 July: https://leetcode.com/problems/minimum-cost-for-cutting-cake-i/description/

nhiều lúc không nghĩ là nó chạy được, cứ nghĩ DP ốm người ko ra

Python:
class Solution:
    def minimumCost(self, m: int, n: int, horizontalCut: List[int], verticalCut: List[int]) -> int:
        A, B, res = sorted(horizontalCut), sorted(verticalCut), 0

        while A or B:
            if not A:
                res += (m - len(A)) * B.pop()
            elif not B:
                res += (n - len(B)) * A.pop()
            elif A[-1] > B[-1]:
                res += (n - len(B)) * A.pop()
            else:
                res += (m - len(A)) * B.pop()
   
        return res

vãi Q4, 7 điểm y hệt Q3 :big_smile:
Bài này e nhìn vô là ra dp ngay mà hoá ra éo phải optimal solution :ah:
Python:
class Solution:
    def minimumCost(self, m: int, n: int, horizontalCut: List[int], verticalCut: List[int]) -> int:
        
        @lru_cache(None)
        def dp(x0, y0, x1, y1):
            if x1 - x0 == 1 and y1 - y0 == 1:
                return 0
            
            res = 10**9
            for x in range(x0, x1-1):
                res = min(res, dp(x0, y0, x+1, y1) + dp(x+1, y0, x1, y1) + horizontalCut[x])
            
            for y in range(y0, y1-1):
                res = min(res, dp(x0, y0, x1, y+1) + dp(x0, y+1, x1, y1) + verticalCut[y])
            
            return res
        
        return dp(0, 0, m, n)
 
C++:
class Solution {
public:
    int findChampion(int n, vector<vector<int>>& edges) {
        unordered_set<int> cnt;
        for (int i = 0; i < n; i++) {
            cnt.insert(i);
        }
        for (auto& edge : edges) {
            if (cnt.find(edge[1]) != cnt.end()) {
                cnt.erase(edge[1]);
            }
        }
        if (cnt.size() == 0 || cnt.size() >= 2) return -1;
        return *cnt.begin();
    }
};
 
PHP:
class Solution {

    /**
     * @param Integer $n
     * @param Integer[][] $edges
     * @return Integer
     */
    function findChampion($n, $edges) {
        if ($n == 1 && count($edges) == 0) return 0;

        $winners = [];
        $losers = [];

        foreach ($edges as $e) {
            $w = $e[0];
            $l = $e[1];

            $winners[$w] = $w;
            $losers[$l] = $l;

            if (isset($winners[$l])) {
                $losers[$l] = $l;
                unset($winners[$l]);
            }

            if (isset($losers[$w])) {
                unset($winners[$w]);
            }
        }

        if (count($winners) + count($losers) != $n) return -1;
        
        return count($winners) > 1 ? -1 : end($winners);
    }
}
 
Python:
class Solution:
    def findChampion(self, n: int, edges: List[List[int]]) -> int:
        indegree = [0]*n
        count = n
        for f, t in edges:
            indegree[t] += 1
            if indegree[t] == 1:
                count -= 1

        if count != 1:
            return -1

        for i in range(n):
            if indegree[i] == 0:
                return i
 
Swift:
class Solution2924 {
    func findChampion(_ n: Int, _ edges: [[Int]]) -> Int {
        if edges.isEmpty && n <= 1 {
          return 0
        }
        var counter: [Int: Int] = [:]
        for i in 0..<n {
          counter[i, default: 0] += 0
        }
        for edge in edges {
          counter[edge[1], default: 0] += 1
        }

        let f = counter.filter { entry in entry.value == 0 }
        if f.count > 1 {
          return -1
        } else {
          return f.first?.key ?? -1
        }
    }
}
 
Java:
class Solution {
    public int findChampion(int n, int[][] edges) {
        Set<Integer> champ = new HashSet();
        for(int i =0 ; i < n ; i++){
            champ.add(i);
        }
        for(int[] edge:edges){
            int a = edge[0];
            int b = edge[1];
            if(champ.contains(b)){
                champ.remove(b);
            }
        }
        if(champ.size()>1 || champ.size()==0) return-1;
        int ans =-1;
        for(int num:champ){
            ans=num;
        }
        return ans;

    }
}
 
Mã:
class Solution:
    def findChampion(self, n: int, edges: List[List[int]]) -> int:
        mp = {}
        for x , y in edges:
            mp[y] = x
        champion = -1
        cnt = 0
        for i in range(n):
            if i not in mp:
                champion = i
                cnt += 1
        return champion if cnt == 1 else -1
 
JavaScript:
var findChampion = function(n, edges) {
    const isWeaker = Array(n).fill(false);
    for (const [u, v] of edges) {
        isWeaker[v] = true;
    }
    const u = isWeaker.indexOf(false), v = isWeaker.lastIndexOf(false);
    return u === v ? u : -1;
};
 
Sorry ae e newbie, cho e hỏi về leetcode bài hôm nay, theo testcase này theo e hiểu là 1 yếu hơn 0, và 1 yếu hơn 2 -> 1 yếu nhất, 0 và 2 không so sánh được, sao đáp án lại ra "1" nhỉ.
Screenshot 2024-11-26 at 10.29.12.png
 
Sorry ae e newbie, cho e hỏi về leetcode bài hôm nay, theo testcase này theo e hiểu là 1 yếu hơn 0, và 1 yếu hơn 2 -> 1 yếu nhất, 0 và 2 không so sánh được, sao đáp án lại ra "1" nhỉ.
champ phải có yếu tố unique nữa, 1 rừng không thể có 2 hổ
TOxIXtu.gif
output là kqua của fen ko phải đáp án của câu hỏi, expect mới là cái nên return ra
 
Sorry ae e newbie, cho e hỏi về leetcode bài hôm nay, theo testcase này theo e hiểu là 1 yếu hơn 0, và 1 yếu hơn 2 -> 1 yếu nhất, 0 và 2 không so sánh được, sao đáp án lại ra "1" nhỉ.
Em khuyên bác new bie thì đừng vào làm daily ngay làm gì cho nó nhọc ra, tập trung vào cái list 150 trước để có cái base cơ bản đã rồi làm sau, nhảy vào daily nay bài này, mai bài khác, kiến thức cơ bản thủng ko có thì sao mà học cho hiệu quả được.
 
champ phải có yếu tố unique nữa, 1 rừng không thể có 2 hổ
TOxIXtu.gif
output là kqua của fen ko phải đáp án của câu hỏi, expect mới là cái nên return ra
Đồng ý a, ok thế e sẽ làm lại theo output nếu đỉnh của Graph đó là unique.
Mấy cái này thì chỉ phải đọc kỹ đề thôi.
Vâng, thanks a.
Em khuyên bác new bie thì đừng vào làm daily ngay làm gì cho nó nhọc ra, tập trung vào cái list 150 trước để có cái base cơ bản đã rồi làm sau, nhảy vào daily nay bài này, mai bài khác, kiến thức cơ bản thủng ko có thì sao mà học cho hiệu quả được.
Vâng, cảm ơn bác hehe.
 
Em khuyên bác new bie thì đừng vào làm daily ngay làm gì cho nó nhọc ra, tập trung vào cái list 150 trước để có cái base cơ bản đã rồi làm sau, nhảy vào daily nay bài này, mai bài khác, kiến thức cơ bản thủng ko có thì sao mà học cho hiệu quả được.
e newbie làm daily đây
MjfezZB.png
chưa từng làm 150
JkpvuKo.png
 
Python:
class Solution:
    def findChampion(self, n: int, edges: List[List[int]]) -> int:
        strongs = set(e for e in range(n))
        for a, b in edges:
            strongs.discard(b)
               
        if len(strongs) == 1:
            return strongs.pop()
       
        return -1
 
Sửa lần cuối:
C#:
public class Solution {
    public int FindChampion(int n, int[][] edges)
    {
        var res = new bool[n];
        Array.Fill(res, true);
        foreach (var pair in edges)
        {
            res[pair[1]] = false;
        }

        if (res.Count(a => a) > 1) return -1;
        return Array.IndexOf(res, true);
    }
}
 
JavaScript:
var findChampion = function(n, edges) {
    const adjList = new Map();
    for(const [from, to] of edges){
        const currentList = adjList.get(from) ?? [];
        currentList.push(to);
        adjList.set(from, currentList);
    }
    const isBeatable = Array(n).fill(false);
    for(let i = 0; i < n; i++){
        if(isBeatable[i]) continue;
        const queue = [i];
        let level = 0;
        while(queue.length > 0){
            const levelSize = queue.length;
            for(let j = 0; j < levelSize; j++){
                const node = queue.shift();
                if(level > 0) isBeatable[node] = true;
                const adjNodes = adjList.get(node);
                if(!adjNodes) continue;
                for(const adjNode of adjNodes){
                    if(isBeatable[adjNode]) continue;
                    queue.push(adjNode);
                }
            }
            level++;
        }
    }
    let firstUnbeatable = isBeatable.indexOf(false);
    let lastUnbeatable = isBeatable.lastIndexOf(false);
    return firstUnbeatable !== lastUnbeatable ? -1 : firstUnbeatable;
};
 
1732593998807.png


Đề bài bảo ko circle, troll quá

Python:
class Solution:
    def findChampion(self, n: int, edges: List[List[int]]) -> int:
        graph = defaultdict(list)
        for u, v in edges:
            graph[u].append(v)

        def bfs(node):
            cnt = 0
            q = deque([node])
            visited = {node}
            
            while q:
                curr = q.popleft()
                cnt += 1

                for nei in graph[curr]:
                    if nei not in visited:
                        q.append(nei)
                        visited.add(nei)

            return cnt == n
        
        champs = [i for i in range(n) if bfs(i)]
        
        return champs[0] if len(champs) == 1 else -1
 
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.406
Quay lại
Lên đầu trang