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

:cry:
PHP:
class Solution {
    /**
     * @param ListNode $node
     * @return
     */
    function deleteNode($node) {
        $cur = $node;

        // replace node value with the next, stopping at the second-last position
        while ($cur->next->next) {
            $cur->val = $cur->next->val;
            $cur = $cur->next;
        }

        // swap the second-last node with the last and remove it.
        $cur->val = $cur->next->val;
        $cur->next = null;
    }
}
 
bài leetcode ngắn nhất từng làm
Python:
class Solution:
    def deleteNode(self, node):
        node.val = node.next.val
        node.next = node.next.next
 
Bữa onsite với MS có gặp bài này, solution thì dễ mà yêu cầu thì hơi khó hiểu.
Làm mình phải hỏi tới hỏi lui vài lần :sad:

Python:
class Solution:
    def deleteNode(self, node):
        """
        :type node: ListNode
        :rtype: void Do not return anything, modify node in-place instead.
        """
        node.val = node.next.val
        node.next = node.next.next
 
Python:
class Solution:
    def deleteNode(self, node):
        while (node.next is not None and node.next.next is not None):
            node.val = node.next.val
            node = node.next
            
        node.val = node.next.val
        node.next = None
 
Bữa onsite với MS có gặp bài này, solution thì dễ mà yêu cầu thì hơi khó hiểu.
Làm mình phải hỏi tới hỏi lui vài lần :sad:

Python:
class Solution:
    def deleteNode(self, node):
        """
        :type node: ListNode
        :rtype: void Do not return anything, modify node in-place instead.
        """
        node.val = node.next.val
        node.next = node.next.next
thao tác với LL thì mấy bài khác toàn để nguyên value ko dc động chạm. nên bài này cứ nghĩ theo hướng đó thì bí chắc.
 
C#:
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void DeleteNode(ListNode node) {
        node.val = node.next.val;
        node.next = node.next.next;
    }
}

thực sự thì ko hiểu sao bài này medium :))))
 
C#:
public class Solution {
    public int NumRescueBoats(int[] people, int limit) {
        Array.Sort(people);
        int count = 0;
        int left = 0;
        int right = people.Length - 1;
        while(left <= right)
        {
            if (people[left] + people[right] <= limit)
            {
                right--;
                left++;
                count++;
            }
            else
            {
                right--;
                count++;
            }
        }
        return count;
    }
}
bài hôm t7 có thím nào giải cách khác ngoài sort không nhỉ? nhìn cái ra cách sort + 2pointers rồi nma liệu còn cách nào tối ưu hơn ko nhỉ? :D
 
Python:
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
        dummy = ListNode(inf, head)
        current = dummy
        stack = []
        while current!= None:
            while stack and stack[-1].val < current.val:
                stack.pop()
                stack[-1].next = current
            
            stack.append(current)
            current = current.next

        return dummy.next
 
C++:
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNodes(ListNode* head) {
        vector<ListNode *> arr;

        while (head != nullptr) {
            arr.push_back(head);
            head = head->next;
        }

        int n = arr.size();
        ListNode * tmp = arr[n -1];
        ListNode* ans;

        for (int i = n - 2; i >= 0; i--) {
            if (arr[i]->val < tmp->val) {
                if (i - 1 < 0) {
                    return tmp;
                }
                else arr[i - 1]->next = tmp;
            } else if (arr[i]->val >= tmp->val) {
                tmp = arr[i];
            }
        }

        return ans;
    }
};
 
C++:
    ListNode* removeNodes(ListNode* head) {
        deque<ListNode*> d;
        ListNode* curr = head;
        while(curr) {
            while (!d.empty() && curr->val > d.back()->val)
                d.pop_back();

            if (!d.empty())
                d.back()->next = curr;

            d.push_back(curr);
            curr = curr->next;
        }
        d.back()->next = nullptr;
        return d.front();
    }
Thánh này code có 3 dòng, nghĩ ra được cũng sợ :oh:
C++:
    ListNode* removeNodes(ListNode* head) {
        if (!head) return NULL;
        head->next = removeNodes(head->next);
        return head->next && head->val < head->next->val ?  head->next : head;
    }
 
Last edited:
Thánh này code có 3 dòng, nghĩ ra được cũng sợ :oh:
C++:
    ListNode* removeNodes(ListNode* head) {
        if (!head) return NULL;
        head->next = removeNodes(head->next);
        return head->next && head->val < head->next->val ?  head->next : head;
    }
k code đc 3 dòng nhưng t cũng làm cách đệ quy tương tự, :beauty:
Python:
class Solution:
    def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head.next:
            return head
        n = self.removeNodes(head.next)
        head.next = n
        return n if head.val < n.val else head
 
k code đc 3 dòng nhưng t cũng làm cách đệ quy tương tự, :beauty:
Python:
class Solution:
    def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head.next:
            return head
        n = self.removeNodes(head.next)
        head.next = n
        return n if head.val < n.val else head
Kể ra thì cũng gần giống hệt :LOL: Tự nghĩ ra thì não cũng to đấy
 
Python:
class Solution:
    def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
        pointer = head
        pointer.prev = None
        while (pointer.next is not None):
            pointer.next.prev = pointer
            pointer = pointer.next
            
        while (pointer.prev is not None):
            if (pointer.prev.val < pointer.val):
                pointer.prev = pointer.prev.prev
                if pointer.prev is not None:
                    pointer.prev.next = pointer
            else:
                pointer = pointer.prev
                
        return pointer
 
Kể ra thì cũng gần giống hệt :LOL: Tự nghĩ ra thì não cũng to đấy
Thực ra thì khi gặp tree, linker list thì cách đầu tiên nghĩ đến là dùng đệ quy nên nếu làm quen thì sẽ thấy dễ thôi mà, :beauty:. Còn sol này t tự làm chứ k phải cover lại đâu, :ah:
 
Code:
public class Solution {
    public ListNode RemoveNodes(ListNode head) {
        ListNode index = head.next;
        Stack <ListNode> stk = new Stack<ListNode>();
        ListNode newHead = head;
        stk.Push(head);
        while(index != null){
            while(stk.Count() != 0 && stk.Peek().val < index.val) stk.Pop();
            if(stk.Count() == 0) newHead = index;
            else stk.Peek().next = index;
            stk.Push(index);
            index = index.next;   
        }
        return newHead;
    }
}
 
JavaScript:
function removeNodes(head: ListNode | null): ListNode | null {
    if (!head) return null;

    head.next = removeNodes(head.next);

    if (head.next && head.val < head.next.val) {
        return head.next;
    }

    return head;
};
 
Java:
class Solution {
    public ListNode removeNodes(ListNode head) {
        ListNode node =head;
        Stack<ListNode> stack = new Stack();
        while(node!=null){
            while(!stack.isEmpty() && node.val>stack.peek().val){
                stack.pop();
            }
            stack.push(node);
            node = node.next;
        }
        
        ListNode temp = stack.pop();
        while(!stack.isEmpty()){
            stack.peek().next = temp;
            temp = stack.pop();
        }
        head = temp;
        return head;
    }
}
 
Python:
s = []
        while head:
            s.append(head.val)
            head = head.next
        
        newHead = None
        while s:
            node = ListNode(s.pop())
            if newHead is None or newHead.val <= node.val:
                node.next = newHead
                newHead = node
        
        return newHead
 
Back
Top