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.
đúng là debug lòi trĩ thật.
C#:
public class CustomStack {
    public int[] Stack;
    public int Index;
    public int[] Lazy;
    public int MaxSize;
    public CustomStack(int maxSize) {
        Stack = new int[maxSize];
        Index = -1;
        Lazy = new int[maxSize];
        MaxSize = maxSize;
    }
    
    public void Push(int x) {
        // Console.WriteLine("xx{0} , {1} , {2}", Index, MaxSize, x);
        if (Index+1 < MaxSize) Stack[++Index] = x;
        // Console.WriteLine("xxx{0} , {1} , {2}", Index, MaxSize, x);
    }
    
    public int Pop() {
        if (Index < 0) return -1;
        // Console.WriteLine("yy{0} , {1}", Index, MaxSize);
        int result = Stack[Index] + Lazy[Index];
        // Console.WriteLine("yyy{0} , {1} , {2}", Index, MaxSize, result);
        if (Index > 0) {
            Lazy[Index - 1] += Lazy[Index];
        }
        Lazy[Index] = 0;
        // Console.WriteLine("yyyy{0} , {1} , {2}", Index, MaxSize, result);
        Index--;
        return result;
    }
    
    public void Increment(int k, int val) {
        int maxK = Math.Min(k, Index+1);
        // Console.WriteLine("kkk{0}, {1}, {2}, {3}", k, Index+1, maxK, val);
        if (maxK > 0) Lazy[--maxK] += val;
        // Console.WriteLine("kkkk{0}, {1}, {2}, {3}", k, Index+1, maxK, Lazy[maxK]);
    }
}

/**
 * Your CustomStack object will be instantiated and called as such:
 * CustomStack obj = new CustomStack(maxSize);
 * obj.Push(x);
 * int param_2 = obj.Pop();
 * obj.Increment(k,val);
 */
 
bài hôm nay là kiến thức phổ thông hay tricky nhỉ, 2 ngày hôm nay chả có tí ý tưởng O(1) nào
tf95Xbz.png
Trick lỏ bác ơi, mấy bài này toàn kiểu greedy trông thế thôi mà khoai vcl @@
Trong mấy cái pattern để giải LC thì ghét nhất là greedy, khó hình dung vc.
 
trick lỏ gì chứ, bài hôm nay dùng line sweep đc dùng trong bài my calendar I, II mới làm cách đây mấy ngày. Ai hôm trước làm đc mà hôm nay là k làm đc là học vẹt hoặc cop sol rồi, :ah:
 
trick lỏ gì chứ, bài hôm nay dùng line sweep đc dùng trong bài my calendar I, II mới làm cách đây mấy ngày. Ai hôm trước làm đc mà hôm nay là k làm đc là học vẹt hoặc cop sol rồi, :ah:
V092S5K.gif
đã từng ăn cơm thêm line sweep của bác phi đâm + học dc skill prefix sum Interval của bác lào show code r mà ko áp dụng dc vào bài này nhục quá
UKiCiKh.png
 
trick lỏ gì chứ, bài hôm nay dùng line sweep đc dùng trong bài my calendar I, II mới làm cách đây mấy ngày. Ai hôm trước làm đc mà hôm nay là k làm đc là học vẹt hoặc cop sol rồi, :ah:
Cái này ko hẳn line sweep đâu bác ơi, nó tricky hơn, implement theo hiểu greedy ấy, ko có pattern cụ thể nào.
 
trick lỏ gì chứ, bài hôm nay dùng line sweep đc dùng trong bài my calendar I, II mới làm cách đây mấy ngày. Ai hôm trước làm đc mà hôm nay là k làm đc là học vẹt hoặc cop sol rồi, :ah:
chôm solution O(1), mà không thấy giống sweep line lắm :sweat:

C-like:
struct CustomStack {
    data: Vec<i32>,
    deltas: Vec<i32>
}

impl CustomStack {
    fn new(maxSize: i32) -> Self {
        Self {
            data: Vec::with_capacity(maxSize as usize),
            deltas: Vec::with_capacity(maxSize as usize)
        }
    }

    fn push(&mut self, x: i32) {
        if self.data.len() == self.data.capacity() {
            return;
        }

        self.data.push(x);
        self.deltas.push(0);
    }

    fn pop(&mut self) -> i32 {
        match self.data.len() {
            0 => -1,
            1 => {
                self.deltas.pop();

                self.data.pop().unwrap()
            },
            _ => {
                let delta = self.deltas.pop().unwrap();
                let top = self.data.pop().unwrap();

                let n = self.data.len();
                self.data[n - 1] += delta;
                self.deltas[n - 1] += delta;

                top
            }
        }
    }

    fn increment(&mut self, k: i32, val: i32) {
        if self.data.is_empty() {
            return;
        }

        let index = (k as usize).min(self.data.len()) - 1;

        self.deltas[index] += val;
        self.data[index] += val;
    }
}
 
chôm solution O(1), mà không thấy giống sweep line lắm :sweat:

C-like:
struct CustomStack {
    data: Vec<i32>,
    deltas: Vec<i32>
}

impl CustomStack {
    fn new(maxSize: i32) -> Self {
        Self {
            data: Vec::with_capacity(maxSize as usize),
            deltas: Vec::new()
        }
    }

    fn push(&mut self, x: i32) {
        if self.data.len() == self.data.capacity() {
            return;
        }

        self.data.push(x);
        self.deltas.push(0);
    }

    fn pop(&mut self) -> i32 {
        match self.data.len() {
            0 => -1,
            1 => {
                self.deltas.pop();

                self.data.pop().unwrap()
            },
            _ => {
                let delta = self.deltas.pop().unwrap();
                let top = self.data.pop().unwrap();

                let n = self.data.len();
                self.data[n - 1] += delta;
                self.deltas[n - 1] += delta;

                top
            }
        }
    }

    fn increment(&mut self, k: i32, val: i32) {
        if self.data.is_empty() {
            return;
        }

        let index = (k as usize).min(self.data.len()) - 1;

        self.deltas[index] += val;
        self.data[index] += val;
    }
}
Cái này ko hẳn line sweep đâu bác ơi, nó tricky hơn, implement theo hiểu greedy ấy, ko có pattern cụ thể nào.
đây trước fen nào đưa đề r giải = prefixsum bài này, ý tưởng giống như v, có thể giải các dạng sweepline nếu như có thể lưu dc hết mốc thay đổi
Xem tệp đính kèm 2671530

các thím cho em hỏi sao code bên phải khi chạy mấy testcase lớn lại bị runtime error ta? cả 2 đều O(m+n) mà nhỉ (m = len queries, n = len array).

em test ở local thì testcase runtime error ở local em chạy okela ra đúng output. submit lên hackerrank thì failed

đề bài đây ạ: array manipulation

Xem tệp đính kèm 2671536
 
đây trước fen nào đưa đề r giải = prefixsum bài này, ý tưởng giống như v, có thể giải các dạng sweepline nếu như có thể lưu dc hết mốc thay đổi
tự nhiên giải thêm được một bài 🤔

C-like:
fn arrayManipulation(n: i32, queries: &[Vec<i32>]) -> i64 {
    let mut freqs = vec![0; n as usize + 1];

    for query in queries.iter() {
        let (a, b, k) = (query[0] as usize - 1, query[1] as usize, query[2] as i64);
        freqs[a] += k;
        freqs[b] -= k;
    }

    freqs.into_iter().fold((0, 0), |(max, current), freq| {
        (max.max(current + freq), current + freq)
    }).0
}
 
chôm solution O(1), mà không thấy giống sweep line lắm :sweat:

C-like:
struct CustomStack {
    data: Vec<i32>,
    deltas: Vec<i32>
}

impl CustomStack {
    fn new(maxSize: i32) -> Self {
        Self {
            data: Vec::with_capacity(maxSize as usize),
            deltas: Vec::with_capacity(maxSize as usize)
        }
    }

    fn push(&mut self, x: i32) {
        if self.data.len() == self.data.capacity() {
            return;
        }

        self.data.push(x);
        self.deltas.push(0);
    }

    fn pop(&mut self) -> i32 {
        match self.data.len() {
            0 => -1,
            1 => {
                self.deltas.pop();

                self.data.pop().unwrap()
            },
            _ => {
                let delta = self.deltas.pop().unwrap();
                let top = self.data.pop().unwrap();

                let n = self.data.len();
                self.data[n - 1] += delta;
                self.deltas[n - 1] += delta;

                top
            }
        }
    }

    fn increment(&mut self, k: i32, val: i32) {
        if self.data.is_empty() {
            return;
        }

        let index = (k as usize).min(self.data.len()) - 1;

        self.deltas[index] += val;
        self.data[index] += val;
    }
}
Idea nó khá giống nhé, dựa vào việc lưu cái mảng delta, cộng ngược về mỗi khi pop giống kiểu suffixSum thay vì prefixSum.
 
Python:
class Solution:
    def canArrange(self, arr: List[int], k: int) -> bool:
        counter = defaultdict(int)
        for num in arr:
            counter[num % k] += 1
        if counter[0] % 2 != 0:
            return False

        for i in range(1, k):
            if counter[i] != counter[k - i]:
                return False
        return True
 
Python:
class Solution:
    def canArrange(self, arr: List[int], k: int) -> bool:
        count = defaultdict(int)
        for num in arr:
            current = num%k
            if current == 0:
                count[current] += 1
                continue

            target = k - current
            if target in count:
                count[target] -= 1
                if count[target] == 0:
                    count.pop(target)
            else:
                count[current] += 1

        return len(count) == 0 or (len(count) == 1 and count[0] > 0 and count[0]%2 == 0)
 
C++:
class Solution {
public:
    bool canArrange(vector<int>& arr, int k) {
        unordered_map<int, int> cnt;

        for (int i = 0; i < arr.size(); i++) {
            cnt[(arr[i] % k + k) % k]++;
        }

        for (int i = 1; i < k; i++) {
            if (cnt[0] % 2 == 1) return false;
            if(cnt[i] != cnt[k - i]) return false;
        }
        
        return true;
    }
};
 
C#:
public class Solution {
    public bool CanArrange(int[] arr, int k) {
        int[] freq = new int[k];
        int n = arr.Length;
        for (int i = 0; i < n; i++){
            freq[(arr[i]%k + k)%k]++;
        }

        bool flag = freq[0] % 2 == 0;
        for (int i = 1; i < k && flag == true; i++) {
            // Console.WriteLine("{0}, {1}, {2}, {3}", freq[i], freq[k-i], i, k - i);
            flag = flag && (freq[i] == freq[k-i]);
        }
        return flag;
    }
}
 
quên ko để ý có số âm, submit fail 1 lần :ops:
Đếm số i và k-i
JavaScript:
function canArrange(arr: number[], k: number): boolean {
    const map = new Map();
    for (const num of arr) {
        const key = ((num % k) + k) % k
        map.set(key, (map.get(key) || 0) + 1);
    }
    for (const key of map.keys()) {
        if (key === 0) {if (map.get(key) & 1) return false;}
        else if (map.get(key) !== map.get(k - key)) return false;
    }
    return true;
};
 
Python:
class Solution:
    def canArrange(self, arr: List[int], k: int) -> bool:
        for i in range(len(arr)):
            arr[i] = arr[i] % k
        arr.sort()
        left = 0
        right = len(arr) - 1
        while left < len(arr) and  arr[left] == 0:
            left += 1
        if left % 2 != 0:
            return False
        while left < right:
            if arr[left] + arr[right] != k:
                return False
            left += 1
            right -= 1
        return True

Mã:
class Solution:
    def canArrange(self, arr: List[int], k: int) -> bool:
        counting = defaultdict(int)
        for i in range(len(arr)):
            counting[arr[i] % k] += 1
        if counting[0] % 2 != 0:
            return False
        for i in range(1, k // 2 + 1):
            if counting[i] != counting[k-i]:
                return False
        return True
 
Sửa lần cuối:
Java:
class Solution {
    public boolean canArrange(int[] arr, int k) {
        int[] freq = new int[k];
        for(int i:arr){
            freq[((i%k)+k)%k]++;
        }
 
        for(int i =1 ; i<(double)k/2;i++){

            if(freq[i]!= freq[k-i]) return false;
        }
        if(k%2==0){
            return freq[k/2]%2==0;
        }
        return true;
    }
}
 
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.215.669
Quay lại
Lên đầu trang