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.
Vô contest tập luyện đi, DNA cái gì
osCpCsi.gif


via theNEXTvoz for iPhone
mỗi ngày làm 1-2 bài là vận hết nội công để chống lại sự lười rồi đó fency, cuối tuần còn kêu làm contest nữa :too_sad:
 
Bài hai hôm trước
C-like:
use std::cmp::Ordering;

#[derive(PartialEq)]
struct Nnan(f64);

impl Eq for Nnan {}
impl PartialOrd for Nnan {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.0.partial_cmp(&other.0)
    }
}
impl Ord for Nnan {
    fn cmp(&self, other: &Self) -> Ordering {
        unsafe { self.0.partial_cmp(&other.0).unwrap_unchecked() }
    }
}

impl Solution {
    pub fn max_probability(n: i32, edges: Vec<Vec<i32>>, succ_prob: Vec<f64>, start_node: i32, end_node: i32) -> f64 {
        let succ_prob = succ_prob.as_slice();

        let n = n as usize;
        let adj_graph = &mut vec![Vec::new(); n];
        let adj_graph = adj_graph.as_mut_slice();
        for (index, edge) in edges.iter().enumerate() {
            let (a, b, prob) = (edge[0] as usize, edge[1] as usize, succ_prob[index]);
            adj_graph[a].push((b, prob));
            adj_graph[b].push((a, prob));
        }

        let (start, end) = (start_node as usize, end_node as usize);
        let max_probas = &mut vec![0.0; n];
        let max_probas = max_probas.as_mut_slice();
        max_probas[start] = 1.0;

        let visited = &mut std::collections::BinaryHeap::new();
        visited.push((Nnan(max_probas[start]), start));

        while let Some((Nnan(probab), node)) = visited.pop() {
            if node == end {
                return probab;
            }

            adj_graph[node].iter().for_each(|&(adj_node, adj_prob)| {
                let probab_to_adj = probab * adj_prob;
                if probab_to_adj > max_probas[adj_node] {
                    max_probas[adj_node] = probab_to_adj;
                    visited.push((Nnan(probab_to_adj), adj_node));
                }
            });
        }

        max_probas[end]
    }
}
 
Cái + 10001 hay quá ta
JavaScript:
class UnionFind {
    constructor () {
        this.parent = {};
    }

    find (x) {
        if (x in this.parent === false) this.parent[x] = x;
        if (this.parent[x] !== x) {
            this.parent[x] = this.find(this.parent[x]);
        }
        return this.parent[x];
    }

    union (x, y) {
        const rootX = this.find(x);
        const rootY = this.find(y);
        if (rootX !== rootY) this.parent[rootY] = rootX;
    }

    numOfConnectedComponents () {
        const set = new Set();
        for (const k of Object.keys(this.parent)) {
            set.add(this.find(k));
        }
        return set.size;
    }
}
var removeStones = function(stones) {
    const uf = new UnionFind();
    for (const [x, y] of stones) {
        uf.union(x, y + 10001);
    }
    
    return stones.length - uf.numOfConnectedComponents();
};
 
Python:
class UnionFind:
    def __init__(self, size):
        self.parent = list(range(size))
        self.rank = [1] * size

    def find(self, x):
        if self.parent[x] != x:
            self.parent[x] = self.find(self.parent[x])
        return self.parent[x]

    def union(self, x, y):
        rootX = self.find(x)
        rootY = self.find(y)

        if rootX == rootY:
            return

        if self.rank[rootX] > self.rank[rootY]:
            self.parent[rootY] = rootX
        elif self.rank[rootX] < self.rank[rootY]:
            self.parent[rootX] = rootY
        else:
            self.parent[rootY] = rootX
            self.rank[rootX] += 1

class Solution:
    def removeStones(self, stones: List[List[int]]) -> int:
        uf = UnionFind(len(stones))
        root_x_map = dict()
        root_y_map = dict()

        for i, (x, y) in enumerate(stones):
            if x in root_x_map:
                uf.union(i, root_x_map[x])
            if y in root_y_map:
                uf.union(i, root_y_map[y])
            
            root_x_map[x] = root_y_map[y] = uf.find(i)
        
        groups = sum(1 for i in range(len(stones)) if i == uf.find(i))
        return len(stones) - groups
 
union find chịu ko biết cách biểu diễn
Java:
class Solution {
    public int removeStones(int[][] stones) {
        int n = stones.length;
        Map<Integer, List<Integer>> ROW = new HashMap<>();
        Map<Integer, List<Integer>> COL = new HashMap<>();
        Set<Pair<Integer, Integer>> visited = new HashSet<>();
        for (int[] stone : stones) {
            int i = stone[0];
            int j = stone[1];
            ROW.computeIfAbsent(i, a -> new ArrayList<Integer>());
            ROW.get(i).add(j);
            COL.computeIfAbsent(j, a -> new ArrayList<Integer>());
            COL.get(j).add(i);
        }
        int cnt = 0;// count connected components
        for (int[] stone : stones) {
            int i = stone[0];
            int j = stone[1];
            if (!visited.contains(new Pair(i, j))) {
                cnt++;
                dfs(ROW, COL, visited, i, j);
            }
        }

        return n - cnt;
    }

    public void dfs(
            Map<Integer, List<Integer>> ROW,
            Map<Integer, List<Integer>> COL,
            Set<Pair<Integer, Integer>> visited,
            int i, int j) {
        if(visited.contains(new Pair(i, j))) return;
        visited.add(new Pair(i,j));
        for(int col: ROW.get(i)){
            dfs(ROW,COL, visited, i, col);
        }   
        for(int row:COL.get(j)){
            dfs(ROW,COL,visited, row, j);
        }
    }
}
 
Chắc thất nghiệp cũng lâu rồi, 3h sáng còn vô đòi ăn cơm :sweat:

via theNEXTvoz for iPhone
fency này nick lúc nào cũng thấy sáng 24/24. Chắc là bot do Trung + cài vào rồi :angry:
JCFtpJo.png
Đi ăn cơm cũng bị camera soi, hôm qua trư làm lạc giấy tờ có nguy cơ đền 5k $ nên phải thức chờ bên hãng tàu bên đầu nhập làm việc để cấp lại giấy mới
yBBewst.png
 
JCFtpJo.png
Đi ăn cơm cũng bị camera soi, hôm qua trư làm lạc giấy tờ có nguy cơ đền 5k $ nên phải thức chờ bên hãng tàu bên đầu nhập làm việc để cấp lại giấy mới
yBBewst.png
Fen đỉnh thật, vừa làm Logistic vừa làm Leetcode for fun, đúng là rồng trong loài người mà
RKp7zWn.gif


via theNEXTvoz for iPhone
 
Python:
class UnionFind:
    def __init__(self, size):
        self.parent = list(range(size))
        self.rank = [1] * size

    def find(self, x):
        if self.parent[x] != x:
            self.parent[x] = self.find(self.parent[x])
        return self.parent[x]

    def union(self, x, y):
        rootX = self.find(x)
        rootY = self.find(y)

        if rootX == rootY:
            return

        if self.rank[rootX] > self.rank[rootY]:
            self.parent[rootY] = rootX
        elif self.rank[rootX] < self.rank[rootY]:
            self.parent[rootX] = rootY
        else:
            self.parent[rootY] = rootX
            self.rank[rootX] += 1

class Solution:
    def removeStones(self, stones: List[List[int]]) -> int:
        uf = UnionFind(len(stones))
        root_x_map = dict()
        root_y_map = dict()

        for i, (x, y) in enumerate(stones):
            if x in root_x_map:
                uf.union(i, root_x_map[x])
            if y in root_y_map:
                uf.union(i, root_y_map[y])
            
            root_x_map[x] = root_y_map[y] = uf.find(i)
        
        groups = sum(1 for i in range(len(stones)) if i == uf.find(i))
        return len(stones) - groups
O(n) đây rồi, mượt như Sunsilk :beauty:

via theNEXTvoz for iPhone
 
Chưa xin cấp lại được giấy nữa
yBBewst.png
Đền 5k chắc phải chờ việt kiều @freedom.9 phát card rồi :too_sad:
Java:
class Solution {
    public int removeStones(int[][] stones) {
        UnionFind uf = new UnionFind();
        for (int[] stone: stones) {
            uf.union(stone[0] + 10001, stone[1]);
        }
        return stones.length - uf.getCount();
    }

    class UnionFind {
        Map<Integer, Integer> parents;
        int count;

        public UnionFind() {
            parents = new HashMap<>();
            count = 0;
        }

        public int getCount() {
            return count;
        }

        public int find(int x) {
            if (!parents.containsKey(x)) {
                parents.put(x, x);
                count++;
            }

            if (x != parents.get(x)) {
                parents.put(x, find(parents.get(x)));
            }

            return parents.get(x);
        }

        public void union(int x, int y) {
            int xParent = find(x);
            int yParent = find(y);

            if (xParent == yParent) return;

            parents.put(xParent, yParent);
            count--;
        }
    }
}
 
union find chịu ko biết cách biểu diễn
Java:
class Solution {
    public int removeStones(int[][] stones) {
        int n = stones.length;
        Map<Integer, List<Integer>> ROW = new HashMap<>();
        Map<Integer, List<Integer>> COL = new HashMap<>();
        Set<Pair<Integer, Integer>> visited = new HashSet<>();
        for (int[] stone : stones) {
            int i = stone[0];
            int j = stone[1];
            ROW.computeIfAbsent(i, a -> new ArrayList<Integer>());
            ROW.get(i).add(j);
            COL.computeIfAbsent(j, a -> new ArrayList<Integer>());
            COL.get(j).add(i);
        }
        int cnt = 0;// count connected components
        for (int[] stone : stones) {
            int i = stone[0];
            int j = stone[1];
            if (!visited.contains(new Pair(i, j))) {
                cnt++;
                dfs(ROW, COL, visited, i, j);
            }
        }

        return n - cnt;
    }

    public void dfs(
            Map<Integer, List<Integer>> ROW,
            Map<Integer, List<Integer>> COL,
            Set<Pair<Integer, Integer>> visited,
            int i, int j) {
        if(visited.contains(new Pair(i, j))) return;
        visited.add(new Pair(i,j));
        for(int col: ROW.get(i)){
            dfs(ROW,COL, visited, i, col);
        }  
        for(int row:COL.get(j)){
            dfs(ROW,COL,visited, row, j);
        }
    }
}
uf mới vài tháng trước còn khoe làm được rồi khen dễ thây, chữ nghĩa bay đi đâu rồi
7JO4RkJ.png
 
xjIzSG9.png
thì bữa học UF là 1 đỉnh chỉ cần 1 số để biểu diễn, h 1 đỉnh nó 2 chiều để biểu diễn thì chạy ntn
kElKEVl.gif
Xem x với y của cùng một stone như 2 thực thể riêng biệt r join nó lại, khi một thằng nào đó join được một trong 2 thì gom tiếp, bị một cái là nếu làm vậy thì (x,y) và (y,z) được cho là cùng một khối ( nhưng thật ra k phải) nên cần tịnh tiến trục của x để tách biệt x y bằng cách + max range trong constrain đề cho 10001
 
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.212.784
Quay lại
Lên đầu trang