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

Brute force, hên là làm được, ban đầu đọc đề cứ nghĩ lại phải đi đọc giải tiếp.

Python:
class Solution:
    def maximumImportance(self, n: int, roads: List[List[int]]) -> int:
        edge_count = {}

        for x, y in roads:
            if x not in edge_count:
                edge_count[x] = 0
            edge_count[x] += 1
            if y not in edge_count:
                edge_count[y] = 0
            edge_count[y] += 1
        
        h = []
        for c, count in edge_count.items():
            heapq.heappush(h, (-count, c))

        importance_map = {}
        importance = n
        while len(h):
            city =  heapq.heappop(h)[1]
            importance_map[city] = importance
            importance -=1

        res = 0
        for x, y in roads:
            res += importance_map[x] + importance_map[y]
        return res
 
Code:
impl Solution {
    pub fn maximum_importance(n: i32, roads: Vec<Vec<i32>>) -> i64 {
        let mut vertex_freq = vec![0; n as usize];

        for edge in roads {
            vertex_freq[edge[0] as usize] += 1;
            vertex_freq[edge[1] as usize] += 1;
        }

        vertex_freq.sort_unstable();

        let result =
            vertex_freq.into_iter().enumerate().fold(0, |sum, (i, freq)| {
                sum + (i + 1) * freq
            });

        result as i64
    }
}
 
@billy_don :smile:
C#:
public class Solution {
    public long MaximumImportance(int n, int[][] roads) {
        long[] nodes = new long[n];
        for(int i = 0; i<roads.Length; i++)
        {
            for(int j = 0; j<2; j++)
            {
                nodes[roads[i][j]]++;
            }
        }
        Array.Sort(nodes);
        long result = 0;
        for(int i = n-1; i>=0; i--)
        {
            result += (i+1) * nodes[i];
        }
        return result;
    }
}
 
JavaScript:
var maximumImportance = function(n, roads) {
    const connected = new Array(n).fill(0);
    for (const [a, b] of roads) {
        connected[a]++;
        connected[b]++;
    }

    connected.sort((a, b) => b - a);

    let res = 0;
    let i = n;
    for (const c of connected) {
        res += c * i--;
    }

    return res;
};

@danghieu1709 đâu rồi chưa up nữa :rolleyes:
 
@billy_don :smile:
C#:
public class Solution {
    public long MaximumImportance(int n, int[][] roads) {
        long[] nodes = new long[n];
        for(int i = 0; i<roads.Length; i++)
        {
            for(int j = 0; j<2; j++)
            {
                nodes[roads[i][j]]++;
            }
        }
        Array.Sort(nodes);
        long result = 0;
        for(int i = n-1; i>=0; i--)
        {
            result += (i+1) * nodes[i];
        }
        return result;
    }
}
Với constant <= 2 thì truy thẳng index luôn khỏi for cho dài dòng. Code đỡ dài hơn rồi đó :D
 
In-degree. Nhạt như nước ốc ao bèo 😌
JavaScript:
function maximumImportance(n: number, roads: number[][]): number {
    const arr = new Array(n).fill(0);
    for (const [from, to] of roads) {
        arr[from]++;
        arr[to]++;
    }
    arr.sort((a,b) => a - b);
    let val = 1, res = 0;
    for (const item of arr) {
        res+= val * item;
        val++
    }
    return res;
};
 
In-degree. Nhạt như nước ốc ao bèo 😌
JavaScript:
function maximumImportance(n: number, roads: number[][]): number {
    const arr = new Array(n).fill(0);
    for (const [from, to] of roads) {
        arr[from]++;
        arr[to]++;
    }
    arr.sort((a,b) => a - b);
    let val = 1, res = 0;
    for (const item of arr) {
        res+= val * item;
        val++
    }
    return res;
};
in degree là gì thế thím, thấy tụi nó cũng hay đặt biến như v
 
ví dụ với đỉnh A:
  • Trong đồ thị có hướng thì in-degree là số cạnh đi đến đỉnh A, out-degree là số lượng cạnh đi ra từ đỉnh A
  • Trong đồ thị vô hướng thì in-degree là số cạnh kết nối với đỉnh A
lúc đọc xong đề cũng nghĩ ngay đến đồ thị giống fen :V
C#:
public class Solution {
    public long MaximumImportance(int n, int[][] roads) {
        int rank = n;
        long[] kvp = new long[n];
        for (int i = 0; i < roads.Length; i++)
        {
            kvp[roads[i][0]]++;
            kvp[roads[i][1]]++;
        }
        long sum = 0;
        Array.Sort(kvp, (x, y) => y.CompareTo(x));
        for (int i = 0; i < kvp.Length; i++)
        {
            sum += kvp[i] * rank;
            rank--;

        }
        return sum;
    }
}
 
C-like:
impl Solution {
    pub fn maximum_importance(n: i32, roads: Vec<Vec<i32>>) -> i64 {
        let mut n = n as usize;
        let mut cities = vec![0; n];
        for r in roads {
            cities[r[0] as usize] -= 1;
            cities[r[1] as usize] -= 1;
        }
        cities.sort_unstable();
        let mut m = 0i64;
        for c in cities {
            if c == 0 {
                break;
            }
            m -= c as i64 * n as i64;
            n -= 1;
        }
        return m;
    }
}
 
Java:
class Solution {
    public long maximumImportance(int n, int[][] roads) {
        int[] cityConnections = new int[n];
        long sumOfImportance = 0;
        for(int[] road:roads){
            cityConnections[road[0]]++;
            cityConnections[road[1]]++;
        }
        Arrays.sort(cityConnections);
        for(int i =0 ;i<n;i++){
            sumOfImportance += 1L * cityConnections[i]* (i+1) ;
        }
        return sumOfImportance;
    }
}
 
Python:
class Solution:
    def maximumImportance(self, n: int, roads: List[List[int]]) -> int:
        indegree = [0]*n
        for road in roads:
            indegree[road[0]] += 1
            indegree[road[1]] += 1

        indegree = sorted(indegree, reverse = True)
        maxPoint = n
        ans = 0
        for d in indegree:
            ans += maxPoint*d
            maxPoint -= 1

        return ans
 
Medium ở đây là cái đề lắt léo, cần đọc hiểu, với gài test case thì có.

  • Count.
  • Sort count giảm dần.
  • Tính kết quả.

Swift:
class Solution {
    func maximumImportance(_ n: Int, _ roads: [[Int]]) -> Int {
        var dictCount:[Int: Int] = [:]
        for road in roads {
            dictCount[road[0], default: 0] += 1
            dictCount[road[1], default: 0] += 1
        }
        let arrayCount = dictCount.values.sorted(by:>)
        var result = 0
        for (index, count) in arrayCount.enumerated() {
            result += (n - index) * count
        }
        return result
    }
}
 
Back
Top