Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Random Point in Non-overlapping Rectangles

Posted on August 5, 2019July 26, 2020 by braindenny

Random Point in Non-overlapping Rectangles



Similar Problems:

  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #binarysearch

Given an integer array of size n, find all elements that appear more than n/3 times. The algorithm should run in linear time and in O(1) space.

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


  • Solution:
// https://code.dennyzhang.com/random-point-in-non-overlapping-rectangles
// Basic Ideas: dynamic programming
//
// Complexity: Time O(log(n)), Space O(n)
import "math/rand"

type Solution struct {
    rects [][]int
    nums []int
}

func Constructor(rects [][]int) Solution {
    nums := make([]int, len(rects))
    sum := 0
    for i, rect := range rects {
        sum += (rect[2]-rect[0]+1)*(rect[3]-rect[1]+1)
        nums[i] = sum
    }
    return Solution{rects:rects, nums:nums}
}

func (this *Solution) Pick() []int {
    total := this.nums[len(this.nums)-1]
    num := rand.Intn(total)
    // search insert position
    // 100, 10, 20, 8, 20
    left, right := 0, len(this.nums)-1
    for left<right {
        mid := (right-left)/2+left
        if this.nums[mid] <= num {
            // right half
            left = mid+1
        } else {
            right = mid
        }
    }
    // left
    x, y := this.rects[left][0], this.rects[left][1]
    width := this.rects[left][2]-this.rects[left][0]+1
    height := this.rects[left][3]-this.rects[left][1]+1

    offset := num-(this.nums[left]-width*height)
    x += offset%width
    y += offset/width
    return []int{x, y}
}

/**
 * Your Solution object will be instantiated and called as such:
 * obj := Constructor(rects);
 * param_1 := obj.Pick();
 */
linkedin
github
slack

Post Views: 0
Posted in MediumTagged #manydetails, binarysearch, redo

Post navigation

Series: Sorted 2D Matrix Problems & Follow-up
LeetCode: Best Time to Buy and Sell Stock with Cooldown

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.