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.
Fen có code ko cho mình coi, recursive thì phải dùng merge sort, mà merge sort thì phải dùng array chứ nhỉ

via theNEXTvoz for iPhone
Mã:
class Solution {
    public int[] sortArray(int[] nums) {
        Stack<Integer> stk = new Stack<>();
        for (int num : nums) {
            stk.add(num);
        }
        for (int i = 0; i < nums.length; i++) {
            sortStack(stk);
        }

        for (int i = nums.length - 1; i >= 0; i--) {
            nums[i] = stk.pop();
        }

        return nums;
    }

    public void sortStack(Stack<Integer> stk) {
        if (stk.isEmpty()) return;

        int top = stk.pop();
        if (!stk.isEmpty() && top < stk.peek()) {
            int temp = stk.pop();
            stk.add(top);
            top = temp;
        }

        sortStack(stk);

        stk.add(top);
    }
}
Em có vể thử thì được bác ạ, chỉ là bị TLE do độ phức tạp cao ấy bác
 
bác này chắc cũng hay hỏi ứng viên mấy câu khó nhằn ntn mới rành như v, để gọi a small lambda vào đấm mới dc
có bao h hỏi mấy câu khắm lọ đánh đố kiểu này đâu bác, mập mờ ngồi cãi nhau cũng tốn time, ko muốn nhận thì cho về luôn chứ bày đặt hỏi tricky đánh đố thể hiện làm cái gì đâu :D
 
có bao h hỏi mấy câu khắm lọ đánh đố kiểu này đâu bác, mập mờ ngồi cãi nhau cũng tốn time, ko muốn nhận thì cho về luôn chứ bày đặt hỏi tricky đánh đố thể hiện làm cái gì đâu :D
Chắc là hỏi vui thôi ấy bác, mấy ổng hỏi cuối giờ bác ạ
 
Mã:
class Solution {
    public int[] sortArray(int[] nums) {
        Stack<Integer> stk = new Stack<>();
        for (int num : nums) {
            stk.add(num);
        }
        for (int i = 0; i < nums.length; i++) {
            sortStack(stk);
        }

        for (int i = nums.length - 1; i >= 0; i--) {
            nums[i] = stk.pop();
        }

        return nums;
    }

    public void sortStack(Stack<Integer> stk) {
        if (stk.isEmpty()) return;

        int top = stk.pop();
        if (!stk.isEmpty() && top < stk.peek()) {
            int temp = stk.pop();
            stk.add(top);
            top = temp;
        }

        sortStack(stk);

        stk.add(top);
    }
}
Em có vể thử thì được bác ạ, chỉ là bị TLE do độ phức tạp cao ấy bác
Hợp lí nhỉ mà chắc tụi nó ko muốn tuyển fen rồi
zFNuZTA.gif


via theNEXTvoz for iPhone
 
Mã:
class Solution {
    public int[] sortArray(int[] nums) {
        Stack<Integer> stk = new Stack<>();
        for (int num : nums) {
            stk.add(num);
        }
        for (int i = 0; i < nums.length; i++) {
            sortStack(stk);
        }

        for (int i = nums.length - 1; i >= 0; i--) {
            nums[i] = stk.pop();
        }

        return nums;
    }

    public void sortStack(Stack<Integer> stk) {
        if (stk.isEmpty()) return;

        int top = stk.pop();
        if (!stk.isEmpty() && top < stk.peek()) {
            int temp = stk.pop();
            stk.add(top);
            top = temp;
        }

        sortStack(stk);

        stk.add(top);
    }
}
Em có vể thử thì được bác ạ, chỉ là bị TLE do độ phức tạp cao ấy bác
Mà fen viết code kiểu này là sai, đề nó cho stack rồi bắt sort trên đó chứ có đc phép access vô cái list nums ban đầu bằng vòng for đâu nhỉ
1BW9Wj4.gif

À cũng có thể dùng while trên length thôi chứ cũng ko vấn đề gì đoạn access này
via theNEXTvoz for iPhone
 
Mã:
class Solution {
    public int[] sortArray(int[] nums) {
        Stack<Integer> stk = new Stack<>();
        for (int num : nums) {
            stk.add(num);
        }
        for (int i = 0; i < nums.length; i++) {
            sortStack(stk);
        }

        for (int i = nums.length - 1; i >= 0; i--) {
            nums[i] = stk.pop();
        }

        return nums;
    }

    public void sortStack(Stack<Integer> stk) {
        if (stk.isEmpty()) return;

        int top = stk.pop();
        if (!stk.isEmpty() && top < stk.peek()) {
            int temp = stk.pop();
            stk.add(top);
            top = temp;
        }

        sortStack(stk);

        stk.add(top);
    }
}
Em có vể thử thì được bác ạ, chỉ là bị TLE do độ phức tạp cao ấy bác
Ý tưởng này dị thật, nó như kiểu bubble sort, mỗi lần gọi sortStack thì được một phần tử vào đúng vị trí, space complexity chắc cỡ O(n^2).
 
LC 2601 Java
Java:
class Solution {
    static boolean[] PS = pS(999);

    public static boolean primeSubOperation(int[] nums) {
        for (int i = 0; i < nums.length; i++) {
            int prev = i > 0 ? nums[i - 1] : 0;
            int p = pClUpTo(nums[i] - prev, PS);
            if (p != -1) nums[i] -= p;
            if (i > 0 && nums[i] <= nums[i - 1]) return false;
        }
        return true;
    }

    public static int pClUpTo(int p, boolean[] sieve) {
        while (p-- > 2) { if (sieve[p]) return p; }
        return p < 2 ? -1 : p;
    }

    public static boolean[] pS(int n) {
        boolean[] rs = new boolean[(int) (n + 1)];
        if (n >= 2) rs[2] = true;
        for (int i = 3; i <= n; i += 2) rs[i] = true;
        for (int i = 3, end = (int) Math.sqrt(n); i <= end; i += 2) {
            if (rs[i]) for (int j = i * i; j <= n; j += i << 1) rs[j] = false;
        }
        return rs;
    }
}
 
Sửa lần cuối:
LC 2601 Java
Java:
class Solution {
    static boolean[] PS = pS(999);

    public static boolean primeSubOperation(int[] nums) {
        for (int i = 0; i < nums.length; i++) {
            int prev = i > 0 ? nums[i - 1] : 0;
            int p = pClUpTo(nums[i] - prev, PS);
            if (p != -1) nums[i] -= p;
            if (i > 0 && nums[i] <= nums[i - 1]) return false;
        }
        return true;
    }

    public static int pClUpTo(int p, boolean[] sieve) {
        while (p-- > 2) { if (sieve[p]) return p; }
        return p < 2 ? -1 : p;
    }

    public static boolean[] pS(int n) {
        boolean[] rs = new boolean[(int) (n + 1)];
        if (n >= 2) rs[2] = true;
        for (int i = 3; i <= n; i += 2) rs[i] = true;
        for (int i = 3, end = (int) Math.sqrt(n); i <= end; i += 2) {
            if (rs[i]) for (int j = i * i; j <= n; j += i << 1) rs[j] = false;
        }
        return rs;
    }
}
Edited: straightforward approach, nvm, TC amortized O(N+logN)
 
Sửa lần cuối:
ví dụ 1001010, mình bật thêm 1 bit vào các số 0 thì có 4 cách chọn mà fen, riêng 1 cái bit đã có 4 cách chọn rồi, 32 phần tử sẽ có 2^32 chứ
4 cách chọn nhưng chỉ xảy ra 1 thôi, ví dụ OR thêm một phần tử thành 1001011 rồi thì sẽ không còn các trường hợp có dạng 1xx1x10 nữa. Nói chung là các OR thêm vào thì chỉ có là càng bật hết bit 1 lên theo một thứ tự nào đó thôi, bật tối đa 32 lần là hết
 
Sửa lần cuối:
Python:
class Solution:
    def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]:
        items = sorted(items)
        for i in range(1, len(items)):
            items[i][1] = max(items[i][1], items[i - 1][1])
        
        def bisect(target):
            left = 0
            right = len(items) - 1
            while left <= right:
                mid = left + (right - left)//2
                if target >= items[mid][0]:
                    left = mid + 1
                else:
                    right = mid - 1
            if left == 0:
                return 0
            return items[left - 1][1]
                
        return [ bisect(query) for query in queries ]
 
Sửa lần cuối:
C++:
class Solution {
public:
    vector<int> maximumBeauty(vector<vector<int>>& items, vector<int>& queries) {
        map<int, int> beauty;
        vector<int> newItems;
        int n = items.size();

        for (int i = 0; i < n; i++) {
            if (beauty[items[i][0]] == 0) {
                beauty[items[i][0]] = items[i][1];
                newItems.push_back(items[i][0]);
            }
            else {
                beauty[items[i][0]] = max(beauty[items[i][0]], items[i][1]);
            }
        }

        sort(newItems.begin(), newItems.end());

        int maxBeautySoFar = 0;
        for (int price : newItems) {
            maxBeautySoFar = max(maxBeautySoFar, beauty[price]);
            beauty[price] = maxBeautySoFar;
        }

        vector<int> ans;

        for (int i = 0; i < queries.size(); i++) {
            int key = binarySearch(newItems, queries[i]);
            if (key >= 0) { 
                ans.push_back(beauty[newItems[key]]);
            } else {
                ans.push_back(0);
            }
        }

        return ans;
    }

    int binarySearch(vector<int>& newItems, int target) {
        int left = 0;
        int right = newItems.size() - 1;

        while (left <= right) {
            int mid = (left + right) / 2;
            int value = newItems[mid];

            if (value == target) return mid;
            else if (value > target) right = mid - 1;
            else if (value < target) left = mid + 1;
        }

        return right; 
    }
};
 
C++:
class Solution {
public:
    vector<int> maximumBeauty(vector<vector<int>>& items, vector<int>& queries) {
        map<int, int> m;
        for (auto& p : items) {
            if (m.count(p[0]) == 0 || m[p[0]] < p[1])
                m[p[0]] = p[1];
        }
        int maxBeauty = 0;
        for (auto& p : m) {
            if (p.second < maxBeauty)
                p.second = maxBeauty;
            else if (maxBeauty < p.second)
                maxBeauty = p.second;
        }

        vector<int> ans;
        ans.reserve(queries.size());
        for (auto& q : queries) {
            auto lb = m.upper_bound(q);
            if (lb == m.begin())
                ans.push_back(0);
            else {
                lb--;
                ans.push_back(lb->second);
            }
        }
        return ans;
    }
};
 
Ý tưởng chung: Sort items -> precompute max beauty cho mỗi price-> dùng binary search
JavaScript:
function maximumBeauty(items: number[][], q: number[]): number[] {
    items.sort((a, b) => a[0] - b[0] || b[1] - a[1]);
    
    const maxList: number[][] = [];
    let curMax = 0;
    for (const [u, v] of items) {
        curMax = Math.max(curMax, v);
        maxList.push([u, curMax]);
    }
    const res: number[] = [];
    for (const p of q) {
        let l = 0, r = maxList.length - 1, cur = 0;
        while (l <= r) {
            const m = l + Math.floor((r - l) / 2);
            if (maxList[m][0] <= p) {
                cur = maxList[m][1];
                l = m + 1;
            } else {
                r = m - 1;
            }
        }
        res.push(cur);
    }

    return res;
}
@LmaoSuVuong trốn đâu rồi, áp dụng ngay kiến thức binary search hôm qua... :canny:
 
Java:
class Solution {
    public int[] maximumBeauty(int[][] items, int[] queries) {
        int n = queries.length;
        int[] res = new int[n];
        Map<Integer, List<Integer>> map = new HashMap<>();
        for (int i = 0; i < n; i++) {
            map.computeIfAbsent(queries[i], k -> new ArrayList());
            map.get(queries[i]).add(i);
        }
        Arrays.sort(queries);
        PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
        for (int[] item : items) {
            pq.add(item);
        }
        int max = 0;
        for (int i = 0; i < n; i++) {
            int query = queries[i];
            while (!pq.isEmpty() && pq.peek()[0] <= query) {
                max = Math.max(max, pq.poll()[1]);
            }
            for (int index : map.get(query)) {
                res[index] = max;
            }
        }
        return res;
    }
}
O92DbXG.gif
 
Ý tưởng chung: Sort items -> precompute max beauty cho mỗi price-> dùng binary search
JavaScript:
function maximumBeauty(items: number[][], q: number[]): number[] {
    items.sort((a, b) => a[0] - b[0] || b[1] - a[1]);
   
    const maxList: number[][] = [];
    let curMax = 0;
    for (const [u, v] of items) {
        curMax = Math.max(curMax, v);
        maxList.push([u, curMax]);
    }
    const res: number[] = [];
    for (const p of q) {
        let l = 0, r = maxList.length - 1, cur = 0;
        while (l <= r) {
            const m = l + Math.floor((r - l) / 2);
            if (maxList[m][0] <= p) {
                cur = maxList[m][1];
                l = m + 1;
            } else {
                r = m - 1;
            }
        }
        res.push(cur);
    }

    return res;
}
@LmaoSuVuong trốn đâu rồi, áp dụng ngay kiến thức binary search hôm qua... :canny:
sao bác lại phản bội lại template l<r :amazed: hôm qua e đã tin tưởng bác sử dụng chung 1 template nên mới cầu cứu mà :canny:
 
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.491
Quay lại
Lên đầu trang