Skip to content

[Containers::CRBTreeMap] GC bug happened in Leetcode 3321 #62

@xerox51

Description

@xerox51

Line 40: [BUG] object allocation during garbage collection phase in solution.rb
ruby 3.2.2 (2023-03-30 revision e51014f9c0) [x86_64-linux]

def find_x_sum(nums, k, x)
  cnt = Hash.new(0)
  
  # 自定义比较器
  comparator = Proc.new { |a, b|
    # a和b都是[freq, val]数组
    # 先比较频率,再比较值
    if a[0] != b[0]
      a[0] <=> b[0]
    else
      a[1] <=> b[1]
    end
  }
  
  l_tree = Containers::CRBTreeMap.new(&comparator)
  r_tree = Containers::CRBTreeMap.new(&comparator)
  sum_l = 0
  
  # 添加元素
  add = lambda do |val|
    c = cnt[val]
    return if c == 0
    
    p = [c, val]
    
    # 如果L不为空且p比L中最小的元素大
    if !l_tree.empty? && comparator.call(p, l_tree.min[0]) > 0
      sum_l += p[0] * p[1]
      l_tree[p] = true
    else
      r_tree[p] = true
    end
  end
  
  # 删除元素
  del = lambda do |val|
    c = cnt[val]
    return if c == 0
    
    p = [c, val]
    if l_tree.has_key?(p)
      sum_l -= p[0] * p[1]
      l_tree.delete(p)
    else
      r_tree.delete(p)
    end
  end
  
  # 从L移动最小元素到R
  l2r = lambda do
    return if l_tree.empty?
    
    min_key = l_tree.min[0]
    sum_l -= min_key[0] * min_key[1]
    l_tree.delete(min_key)
    r_tree[min_key] = true
  end
  
  # 从R移动最大元素到L
  r2l = lambda do
    return if r_tree.empty?
    
    max_key = r_tree.max[0]
    sum_l += max_key[0] * max_key[1]
    r_tree.delete(max_key)
    l_tree[max_key] = true
  end
  
  ans = Array.new([0, nums.length - k + 1].max, 0)
  
  nums.each_with_index do |in_val, r|
    # 移除旧计数,添加新计数
    del.call(in_val)
    cnt[in_val] += 1
    add.call(in_val)
    
    l_index = r + 1 - k
    next if l_index < 0
    
    # 维护L的大小为x
    while !r_tree.empty? && l_tree.size < x
      r2l.call
    end
    while l_tree.size > x
      l2r.call
    end
    
    ans[l_index] = sum_l
    
    # 移除窗口最左边的元素
    out_val = nums[l_index]
    del.call(out_val)
    cnt[out_val] -= 1
    add.call(out_val)
  end
  
  ans
end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions