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.
C++:
class Solution {

struct LeavingNode {
    int i;
    int arrival;
    int leaving;
    int order;

    LeavingNode(int _i, int _arrival, int _leaving, int _order) {
        i = _i;
        arrival = _arrival;
        leaving = _leaving;
        order = _order;
    }
    
};

class Compare
{
public:
    bool operator() (LeavingNode x, LeavingNode y){
        return x.leaving > y.leaving;
    }
};

public:
    int smallestChair(vector<vector<int>>& times, int targetFriend) {
        priority_queue<LeavingNode, std::vector<LeavingNode>, Compare> pq_leave;
        priority_queue<int, vector<int>, greater<int>> pq_order;

        int n = times.size();
        int ids[n];
        for (int i = 0; i < n; ++i) ids[i] = i;

        sort(ids, ids + n, [&times](int i, int j) { return times[i][0] < times[j][0]; });

        // for (int i : ids) cout << i << "\n";
        for (int i = 0; i < n; ++i){
            pq_order.push(i);
        }

        for (int i : ids) {
            // LeavingNode cur(i, times[i][0], times[i][1], )
            int cur_arrival = times[i][0];
            while (!pq_leave.empty()){
                auto top = pq_leave.top();
                // cout << top.i << " [" << top.arrival << "," << top.leaving << "] " << top.order << " x\n";
                if (top.leaving > cur_arrival) break;
                pq_order.push(top.order);
                pq_leave.pop();
            }
            int order = pq_order.top();
            pq_order.pop();
            if (i == targetFriend) return order;
            LeavingNode cur(i, cur_arrival, times[i][1], order);
            pq_leave.push(cur);
            // cout << i << " [" << cur_arrival << "," << times[i][1] << "] " << order << "\n";
        }

        return -1;
    }
};
 
Python:
class Solution:
    def smallestChair(self, times: List[List[int]], targetFriend: int) -> int:       
        startHeap = []
        endHeap = []
        seatHeap = []
        for i in range(len(times)):
            heappush(startHeap, (times[i][0], i))
            heappush(seatHeap, i)

        for i in range(len(startHeap)):
            arrivalAt, arrivalFriend = heappop(startHeap)

            while endHeap and arrivalAt >= endHeap[0][0]:
                endAt, seat = heappop(endHeap)
                heappush(seatHeap, seat)

            newSeat = heappop(seatHeap)
            heappush(endHeap, (times[arrivalFriend][1], newSeat))
            if arrivalFriend == targetFriend:
                return newSeat

        return 0
 
Java:
class Solution {
    public int smallestChair(int[][] times, int targetFriend) {
        int n = times.length;
        PriorityQueue<Integer> available_chairs = new PriorityQueue();
        PriorityQueue<int[]> leaving = new PriorityQueue<>((a,b)->{
            return a[0]-b[0];
        });
        int index =0;
        int max =0;
        int chair =0;
        Map<Integer,Integer> mapper = new HashMap();
      
        for(int[] time:times){
            mapper.put(time[0], index++);
        }
        Arrays.sort(times, (a,b)-> a[0]-b[0]);
        index =0 ;
        for(int[] time:times){
          
            int arrival_time = time[0];
            int leaving_time = time[1];
            if(!leaving.isEmpty()){
                int[] min_leaving = leaving.peek();
                while(min_leaving[0]<=arrival_time){
                    available_chairs.add(min_leaving[1]);
                    leaving.poll();
                    if(leaving.isEmpty()) break;
                    min_leaving = leaving.peek();
                }
            }
        
            if(!available_chairs.isEmpty()){
               chair = available_chairs.poll();
            }
            else {
                chair = max++;
            }
            int fr_number = mapper.get(arrival_time);
            if(fr_number == targetFriend) return chair;
          
            leaving.add(new int[]{leaving_time,chair});
          
        }
        return -1;
    }
}
tính lưu cái leaving vào treemap mà ko nhận ra vấn đề n=1000 thôi mà tạo 1000 cái array list MLE
XZlCqK8.png
bảo sao tìm mãi mà n bé tí cũng ăn MLE
exp: TreeMap<key , List<>> = MLE
rn0vAkf.png
 
Em mới xong round livecode 2, đề dễ lắm nên e cũng k mention đây. Nhưng có vài điểm thú vị. Đó là follow up, xoáy vào multi-thread, khúc này e dùng synchronized, sau đó bị hỏi cách khác => atomic counter. Và câu follow up cuối em bị choke. Solution của e đang là O(1), interviewer sửa code lại thành O(n) và kêu e finish/fix đoạn này cho nó chạy. Đoạn này choke vì tư duy đang luôn tìm solution lẹ nhất -.- nên loay hoay mãi.
 
Em mới xong round livecode 2, đề dễ lắm nên e cũng k mention đây. Nhưng có vài điểm thú vị. Đó là follow up, xoáy vào multi-thread, khúc này e dùng synchronized, sau đó bị hỏi cách khác => atomic counter. Và câu follow up cuối em bị choke. Solution của e đang là O(1), interviewer sửa code lại thành O(n) và kêu e finish/fix đoạn này cho nó chạy. Đoạn này choke vì tư duy đang luôn tìm solution lẹ nhất -.- nên loay hoay mãi.
fency phỏng vấn role gì đấy :shame:

via theNEXTvoz for iPhone
 
Java:
class Solution {
    public int smallestChair(int[][] times, int targetFriend) {
        int n = times.length;
        Integer[] idxArr = new Integer[n];

        for (int i = 0; i < n; i++) {
            idxArr[i] = i;
        }

        Arrays.sort(idxArr, (a, b) -> {
            return times[a][0] - times[b][0];
        });

        int[] trackingArr = new int[n];

        for (int num : idxArr) {
            int arrive = times[num][0], leave = times[num][1];

            for (int i = 0; i < n; i++) {
                if (trackingArr[i] <= arrive) {
                    trackingArr[i] = leave;
                    if (num == targetFriend) {
                        return i;
                    }
                    break;
                }
            }
        }

        return 0;
    }
}
 
Em mới xong round livecode 2, đề dễ lắm nên e cũng k mention đây. Nhưng có vài điểm thú vị. Đó là follow up, xoáy vào multi-thread, khúc này e dùng synchronized, sau đó bị hỏi cách khác => atomic counter. Và câu follow up cuối em bị choke. Solution của e đang là O(1), interviewer sửa code lại thành O(n) và kêu e finish/fix đoạn này cho nó chạy. Đoạn này choke vì tư duy đang luôn tìm solution lẹ nhất -.- nên loay hoay mãi.
Em thấy bác dính live coding về multi-thread khá nhiều. Bác share về cty bác apply (cái nào bác process xong r ấy ạ) với cách ôn mấy dạng như này em tham khảo với. Nhạy cảm quá thì cho em xin hộp bác nhé
 
Em thấy bác dính live coding về multi-thread khá nhiều. Bác share về cty bác apply (cái nào bác process xong r ấy ạ) với cách ôn mấy dạng như này em tham khảo với. Nhạy cảm quá thì cho em xin hộp bác nhé
E cũng k có ôn gì multithread hết thím, tại cũng k có giải topic đó nhiều. Nói chung là bị hỏi vậy thì làm theo kiến thức khi đi làm thôi. Còn thím ôn thì hổm có thím nào share trên leetcode có topic multihread ấy, khá là ok.
 
C#:
public class Solution
{
    public int SmallestChair(int[][] times, int targetFriend)
    {
        int[] target = times[targetFriend];
        Array.Sort(times, (a, b) => a[0] - b[0]);
        PriorityQueue<(int, int), int> q = new(); // timeOut, seat, timeOut
        PriorityQueue<int, int> usableChairs = new();

        int maxSeat = 0;
        for (int i = 0; i < times.Length; i++)
        {
            int[] time = times[i];
            while (q.Count > 0)
            {
                (int, int) peek = q.Peek();
                if (time[0] < peek.Item1)
                {
                    break;
                }
                int chair = q.Dequeue().Item2;
                usableChairs.Enqueue(chair, chair);
            }

            int seat;
            if (usableChairs.Count == 0)
            {
                seat = maxSeat;
                maxSeat++;
            }
            else
            {
                seat = usableChairs.Dequeue();
            }
            q.Enqueue((time[1], seat), time[1]);
            if (time[0] == target[0] && time[1] == target[1])
            {
                return seat;
            }
        }

        return -1;
    }
}
 
hôm nay cop bài để làm bài tập multithreading vì xưa nay xài Ruby và JS chỉ biết async, không biết ba cái mutex semaphore atomic hình dong ntn mà giờ phải biết vì job có xài, bài tập đưa ra một danh sách các phát biểu rồi hỏi coi phát biểu đó đang nói về tính chất safety ("bad things must not happen") hay là liveness ("good things eventually happen), nhưng đến câu này thì mình bí:

You can always tell a Sorbonne man.

các cao nhân có cao kiến gì không?
 
hôm nay cop bài để làm bài tập multithreading vì xưa nay xài Ruby và JS chỉ biết async, không biết ba cái mutex semaphore atomic hình dong ntn mà giờ phải biết vì job có xài, bài tập đưa ra một danh sách các phát biểu rồi hỏi coi phát biểu đó đang nói về tính chất safety ("bad things must not happen") hay là liveness ("good things eventually happen), nhưng đến câu này thì mình bí:



các cao nhân có cao kiến gì không?

Mình hỏi hơi ngoài lề một chút.
Bạn đang học ở Massachusetts Institute of Technology à ?
Lần trước mình cũng thấy bạn muốn chứng minh thuật toán theo chuẩn các bước của cuốn sách CLRS đặt ra, rồi cũng thấy bạn làm bài tập toán xác suất của MIT.
 
hôm nay cop bài để làm bài tập multithreading vì xưa nay xài Ruby và JS chỉ biết async, không biết ba cái mutex semaphore atomic hình dong ntn mà giờ phải biết vì job có xài, bài tập đưa ra một danh sách các phát biểu rồi hỏi coi phát biểu đó đang nói về tính chất safety ("bad things must not happen") hay là liveness ("good things eventually happen), nhưng đến câu này thì mình bí:



các cao nhân có cao kiến gì không?
em không hiểu đề lắm bác, bác giải thích lại được không ạ.
 
Python:
class Solution:
    def minGroups(self, intervals: List[List[int]]) -> int:
        lines = set()
        countStart = defaultdict(int)
        countEnd = defaultdict(int)
        for start, end in intervals:
            countStart[start] += 1
            countEnd[end] -= 1
            lines.add(start)
            lines.add(end)

        lines = sorted(lines)
        groups = 0
        ans = 0
        for l in lines:
            groups += countStart[l]
            ans = max(ans, groups)
            groups += countEnd[l]

        return ans
 
Python:
class Solution:
    def minGroups(self, intervals: List[List[int]]) -> int:
        lines = set()
        countStart = defaultdict(int)
        countEnd = defaultdict(int)
        for start, end in intervals:
            countStart[start] += 1
            countEnd[end] -= 1
            lines.add(start)
            lines.add(end)

        lines = sorted(lines)
        groups = 0
        ans = 0
        for l in lines:
            groups += countStart[l]
            ans = max(ans, groups)
            groups += countEnd[l]

        return ans
dài quá :shame:
 
Python:
class Solution:
    def minGroups(self, intervals: List[List[int]]) -> int:
        heap = []
        for left, right in intervals:
            heapq.heappush(heap, (left, right))
        group = []

        while heap:
            left, right = heapq.heappop(heap)
            if group and group[0] < left:
                heapq.heappop(group)
            heapq.heappush(group, right)
        return len(group)
 
Python:
class Solution:
    def minGroups(self, A: List[List[int]]) -> int:
        A = sorted(A)
        q = []
        for s,e in A:
            if q and q[0] < s:
                heapq.heappop(q)
            heapq.heappush(q, e)
        return len(q)
 
JavaScript:
var minGroups = function (intervals) {
    intervals.sort((u, v) => u[0] - v[0]);
    const pq = new MinPriorityQueue();
    let ans = 0, free = 0;
    for (const [u, v] of intervals) {
        while (!pq.isEmpty() && pq.front().element < u) {
            pq.dequeue();
            free++;
        }
        if (free > 0) {
            free--;
        } else {
            ans++;
        }
        pq.enqueue(v);
    }
    return ans;
};
 
Python:
class Solution:
    def minGroups(self, intervals: List[List[int]]) -> int:
        lines = set()
        countStart = defaultdict(int)
        countEnd = defaultdict(int)
        for start, end in intervals:
            countStart[start] += 1
            countEnd[end] -= 1
            lines.add(start)
            lines.add(end)

        lines = sorted(lines)
        groups = 0
        ans = 0
        for l in lines:
            groups += countStart[l]
            ans = max(ans, groups)
            groups += countEnd[l]

        return ans
Thím này phù hợp đi làm outsource cho nhựt bổn, trả lương theo LOC, :cautious:
 
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.214.086
Quay lại
Lên đầu trang