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

BS Week :D

Python:
class Solution:
    def maxDistance(self, p: List[int], m: int) -> int:
        p.sort()
        l = 1
        r = p[-1] - p[0]
        def can_put_the_balls(f):
            count = 1
            last_pos = p[0]
            for i in range(1, len(p)):
                if p[i] - last_pos >= f:
                    count += 1
                    last_pos = p[i]
                    if count == m:
                        return True
            return False
        ans = 0
        while l <= r:
            mid = l + (r - l) // 2
            if can_put_the_balls(mid):
                l = mid + 1
                ans = mid
            else:
                r = mid - 1
                
        return ans
 
Java:
class Solution {
    public int maxDistance(int[] position, int m) {
        Arrays.sort(position);
        int n = position.length;
        int left = 1;
        int right = position[n - 1] - position[0];
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (condition(position, m, mid)) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        return left;
    }

    boolean condition(int[] pos, int m, int range){
        int n = pos.length;
        int last_pos = 0;
        int cnt=1;
        for(int i = 1; i<n;i++){
            if(pos[i]-pos[last_pos]>range){
                last_pos = i;
                cnt++;
            }
            if(cnt==m) return true;
        }
        return false;
    }
}
 
Python:
class Solution:
    def maxDistance(self, position: List[int], m: int) -> int:
        position = sorted(position)
        n = len(position)
        def good(minimum):
            count = 0
            prev = position[0]
            for i in range(1, n):
                if position[i] - prev >= minimum:
                    count += 1
                    prev = position[i]

                if count + 1 == m:
                    return True

            return False
      
        left = 0
        right = position[-1] - position[0]

        ans = 0
        while left <= right:
            mid = left + (right - left)//2
            if good(mid):
                ans = mid
                left = mid + 1
            else:
                right = mid - 1

        return ans
vẫn chưa hiểu khi nào l<=r khi nào l<r bác ạ.
nhưng mà đọc bài viết hôm qua thấy template l<r giải dc mọi bài nên e xài
RmA5ODa.png
 
Last edited:
Mấy thím học giải thuật kiểu gì thế ợ, trư lên youtube coi mà thấy khó hiểu quá
học nội công tâm pháp : cấu trúc dữ liệu & giải thuật đi fen. đừng đi tắt giải leetcode trước.
trong mọi chương trình học đều có môn cấu trúc dữ liệu và giải thuật đó fen. base đều từ đây mà ra cả,
cái môn này mà fen thuần thục dc mọi chủ đề trong đó thôi là cứng lắm r, nhiều khi học môn này xong mà ko biết áp dụng vào để làm đấy chứ môn này mạnh lắm.
 
BS duoi co edge case tai m = 2.
C++:
class Solution {
public:
    int maxDistance(vector<int>& pos, int m) {
        sort(begin(pos), end(pos));
        if (m == 2) return pos.back() - pos[0];
        int n = pos.size(), lo = 1, hi = pos[n - 1] - pos[0];
        function<bool(int)> solve = [&](int dis) -> bool {
            int cnt = 1, i = 0;
            while (cnt < m) {
                i = lower_bound(begin(pos) + i, end(pos), dis + pos[i]) - begin(pos);
                if (i == n) break;
                cnt++;
            }
            return cnt >= m;
        };
        while (lo < hi) {
            int mi = (lo + hi) / 2;
            if (solve(mi)) lo = mi + 1;
            else hi = mi;
        }
        return lo - 1;
    }
};
 
vẫn chưa hiểu khi nào l<=r khi nào l<r bác ạ.
nhưng mà đọc bài viết hôm qua thấy template l<r giải dc mọi bài nên e xài
RmA5ODa.png
Có bài phải ktra lại điểm left cuối cùng có thoả mãn yêu cầu của đề bài nữa ko thì phải fence, trong trường hợp array chứa duplicated thì phải thì sẽ ăn bug. Nên xài left <= right rồi gán variable như mình mới cover được hết tất cả các bài.
 
vẫn chưa hiểu khi nào l<=r khi nào l<r bác ạ.
nhưng mà đọc bài viết hôm qua thấy template l<r giải dc mọi bài nên e xài
RmA5ODa.png
Tối mới đọc luôn nè nhưng đang nghiệm thêm
Code:
4. while loop
To keep the logic simple, I always use

while(lo < hi) { ... }
Why? Because this way, the only condition the loop exits is lo == hi. I know they will be pointing to the same element, and I know that element always exists.
 
position = [5,4,3,2,1,1000000000], m = 2
position = [1,2,3,4,5,1000000000], m = 2

thứ tự của item trong mảng position có quan trọng k các bác nhỉ, em thử 2 case trên thì kết quả đều là 9999999.
Đề khó hiểu quá :ah:
 
position = [5,4,3,2,1,1000000000], m = 2
position = [1,2,3,4,5,1000000000], m = 2

thứ tự của item trong mảng position có quan trọng k các bác nhỉ, em thử 2 case trên thì kết quả đều là 9999999.
Đề khó hiểu quá :ah:
Quan trọng là vị trí position, chỉ số i ko cần quan tâm. Sort lại mảng tăng dần là được
 
Ai code ios swift ko ạ ?
Swift:
// Problem: https://leetcode.com/problems/magnetic-force-between-two-balls/
class Solution {
    func maxDistance(_ position: [Int], _ m: Int) -> Int {
        let sortedPos = position.sorted()
        let len = position.count

        func validate(_ value: Int) -> Bool {
            var cnt = 1
            var next = 1
            var currentPos = sortedPos[0]

            while (next < len) {
                if currentPos + value <= sortedPos[next] {
                    // nếu có position tiếp theo
                    currentPos = sortedPos[next]
                    next += 1
                    cnt += 1
                } else {
                    next += 1
                }

                if cnt == m {
                    return true
                }
            }
            return false
        }

        // value min is 1, max is last-first
        var left: Int = 1
        var right: Int = sortedPos[len-1] - sortedPos[0]
        var ans: Int = 0
        while (left <= right) {
            let mid: Int = (left + right)/2
            if (validate(mid)) {
                ans = max(ans, mid)
                left = mid + 1
            } else {
                // search in just case (left, mid-1)
                right = mid - 1
            }
        }
       
        return ans
    }
}
 
Last edited:
Ai code ios swift ko ạ ?
Swift:
// Problem: https://leetcode.com/problems/magnetic-force-between-two-balls/
class Solution {
    func maxDistance(_ position: [Int], _ m: Int) -> Int {
        let sortedPos = position.sorted()
        let len = position.count

        func validate(_ value: Int) -> Bool {
            var cnt = 1
            var next = 1
            var currentPos = sortedPos[0]

            while (next < len) {
                if currentPos + value <= sortedPos[next] {
                    // nếu có position tiếp theo
                    currentPos = sortedPos[next]
                    next += 1
                    cnt += 1
                } else {
                    next += 1
                }

                if cnt == m {
                    return true
                }
            }
            return false
        }

        // value min is 1, max is last-first
        var left: Int = 1
        var right: Int = sortedPos[len-1] - sortedPos[0]
        var ans: Int = 0
        while (left <= right) {
            let mid: Int = (left + right)/2
            if (validate(mid)) {
                ans = max(ans, mid)
                left = mid + 1
            } else {
                // search in just case (left, mid-1)
                right = mid - 1
            }
        }
      
        return ans
    }
}
Minh dang hoc Swift, dang con ga lam :LOL: Toan code C++/Obj-C++ roi port qua
 
"For those having difficulty in understanding the problem, replace force with distance and balls with boys.
Now this problem reduces to daily problem - in a male toilet, find a slot such that minimum distance from other boy is maximized.
Thank me later!"

K thể thẩm được đề gốc, phải lái đề theo cái comment này thì mới hiểu
 
Python:
class Solution:
    def maxDistance(self, position: List[int], m: int) -> int:
        def check(minDistance):
            balls = 0
            prev = -math.inf
            for pos in position:
                if pos - prev >= minDistance:
                    balls += 1
                    if balls == m:
                        return True
                    prev = pos
            return False

        position.sort()
        lo = 1
        hi = (position[-1] - position[0] + 1) // (m - 1)
        while lo < hi:
            mid = (lo + hi + 1) // 2
            if check(mid):
                lo = mid
            else:
                hi = mid - 1
        return lo

Python:
class Solution:
    def maxDistance(self, position: List[int], m: int) -> int:
        def check(minDistance):
            balls = 0
            prev = -math.inf
            for pos in position:
                if pos - prev >= minDistance:
                    balls += 1
                    if balls == m:
                        return True
                    prev = pos
            return False

        position.sort()
        lo = 1
        hi = (position[-1] - position[0] + 1) // (m - 1)
        searchRange = range(hi, lo - 1, -1)
        return searchRange[bisect.bisect_left(searchRange, x=True, key=check)]
 
Last edited:
Mấy thím học giải thuật kiểu gì thế ợ, trư lên youtube coi mà thấy khó hiểu quá
Mấy nay em đang học trên này nè, thấy khóa này dạy bằng pseudocode nên cũng dễ hiểu lắm. Hơi nặng chứng minh với lý thuyết thôi.
Khóa này thì của princeton, nếu thím biết C++ rồi thì học java cũng nhanh thôi.
Cái này học free trên OCW của MIT, có bài tập với videos luôn
 
Back
Top