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.
bài hôm nay real medium đấy, ko quá dễ, ko quá khó
QhjvfIv.gif
 
Production issue nên h mới điểm danh :v
Edited: xoá null check thừa
Java:
class Solution {
    public boolean isSubPath(ListNode head, TreeNode root) {
        return tryTravel(root, head);
    }

    boolean tryTravel(TreeNode tree, ListNode list) {
        if (tree == null)
            return false;

        if (travel(tree, list))
            return true;
       
        return tryTravel(tree.left, list) || tryTravel(tree.right, list);
    }

    boolean travel(TreeNode tree, ListNode list) {
        if (list == null)
            return true;

        if (tree == null)
            return false;

        if (tree.val != list.val)
            return false;

        return travel(tree.left, list.next) || travel(tree.right, list.next);
    }
}
 
1725727881782.png


các thím cho em hỏi sao code bên phải khi chạy mấy testcase lớn lại bị runtime error ta? cả 2 đều O(m+n) mà nhỉ (m = len queries, n = len array).

em test ở local thì testcase runtime error ở local em chạy okela ra đúng output. submit lên hackerrank thì failed

đề bài đây ạ: array manipulation

1725728000202.png
 
Xem tệp đính kèm 2671530

các thím cho em hỏi sao code bên phải khi chạy mấy testcase lớn lại bị runtime error ta? cả 2 đều O(m+n) mà nhỉ (m = len queries, n = len array).

em test ở local thì testcase runtime error ở local em chạy okela ra đúng output. submit lên hackerrank thì failed

đề bài đây ạ: array manipulation

Xem tệp đính kèm 2671536
Hackerank nhìn nó cứ cùi cùi, mình cũng ko hiểu tại sao fence tính sai. Xài prefix sum đúng rồi mà, chắc do hackerrank nó limit cái gì đó ở run time.
1 điểm là cách 1 max_value initial value phải là -inf nó mới đúng logic so với cách 2.
Fence có thể viết
Mã:
a,b,k = queries
để cho gọn.
Mã:
Đoạn if total_sum > max_value: max_value = total_sum thì chỉ cần dùng hàm max_value = max(max_value, total_sum)
 
Làm tí khởi động tí lấy rank của vozliz @Cố Trường Ca
Python:
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]:
        count = 0
        current = head
        while current != None:
            count += 1
            current = current.next

        size, mod = divmod(count, k)
        ans = []*k

        for _ in range(k):
            groupSize = size + 1 if mod > 0 else size
            if groupSize == 0:
                ans.append(None)
                continue

            mod -=1
            p1 = head
            ans.append(head)
            groupSize -= 1
            while groupSize:
                p1 = p1.next
                groupSize -=1

            newHead = p1.next
            p1.next = None
            head = newHead

        return ans
 
Java:
class Solution {
    public ListNode[] splitListToParts(ListNode head, int k) {
        ListNode[] arr = new ListNode[k];
        ListNode[] cur = new ListNode[k];

        int count = 0;

        ListNode h = head;
        while(h != null) {
            count++;
            h = h.next;
        }

        int parts = count / k;
        int remain = count % k;
        int index = 0;

        while(head != null) {
            for (int i = 0; i < parts; i++) {
                if (arr[index] == null) {
                    arr[index] = head;
                    cur[index] = arr[index];
                }
                else {
                    cur[index].next = head;
                    cur[index] = cur[index].next;
                }
                head = head.next;
                cur[index].next = null;
            }

            if (remain > 0) {
                if (arr[index] == null) {
                    arr[index] = head;
                    cur[index] = arr[index];
                }
                else {
                    cur[index].next = head;
                    cur[index] = cur[index].next;
                }
                remain--;
                head = head.next;
                cur[index].next = null;
            }

            index++;
        }

        return arr;
    }
}

Java:
class Solution {
    public ListNode[] splitListToParts(ListNode head, int k) {
        ListNode[] arr = new ListNode[k];
        ListNode[] cur = new ListNode[k];

        int count = 0;

        ListNode h = head;
        while(h != null) {
            count++;
            h = h.next;
        }

        int parts = count / k;
        int remain = count % k;
        int index = 0;
        int i = 0;

        while(head != null) {
            i = 0;
            
            if (remain > 0) {
                i--;
                remain--;
            }

            while(i < parts) {
                if (arr[index] == null) {
                    arr[index] = head;
                    cur[index] = arr[index];
                }
                else {
                    cur[index].next = head;
                    cur[index] = cur[index].next;
                }
                head = head.next;
                cur[index].next = null;
                i++;
            }

            index++;
        }

        return arr;
    }
}
 
C#:
public class Solution
{
    public ListNode[] SplitListToParts(ListNode head, int k)
    {
        ListNode pointer = head;
        int n = 0;
        while (pointer != null)
        {
            n++;
            pointer = pointer.next;
        }

        int partSize = n / k;
        int remainder = n % k;

        ListNode[] result = new ListNode[k];
        pointer = head;
        for (int i = 0; i < k; i++)
        {
            int chunkSize = partSize + (remainder > 0 ? 1 : 0);
            remainder--;
            result[i] = pointer;
            if (result[i] == null)
            {
                continue;
            }
            for (int j = 0; j < chunkSize - 1; j++)
            {
                pointer = pointer.next;
            }
            ListNode last = pointer;
            pointer = pointer.next;
            last.next = null;
        }

        return result;
    }
}
 
Làm tí khởi động tí lấy rank của vozliz @Cố Trường Ca
Python:
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]:
        count = 0
        current = head
        while current != None:
            count += 1
            current = current.next

        size, mod = divmod(count, k)
        ans = []*k

        for _ in range(k):
            groupSize = size + 1 if mod > 0 else size
            if groupSize == 0:
                ans.append(None)
                continue

            mod -=1
            p1 = head
            ans.append(head)
            groupSize -= 1
            while groupSize:
                p1 = p1.next
                groupSize -=1

            newHead = p1.next
            p1.next = None
            head = newHead

        return ans
lại vào trễ nữa rồi :too_sad: thôi tắt máyđi ngủ cho đỡ tuột rating, xuống 1k3 ai coi nữa
xjIzSG9.png
 
Java:
class Solution {
    public ListNode[] splitListToParts(ListNode head, int k) {
        ListNode pnt = head;
        int len = 0;
        while (pnt != null) {
            len++;
            pnt = pnt.next;
        }
        ListNode[] res = new ListNode[k];
        split(res, k,len, k,head);
        return res;
    }

    public void split(ListNode[] res, int k ,int remain, int i, ListNode headOfPart) {
        if(i==0) return;
        int len =(int) Math.ceil((double)remain / i);
        remain -= len;
        ListNode curNode = headOfPart;
        while(len>1){
            curNode= curNode.next;
            len--;
        }
        split(res,k, remain, i-1, curNode==null?null:curNode.next);
        res[k-i] = headOfPart;
        if(curNode !=null){
            curNode.next= null;
        }
    }
}
 
Xem tệp đính kèm 2671530

các thím cho em hỏi sao code bên phải khi chạy mấy testcase lớn lại bị runtime error ta? cả 2 đều O(m+n) mà nhỉ (m = len queries, n = len array).

em test ở local thì testcase runtime error ở local em chạy okela ra đúng output. submit lên hackerrank thì failed

đề bài đây ạ: array manipulation

Xem tệp đính kèm 2671536
fen lày giả hổ ăn thịt heo à
YHs5f6H.png
hôm qua bảo mới học DS, nay thấy chém hard hackerrank r
V092S5K.gif
cách giải nhìn cũng uy tín dân lành nghề đấy chứ mới học chỗ nào
Xv0BtTR.png
lại còn xài cả vim
 
Swift:
class Solution {
    func splitListToParts(_ head: ListNode?, _ k: Int) -> [ListNode?] {
        
        var count = 0
        var node = head
        while node != nil {
            count += 1
            node = node!.next
        }
        
        let avg = count/k
        var mod = count%k
        var result:[ListNode?] = Array(repeating: nil, count: k)

        var idx = 0
        node = head
        var numNodes = 0
        while node != nil {
            if numNodes > 1 {
                numNodes -= 1
                node = node!.next
            } else if numNodes == 1 {
                numNodes -= 1
                let temp = node!.next
                node!.next = nil
                node = temp
            } else {
                result[idx] = node
                numNodes = avg + (mod > 0 ? 1 : 0)
                mod -= 1
                idx += 1
            }
        }

        return result
    }
}
 
Contest khoai lang

Java:
class Solution {
    public String convertDateToBinary(String date) {
        String[] split = date.split("-");
        for(int i = 0; i < split.length; i++) {
            split[i] = Integer.toBinaryString(Integer.parseInt(split[i]));
        }

        return String.join("-", split);
    }
}


Java:
class Solution {
    public long findMaximumScore(List<Integer> nums) {
        long[] dp = new long[nums.size()];
        long max;
        long score;

        for (int i = 1; i < nums.size(); i++) {
            max = 0;
            for (int j = 0; j < i; j++) {
                score = (i - j) * nums.get(j) + dp[j];
                max = score > max ? score : max;
            }
            dp[i] = max;
        }
        return dp[nums.size() - 1];
    }
}
Câu 2 k kịp hiểu đề, câu 4 bỏ đi :v
 
Contest khoai lang

Java:
class Solution {
    public String convertDateToBinary(String date) {
        String[] split = date.split("-");
        for(int i = 0; i < split.length; i++) {
            split[i] = Integer.toBinaryString(Integer.parseInt(split[i]));
        }

        return String.join("-", split);
    }
}


Java:
class Solution {
    public long findMaximumScore(List<Integer> nums) {
        long[] dp = new long[nums.size()];
        long max;
        long score;

        for (int i = 1; i < nums.size(); i++) {
            max = 0;
            for (int j = 0; j < i; j++) {
                score = (i - j) * nums.get(j) + dp[j];
                max = score > max ? score : max;
            }
            dp[i] = max;
        }
        return dp[nums.size() - 1];
    }
}
Câu 2 k kịp hiểu đề, câu 4 bỏ đi :v
Câu 3 dùng dfs + memoi lại, 10^5 thì phải On mới được accept, ko là tle hết, nhưng mà nch là vẫn khoai quá T_T câu 2 biết là dùng BS rồi mà đéo biết implement như nào, khó vãi đái.
 
Câu 3 dùng dfs + memoi lại, 10^5 thì phải On mới được accept, ko là tle hết, nhưng mà nch là vẫn khoai quá T_T câu 2 biết là dùng BS rồi mà đéo biết implement như nào, khó vãi đái.
Có thử làm O(N) thím mà tới 612 / 626 bị wrong answer :( hết time luôn
 
Hackerank nhìn nó cứ cùi cùi, mình cũng ko hiểu tại sao fence tính sai. Xài prefix sum đúng rồi mà, chắc do hackerrank nó limit cái gì đó ở run time.
1 điểm là cách 1 max_value initial value phải là -inf nó mới đúng logic so với cách 2.
Fence có thể viết
Mã:
a,b,k = queries
để cho gọn.
Mã:
Đoạn if total_sum > max_value: max_value = total_sum thì chỉ cần dùng hàm max_value = max(max_value, total_sum)
thank iu frency

fen lày giả hổ ăn thịt heo à
YHs5f6H.png
hôm qua bảo mới học DS, nay thấy chém hard hackerrank r
V092S5K.gif
cách giải nhìn cũng uy tín dân lành nghề đấy chứ mới học chỗ nào
Xv0BtTR.png
lại còn xài cả vim
mấy cái DS này học lâu rồi mà không vững nên ôn lại hết từ đầu. DS mục array của hackerrank có 5 bài á fency rồi mới qua linked list, bài cuối là hard có bít làm đâu =(( , lên mạng cọp pi lời giải rồi code lại á.

nghe lời mấy thím vừa ôn vừa làm luôn daily leetcode. để làm bài daily hôm qua thử =((
 
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.213.752
Quay lại
Lên đầu trang