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.
ờm chỗ speedSum toy ko để ý
MjfezZB.png

mà lạ vậy pq size là k vẫn đúng à
BdgiW7R.png
à chắc vì xét max sau khi -= nên vẫn đúng
OG0lsXv.png
thì bác thử đi

Đây trư re-submit lại lần thứ n vẫn đúng: https://leetcode.com/submissions/detail/797171689/
 
220912: 948. Bag of Tokens
Bài hôm nay medium mà thấy khó hơn 2 bài hard cuối tuần. Mãi mới ra được cách O(n^2) 5%. Nhưng có thể optimize thành O(nlogn) hoặc O(n).
https://leetcode.com/submissions/detail/797684352/


Ý tưởng
  • Sort token từ lớn đến đến nhỏ,
  • Tính prefix sum
  • Chiến lược chơi:
- Chia token làm ba phần: phần I gồm nhưng token giá trị lớn là down để lấy power, phần II là nothing không làm gì cả, phần III là up gồm nhưng token giá trị nhỏ để score,​
- Thử hết các boundary của 3 phần để tìm score lớn nhất,​
- Do điều kiện để down thì cần score >= 1 nên nếu từ đầu power nhỏ hơn token nhỏ nhất thì trả về 0 luôn.​
[/ispoler]
 
220912: 948. Bag of Tokens
Bài hôm nay medium mà thấy khó hơn 2 bài hard cuối tuần. Mãi mới ra được cách O(n^2) 5%. Nhưng có thể optimize thành O(nlogn) hoặc O(n).
T lại thấy bài hôm nay dễ hơn, :p. Dùng 2 pointers thôi
B1: Sort cái tokens
B2: Dùng indies bên trái và bên phải để loop qua cái tokens. Face up thì lấy token bên trái (mất ít power nhất). Face down thì lấy bên phải (được nhiều power nhất).
https://leetcode.com/submissions/detail/797693682/
 
T lại thấy bài hôm nay dễ hơn, :p. Dùng 2 pointers thôi
B1: Sort cái tokens
B2: Dùng indies bên trái và bên phải để loop qua cái tokens. Face up thì lấy token bên trái (mất ít power nhất). Face down thì lấy bên phải (được nhiều power nhất).
https://leetcode.com/submissions/detail/797693682/
Mình cũng làm như này, mà lúc đầu ko để ý dính 2 cái edge case [] với [26],51 :beat_brick:
O(nlogn) nhưng mà beat được có 20% :angry:
https://leetcode.com/submissions/detail/797610108/
 
OG0lsXv.png
ủa mà hàm trong Python không có chức năng "Khai báo trước" (Forward declaration) à các bác?
 
bài hôm nay toy thử greedy 2 con chỏ phát được luôn, ý tưởng đơn giản là sort tokens ròi xài 2 con chỏ tham lam khi nào power > giá trị của con chỏ thứ nhứt thì trừ nó đi ++score, hết được thì cộng giá trị của con chỏ thứ 2 vào, --score.

5 dòng
aVgiONl.png


C++:
struct Solution {
    int bagOfTokensScore(vector<int>& tokens, int power) {
        sort(begin(tokens), end(tokens));
        for (int i = 0, j = tokens.size() - 1, score = 0;;) {
            while (i <= j && power >= tokens[i]) power -= tokens[i++], ++score;
            if (score == 0 || i >= j || tokens[j] + power < tokens[i]) return score;
            power += tokens[j--], --score;
        }
    }
};
 
Elixir, hơi dài dòng do phải dùng 2 list để tăng performance
hkNtitg.png


Mã:
defmodule Solution do
  def bag_of_tokens_score(tokens, power) do
    play(
      tokens |> Enum.sort(),
      tokens |> Enum.sort(:desc),
      power,
      tokens |> Enum.count(),
      0,
      0
    )
  end
  defp play(_up, _down, _power, n, played, score) when played == n, do: score
  defp play([cost | c_rest] = up, [restore | r_rest] = down, power, n, played, score) do
    cond do
      power >= cost -> play(c_rest, down, power - cost, n, played + 1, score + 1)
      score == 0 or played == n - 1 -> score
      true -> play(up, r_rest, power + restore, n, played + 1, score - 1)
    end
  end
end
 
Sửa lần cuối:
Python:
class Solution:
    def bagOfTokensScore(self, tokens: List[int], power: int) -> int:
        tokens=sorted(tokens)
        left,right=0,len(tokens)-1
        score, res = 0, 0
        while left<=right and power>=tokens[left]:
            score+=1
            power-=tokens[left]
            left+=1
            res=max(res,score)
            while left<=right and power<tokens[left] and score>=1:
                power+=tokens[right]
                right-=1
                score-=1
        return res
 
Python:
class Solution:
    def bagOfTokensScore(self, tokens: List[int], power: int) -> int:
        tokens.sort()
        l, r = 0, len(tokens) - 1
        res, res_max = 0, 0

        while l <= r:
            while l <= r and power >= tokens[l]:
                power -= tokens[l]
                res += 1
                l += 1
               
            res_max = max(res_max, res)

            if res >= 1:
                res -= 1
                power += tokens[r]
                r -= 1
               
            if l <= r and res == 0 and power < tokens[l]:
                break
           
        return res_max
 
220913 - 393. UTF-8 Validation

Hôm nay đúng bài về bit manipulation sở trưởng, thử đổi gió sang scala.
Ý tưởng là đảo ngược các bit rồi dùng hàm để đếm số bit 0 ở đầu, hầu như ngôn ngữ nào cũng có sẵn hàm này.

https://leetcode.com/submissions/detail/798415076/

1663035030247.png

 
Sửa lần cuối:
Bài này là check điều kiện với số tự nhiên do ko sở trường món bit manipulation :sad:
https://leetcode.com/submissions/detail/798441298/
Python:
class Solution:
    def validUtf8(self, data: List[int]):
        def check_type(num):
            if 0 <= num <= 127:
                return 0
            elif num <= 191:
                return -1
            elif num <= 223:
                return 1
            elif num <= 239:
                return 2
            elif num <= 247:
                return 3
            else:
                return None

        remain = 0
        for num in data:
            tp = check_type(num)
            # print(remain, tp)
            if tp is None:
                return False
            if remain == 0 and tp < 0:
                return False
            elif remain > 0 and  tp >= 0:
                return False
            remain += tp
        
        if remain == 0:
            return True
        else:
            return False
 
"1" dòng return
cgE9MkI.gif

edit: ơ xài all_of tiện hơn
MjfezZB.png


C++:
struct Solution {
    bool validUtf8(vector<int>& data, int remainingBytes = 0) {
        return all_of(begin(data), end(data), [&](int byte){
            return ((byte >> 7) == 0b0 && !remainingBytes) ||
                   ((byte >> 6) == 0b10 && remainingBytes--) ||
                   ((byte >> 5) == 0b110 && !exchange(remainingBytes, 1)) ||
                   ((byte >> 4) == 0b1110 && !exchange(remainingBytes, 2)) ||
                   ((byte >> 3) == 0b11110 && !exchange(remainingBytes, 3));
        }) && !remainingBytes;
    }
};


bỏ () đi, code này rắc nguy hiểm toy đang bị interpool truy nã vì viết dòng code này đây
gvTwnV8.gif
gvTwnV8.gif
gvTwnV8.gif


C++:
struct Solution {
    bool validUtf8(vector<int>& data, int remainingBytes = 0) {
        return all_of(begin(data), end(data), [&](int byte){
            return byte >> 7 == 0b0 && !remainingBytes ||
                   byte >> 6 == 0b10 && remainingBytes-- ||
                   byte >> 5 == 0b110 && !exchange(remainingBytes, 1) ||
                   byte >> 4 == 0b1110 && !exchange(remainingBytes, 2) ||
                   byte >> 3 == 0b11110 && !exchange(remainingBytes, 3);
        }) && !remainingBytes;
    }
};
 
Sửa lần cuối:
Pattern matching
janDexM.jpg


Mã:
defmodule Solution do
  def valid_utf8(data), do: check(Enum.map(data, &to_bin/1))
  defp check([]), do: true
  defp check(["0" <> _ | rest]), do: check(rest)
  defp check(["110" <> _, "10" <> _ | rest]), do: check(rest)
  defp check(["1110" <> _, "10" <> _, "10" <> _ | rest]), do: check(rest)
  defp check(["11110" <> _, "10" <> _, "10" <> _, "10" <> _ | rest]), do: check(rest)
  defp check(_), do: false
  defp to_bin(num), do: :io_lib.format("~8.2.0B", [num]) |> List.to_string()
end
 
Sửa lần cuối:
:angry: cái bài gì mà dislike nhiều hơn like thế này?
chắc là do ko check đủ hết điều kiện valid utf-8. Có thằng xài Python .decode('utf8') để check thì ra xai vì utf8 hiện tại chỉ encode 17 planes = 16 * 2^16 = 1,114,112 code points thoy
TG0OxM9.gif
input [244,164,190,128] là code point 1,200,000 là invalid Unicode code point thì Python utf8 decoder sẽ reject, trong khi bài này vẫn cho là đúng.

Ngoài ra bài này nó cũng ko check overlong encoding, ví dụ code point 0 encode đúng sẽ thành 1 byte 0x00, nhưng cũng có thể encode sai thành 2 bytes 0xc0 0x80 là [192,128] thì Python utf8 decoder nó sẽ reject nhưng bài này vẫn cho là đúng.

Nếu strict hơn nữa thì phải reject luôn các surrogate code points vì các code points này ko valid trong utf16, nếu utf8/utf32 encode các code points này thì khi chuyển utf8/utf32 text sang utf16 text sẽ ko chuyển được, Python utf8 decoder có check cái này: 0xDC00 encode thành [240,141,176,128] bài này trả về true nhưng strict utf8 decoder sẽ trả về false
 
OG0lsXv.png
đậu xanh, voz lại sập
janDexM.jpg
Mà lần này sập hơi lâu. Có big update gì à?


Hay chả qua hôm nay có ai đó say xỉn quá mà lại đái vào server chăng?
tFvvWhy.jpg
 
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.212.745
Quay lại
Lên đầu trang