My Ruby solution using corners


  • 0
    T
    def is_rectangle_cover(rectangles)
        @min_x = @min_y = @max_x = @max_y = nil
        area = 0
        points = {}
        sets = [[0,1],[0,3],[2,1],[2,3]]
        rectangles.each do |rect|
            area += ((rect[3] - rect[1]) * (rect[2] - rect[0]))
            sets.each do |set|
                key = to_key(rect[set[0]], rect[set[1]])
                set_min_max(rect[set[0]], rect[set[1]])
                points[key] ||= 0
                points[key] += 1
            end
        end
        corners = [[@min_x, @min_y], [@min_x, @max_y], [@max_x, @min_y], [@max_x, @max_y]]
        corners.each do |pt|
            key = to_key(pt[0], pt[1])
            points[key] ||= 0
            points[key] += 1
        end
        points.each do |key, value|
            points.delete(key) if value%2 == 0
        end
        total_area = (@max_y - @min_y) * (@max_x - @min_x)
        return points.size == 0 && total_area == area
    end
    
    def set_min_max(i,j)
        @min_x ||= i
        @min_x = [@min_x, i].min
        @min_y ||= j
        @min_y = [@min_y, j].min
        @max_x ||= i
        @max_x = [@max_x, i].max
        @max_y ||= j
        @max_y = [@max_y, j].max
    end
    
    def to_key(i,j)
        return "#{i}-#{j}"
    end
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.