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.
JavaScript:
var maximumBeauty = function (items, queries) {
    const sorted = [...items].sort((u, v) => {
        return u[0] - v[0] || v[1] - u[1];
    });
    items.length = 0;
    for (const item of sorted) {
        if (!items.length || item[1] > items[items.length-1][1]) {
            items.push(item);
        }
    }
    return queries.map(q => {
        const idx = _.sortedLastIndexBy(items, [q], '0');
        console.log({ q, idx });
        return idx ? items[idx-1][1] : 0;
    });
};
 
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:
lòng người còn thay đổi nữa là vài 3 dòng code :canny:
Edit: template l < r vẫn chạy, nhưng nhìn code nó ko... tự nhiên lắm :canny:
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;
        while (l < r) {
            const m = l + Math.floor((r - l) / 2);
            if (maxList[m][0] > p) {
                r = m;
            } else {
                l = m + 1;
            }
        }

        const cur = l > 0 ? maxList[l - 1][1] : 0;
        res.push(cur);
    }

    return res;
}
 
Sửa lần cuối:
Python:
class Solution:
    def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]:
        items.sort()
        prev_max_beauty = 0
        for item in items:
            prev_max_beauty = item[1] = max(item[1], prev_max_beauty)

        res = []
        for query in queries:
            l, r = 0, len(items)
            while l < r:
                mid = (l + r)//2
                if items[mid][0] <= query:
                    l = mid + 1
                else:
                    r = mid
            if l == 0:
                res.append(0)
            else:
                res.append(items[l - 1][1])
        
        return res
 
Bảo rồi ko nghe trình độ chưa đủ mà nó cứ nhăm nhe đòi đấm, giờ lại quay qua chửi ae bỏ rơi
osCpCsi.gif
mạt vận

via theNEXTvoz for iPhone
 
Python:
class Solution(object):
    def maximumBeauty(self, items, queries):
        items.sort(key = lambda x: (x[0], -x[1]))
        cur_max = items[0][1]
        n = len(items)
        for i in range(n):
            cur_max = max(cur_max, items[i][1])
            items[i][1] = cur_max

        def search(num):
            l, r = 0, n - 1
            while l <= r:
                mid = (l + r) // 2
                if items[mid][0] > num:
                    r = mid - 1
                else:
                    l = mid + 1
            return items[r][1] if r >= 0 else 0

        return [search(i) for i in queries]
 
C++:
func binarySearch(num int, arr [][]int) int {
    low, high := 0, len(arr)-1
    found := -1

    for low <= high {
        mid := (low + high) / 2
        if arr[mid][0] <= num {
            found = mid
            low = mid + 1
        } else {
            high = mid - 1
        }
    }

    return found
}

func maximumBeauty(items [][]int, queries []int) []int {
    sort.Slice(items, func(i, j int) bool {
        return items[i][0] < items[j][0]
    })

    n := len(items)
    maxBeauty := make([]int, n)
    maxBeauty[0] = items[0][1]

    for i := 1; i < n; i++ {
        if items[i][1] > maxBeauty[i-1] {
            maxBeauty[i] = items[i][1]
        } else {
            maxBeauty[i] = maxBeauty[i-1]
        }
    }

    results := make([]int, len(queries))
    memo := make(map[int]int)

    for i, val := range queries {
        if cachedValue, exists := memo[val]; exists {
            results[i] = cachedValue
            continue
        }

        j := binarySearch(val, items)

        if j == -1 {
            results[i] = 0
            memo[val] = 0
        } else {
            results[i] = maxBeauty[j]
            memo[val] = maxBeauty[j]
        }
    }

    return results
}
 
mình thấy l < r hay l <= r đều được, l < r thì khi kết thúc l == r, l <= r thì khi kết thúc l > r.
cái l<r nó có chia thành 2 case (maximize, minimize -> vai trò l r thay đổi nên ko có consistent) còn l<=r thì khỏi nghĩ gì hết cứ condition đúng update lại result thôi. nhìn code l<r đẹp hơn gọn hơn nhưng áp sai thấy cảnh debug liền ko còn đúng mục đích khi sài template nữa
uEspPCS.png
 
C++:
class Solution {
public:
    vector<int> maximumBeauty(vector<vector<int>>& items, vector<int>& queries) {
        auto queryMap = map<int, vector<int>>();
        for (auto i = 0; i < queries.size(); ++i) { queryMap[queries[i]].push_back(i); }

        sort(items.begin(), items.end(), [](const vector<int>& item_a, const vector<int>& item_b) {
            return item_a[0] < item_b[0];
        });

        auto itemIter = items.begin(); auto currentMaxBeauty = 0;
        auto maxBeauties = vector<int>(queries.size(), 0);
        for (const auto& priceIndexes : queryMap) {
            for (; itemIter < items.end() && (*itemIter)[0] <= priceIndexes.first; ++itemIter) {
                if (currentMaxBeauty < (*itemIter)[1]) currentMaxBeauty = (*itemIter)[1];
            }
            for (const auto& j : priceIndexes.second) {
                maxBeauties[j] = currentMaxBeauty;
            }
        }
        return maxBeauties;
    }
};
 
Sửa lần cuối:
LC 2070 map
Java:
class Solution {
    public int[] maximumBeauty(int[][] items, int[] queries) {
        int nq = queries.length, cMaxB = 0, rs[] = new int[nq];
        Arrays.sort(items, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]);
        var tm = new TreeMap<Integer, Integer>();
        for (int[] e : items) if (cMaxB < e[1]) tm.put(e[0], cMaxB = e[1]);
        for (int i = 0; i < nq; i++) {
            var e = tm.floorEntry(queries[i]);
            if (e != null) rs[i] = e.getValue();
        }
        return rs;
    }
}
 
C++:
class Solution {
public:
    vector<int> maximumBeauty(vector<vector<int>>& items, vector<int>& queries) {
        int n = items.size();
        int m = queries.size();

        sort(items.begin(), items.end(), [] (const vector<int> &i1, const vector<int> &i2) {
            return i1[0] < i2[0];
        });

        vector<int> query_indexes(m);
        iota(query_indexes.begin(), query_indexes.end(), 0);
        sort(query_indexes.begin(), query_indexes.end(), [&queries] (const int &i, const int &j) {
            return queries[i] < queries[j];
        });

        vector<int> res(m);
        int p_items = 0;
        int max_beauty = 0;

        for (const int &index : query_indexes) {
            int query = queries[index];
            while (p_items < n && items[p_items][0] <= query) {
                max_beauty = max(max_beauty, items[p_items][1]);
                ++p_items;
            }
            res[index] = max_beauty;
        }
        return res;
    }
};
 
C++:
class Solution {
public:
    vector<int> maximumBeauty(vector<vector<int>>& items, vector<int>& queries) {
        int n = items.size();
        int m = queries.size();

        sort(items.begin(), items.end(), [] (const vector<int> &i1, const vector<int> &i2) {
            return i1[0] < i2[0];
        });

        vector<int> query_indexes(m);
        iota(query_indexes.begin(), query_indexes.end(), 0);
        sort(query_indexes.begin(), query_indexes.end(), [&queries] (const int &i, const int &j) {
            return queries[i] < queries[j];
        });

        vector<int> res(m);
        int p_items = 0;
        int max_beauty = 0;

        for (const int &index : query_indexes) {
            int query = queries[index];
            while (p_items < n && items[p_items][0] <= query) {
                max_beauty = max(max_beauty, items[p_items][1]);
                ++p_items;
            }
            res[index] = max_beauty;
        }
        return res;
    }
};
e cũng mlogm + nlogn mà sao xếp chót bên java :ah:
 
1st problem với các bác dùng kotlin
class Solution {
fun maximumBeauty(items: Array<IntArray>, queries: IntArray): IntArray {
items.sortBy { it[0] }
val queriesWithIndex = queries
.mapIndexed { index, value -> intArrayOf(index, value) }
.sortedBy { it.last() }
val result = IntArray(queries.size)
var ans = 0
var curIdx = 0
for ((idx, value) in queriesWithIndex) {
while (curIdx <= items.lastIndex && items[curIdx][0] <= value) {
ans = maxOf(ans, items[curIdx][1])
curIdx++
}
result[idx] = ans
}
return result
}
}
 
cái l<r nó có chia thành 2 case (maximize, minimize -> vai trò l r thay đổi nên ko có consistent) còn l<=r thì khỏi nghĩ gì hết cứ condition đúng update lại result thôi. nhìn code l<r đẹp hơn gọn hơn nhưng áp sai thấy cảnh debug liền ko còn đúng mục đích khi sài template nữa
uEspPCS.png
template thì vẫn phải sửa 3 chỗ mà, có phải là chỗ nào cũng viết giống nhau đâu :rap:
  • Correctly initialize the boundary variables left and right to specify search space. Only one rule: set up the boundary to include all possible elements;
  • Decide return value. Is it return left or return left - 1? Remember this: after exiting the while loop, left is the minimal k satisfying the condition function;
  • Design the condition function. This is the most difficult and most beautiful part. Needs lots of practice.
 
e cũng mlogm + nlogn mà sao xếp chót bên java :ah:
Vãi, sao lại dùng hashmap để store list indexes của từng query?
1731398648506.png


Xong mỗi lần duyệt qua queries lại update tất cả index của queries với queries[index] == queries. Ít nhất cũng phải check nếu đã tính rồi thì skip không tính nữa chứ

Cho bác 1 test case ví dụ nè: tất cả các queries đều có chung value
queries = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1..........] bác hãy chạy thử và cảm nhận
 
Vãi, sao lại dùng hashmap để store list indexes của từng query? Xem tệp đính kèm 2777899

Xong mỗi lần duyệt qua queries lại update tất cả index của queries với queries[index] == queries. Ít nhất cũng phải check nếu đã tính rồi thì skip không tính nữa chứ

Cho bác 1 test case ví dụ nè: tất cả các queries đều có chung value

queries = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1..........] bác hãy chạy thử và cảm nhận
e sort queries nên phải map để lưu lại cái vị trí ban đầu.
cái khúc này nhìn v thôi chứ nó cũng O(m+n) à. chạy query tăng dần thì cũng bốc từng cái item có price< query (tối đa pop hết m item ra khỏi queue) thôi. nếu query trùng nhau v thì chắc chắn ko chạy đoạn pop queue ra nữa đâu gán luôn max vào result mà
 
Python:
class Solution:
    def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]:
        items = sorted(items)
        queries = sorted([(queries[i], i) for i in range(len(queries))])
        ans = [0] * len(queries)

        i, max_beautiful = 0, 0
        for [q, j] in queries:
            while i < len(items) and items[i][0] <= q:
                max_beautiful = max(max_beautiful, items[i][1])
                i += 1
            ans[j] = max_beautiful

        return ans
 
Java:
class Solution {
    public static final int PRICE = 0;
    public static final int BEAUTY = 1;
    public int[] maximumBeauty(int[][] items, int[] queries) {
        Arrays.sort(items, new Comparator<int[]> () {
            @Override
            public int compare(int[] itemA, int[] itemB) {
                return itemA[PRICE] - itemB[PRICE];
            }
        });

        int[] maxBeautyAt = new int[items.length];
        int maximumBeauty = 0;
        int index = 0;
        for (int[] item : items) {
            maximumBeauty = Math.max(
                maximumBeauty,
                item[BEAUTY]
            );
            maxBeautyAt[index] = maximumBeauty;
            index++;
        }

        int[] answer = new int[queries.length];
        for (int i = 0; i < queries.length; i++) {
            int queryPrice = queries[i];
            int lastItem = lowerBoundPriceItem(items, queryPrice);
            answer[i] = (lastItem == -1) ? 0 : maxBeautyAt[lastItem];
        }

        return answer;
    }

    public int lowerBoundPriceItem(int[][] items, int queryPrice) {
        int found = -1;
        int left = 0, right = items.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (items[mid][PRICE] <= queryPrice) {
                found = mid;
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }

        return found;
    }
}

Code như này đủ đẹp chưa các bác :beauty: :beauty: :beauty:
 
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