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

Mấy bác cho em hỏi, đó giờ làm LC em đa phần toàn tryhard tự làm , nào mà khó quá bí idea thì em mới xem solution, nên thường thường thì mất 1 ngày - 2 ngày để làm LC nếu bí problem đó, thì có nên không nhỉ?
bí quá thì mở hint với topic xem có phải thứ mình đã biết ko, nếu nhìn thấy topic mà chưa nhìn thấy bh thì nên đọc sol hoặc hiểu topic ấy đã. có mấy bài toán có tên riêng mà ko đọc sol chắc ngồi 1 năm cũng ko thấy hướng đi luôn
RmA5ODa.png
 
Giống bài hôm qua thêm chút tính toán
Python:
class Solution:
    def doubleIt(self, head: Optional[ListNode]) -> Optional[ListNode]:
        rev_head = None
        cur = head
        while cur is not None:
            next_node = cur.next
            cur.next = rev_head
            rev_head = cur
            cur = next_node
        
        cur = rev_head
        str_head = None
        temp_val = 0
        while cur is not None:
            temp_val = cur.val * 2 + temp_val
            cur.val = temp_val % 10
            temp_val = int(temp_val / 10)
            next_node = cur.next
            cur.next = str_head
            str_head = cur
            cur = next_node
        
        if temp_val > 0:
            return ListNode(temp_val, head)
        return head
 
Python:
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def doubleIt(self, head: Optional[ListNode]) -> Optional[ListNode]:
        ph = ListNode(0, head)
        pp, p = ph, head
        while p:
            if p.val >= 5:
                pp.val += 1
            p.val = p.val * 2 % 10
            pp = p
            p = p.next

        return ph if ph.val > 0 else head
 
bí quá thì mở hint với topic xem có phải thứ mình đã biết ko, nếu nhìn thấy topic mà chưa nhìn thấy bh thì nên đọc sol hoặc hiểu topic ấy đã. có mấy bài toán có tên riêng mà ko đọc sol chắc ngồi 1 năm cũng ko thấy hướng đi luôn
RmA5ODa.png
Hóa ra trước giờ mình học sai cách :(
 
e5Ttzq3.png
as37AZS.png
bài hôm nay đâu
1715055568495.png

Java:
class Solution {
    public ListNode doubleIt(ListNode head) {
        int carry = 0;
        Stack<ListNode> stack = new Stack<>();

        ListNode ans = null;
        ListNode pointer = head;

        while (pointer != null) {
            stack.push(pointer);
            pointer = pointer.next;
        }

        while (!stack.isEmpty()) {
            ListNode temp = ans;
            ans = stack.pop();
            int val = (ans.val * 2 + carry) % 10;
            carry = (ans.val * 2 + carry) / 10;
            ans.val = val;
            ans.next = temp;
        }

        return carry == 1 ? new ListNode(1, ans) : ans;
    }
}
 
Python:
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def doubleIt(self, head: Optional[ListNode]) -> Optional[ListNode]:
        current = head
        result = None
        s = 0
        while(current is not None):
            s = ((s*10)+current.val)
            current = current.next
        total = s*2
        if not total:
            return ListNode(0)
        c = result = None
        while total > 0:
            c = ListNode(total % 10)
            if result:
                c.next = result
            result = c
            total//=10
        return result
 
Code:
public class Solution {
    public ListNode DoubleIt(ListNode head) {
        ListNode index = head;
        Stack<ListNode>st = new Stack<ListNode>();
        while(index != null){
            st.Push(index);
            index = index.next;
        }
        int surplus = 0;
        while(st.Count() > 0){
            ListNode temp = st.Pop();
            temp.val = temp.val * 2 + surplus;
            if(temp.val >= 10) surplus = 1;
            else surplus = 0;
            temp.val %= 10;
        }
        if(surplus == 1) return new ListNode(1,head);
        return head;
    }

}
 
JavaScript:
var doubleIt = function (head) {
    let H = new ListNode(0, head);
    const dfs = node => {
        node.val *= 2;
        if (node.next) {
            node.val += dfs(node.next);
        }
        const r = Math.trunc(node.val / 10);
        node.val %= 10;
        return r;
    };
    dfs(H);
    return H.val === 0 ? H.next : H;
};
 
JavaScript:
var doubleIt = function(head) {
    let stack = [];
    let node = head;
    while (node) {
        stack.push(node);
        node = node.next;
    }

    let carry = 0;
    while (stack.length > 0) {
        let lastNode = stack.pop();
        let double = lastNode.val * 2 + carry;
 
        lastNode.val = double % 10;
        carry = Math.floor(double / 10);
    }

    if (carry > 0) {
        let newHead = new ListNode(carry);
        newHead.next = head;
        head = newHead;
    }

    return head;
};
Bảo chatgpt xem code, nó viết lại dùng có 1 vòng while, cơ mà đọc không hiểu :burn_joss_stick:
 
Hix ngồi làm bằng recursion hoài mà không được tức ghê :too_sad:
C#:
public class Solution {
    public ListNode DoubleIt(ListNode head) {
        Stack<int> s = new Stack<int>();
        ListNode current = head;
        while(current != null)
        {
            s.Push(current.val);
            current = current.next;
        }
        
        ListNode newHead = null;
        int temp = 0;
        while(s.Count != 0)
        {
            int currentVal = s.Pop();
            ListNode node = new ListNode((currentVal * 2 + temp) % 10, newHead);
            newHead = node;
            temp = currentVal * 2 / 10;
        }
        if(temp > 0)
        {
            ListNode node = new ListNode(temp, newHead);
            newHead = node;
        }
        return newHead;
    }
}
 
Java:
    public ListNode doubleIt(ListNode head) {
        Stack<Integer> stack = new Stack<>();
        ListNode curr = head;
        ListNode ans = new ListNode(0);
        int carry = 0;
        while(curr != null){
            stack.push(curr.val);
            curr = curr.next;
        }
        while(!stack.isEmpty()){
            int val = (stack.peek()*2 + carry) % 10;
            carry = (stack.pop()*2 + carry) / 10;
            ans.val = val;
            ans = new ListNode(carry, ans);
        }
        return carry == 0 ? ans.next : ans;
    }
 
2 solutions: using hash table and heap

C++:
// Hash table
class Solution {
 public:
     vector<string> findRelativeRanks(vector<int>& score) {
         unordered_map<int, int> mp;
         for(int i = 0; i < score.size(); ++i)
             mp[score[i]] = i;
         sort(score.begin(), score.end(), [](int a, int b){ return a > b;});
         vector<string> ans(score.size());

         for(int i = 0; i < score.size(); ++i){
             int s = score[i];
             cout << s << endl;
             if(i ==0){
                 ans[mp[s]] = "Gold Medal";
             }
             else if(i ==1){
                 ans[mp[s]] = "Silver Medal";
             }
             else if(i ==2){
                 ans[mp[s]] = "Bronze Medal";
             }
             else{
                 ans[mp[s]] = to_string(i + 1);
             }
         }

         return ans;

     }
 };


// Heap
class Solution {
public:
    struct Comp{
        bool operator()(const pair<int, int>& p1, const pair<int, int>& p2){
            return p1.first < p2.first;
        }
    };
    vector<string> findRelativeRanks(vector<int>& score) {
        priority_queue<pair<int, int>, vector<pair<int, int>>,Comp> q;
        for(int i = 0; i < score.size(); ++i)
            q.push({score[i], i});
        
    
        int idx = 1;
        vector<string> ans(score.size());
        while(q.size()){
            int s = q.top().second;
            q.pop();
            if(idx ==1){
                ans[s] = "Gold Medal";
            }
            else if(idx ==2){
                ans[s] = "Silver Medal";
            }
            else if(idx ==3){
                ans[s] = "Bronze Medal";
            }
            else{
                ans[s] = to_string(idx);
            }
            idx++;
        }

        return ans;
        
    }
};
 
JavaScript:
var findRelativeRanks = function(score) {
    const rankMap = {
        "1": "Gold Medal",
        "2": "Silver Medal",
        "3": "Bronze Medal",
    }
    const rank = {};
    const sorted = [...score].sort((a, b) => b - a);
    
    sorted.forEach((s, i) => {
        rank[s] = (i + 1).toString();
    });

    return score.map(s => rank[s] in rankMap ? rankMap[rank[s]] : rank[s]);
};
 
cần gì hash với chả heap

Code:
use std::cmp;

impl Solution {
    pub fn find_relative_ranks(score: Vec<i32>) -> Vec<String> {
        let n = score.len();

        let mut sorted_scores = score.into_iter().enumerate().collect::<Vec<(usize, i32)>>();

        sorted_scores.sort_unstable_by_key(|tuple| cmp::Reverse(tuple.1));

        let mut results = vec![String::default(); n];

        for (rank, (index, score)) in sorted_scores.into_iter().enumerate() {
            match rank {
                0 => results[index] = "Gold Medal".to_string(),
                1 => results[index] = "Silver Medal".to_string(),
                2 => results[index] = "Bronze Medal".to_string(),
                _ => results[index] = (rank + 1).to_string()
            }
        }

        results
    }
}
 
cần gì hash với chả heap

Code:
use std::cmp;

impl Solution {
    pub fn find_relative_ranks(score: Vec<i32>) -> Vec<String> {
        let n = score.len();

        let mut sorted_scores = score.into_iter().enumerate().collect::<Vec<(usize, i32)>>();

        sorted_scores.sort_unstable_by_key(|tuple| cmp::Reverse(tuple.1));

        let mut results = vec![String::default(); n];

        for (rank, (index, score)) in sorted_scores.into_iter().enumerate() {
            match rank {
                0 => results[index] = "Gold Medal".to_string(),
                1 => results[index] = "Silver Medal".to_string(),
                2 => results[index] = "Bronze Medal".to_string(),
                _ => results[index] = (rank + 1).to_string()
            }
        }

        results
    }
}
sort thì complexity có gì vượt trội hơn so với heap đâu nhỉ
 
đơn giản nhất thì vẫn là sort + map.
JavaScript:
function findRelativeRanks(score: number[]): string[] {
    const map = new Map();
    const ans = new Array(score.length);
    score.slice().sort((a, b) => b - a).forEach((val, idx) => {
        map.set(val, idx)
    });

    score.forEach((score, idx) => {
        const item = map.get(score);
        switch (item) {
            case 0:
                ans[idx] = 'Gold Medal';
                break;
            case 1:
                ans[idx] = 'Silver Medal';
                break;
            case 2:
                ans[idx] = 'Bronze Medal'
                break;
            default:
                ans[idx] = `${item + 1}`
        }
    });
    return ans;
};
 
Back
Top