当前位置:网站首页>LeetCode 497(C#)

LeetCode 497(C#)

2022-07-07 19:04:00 Just be interesting

List of articles

subject

Given an array of rectangles aligned by non overlapping axes rects , among rects[i] = [ai, bi, xi, yi] Express (ai, bi) It's No i Bottom left corner of rectangle ,(xi, yi) It's No i The upper right corner of a rectangle . Design an algorithm to randomly select an integer point covered by a rectangle . Points on the perimeter of a rectangle are also considered to be covered by the rectangle . All points that meet the requirements must be returned with equal probability .

Any integer point in the space covered by a given rectangle can be returned .

Please note that , An integer point is a point with integer coordinates .

Realization Solution class :

Solution(int[][] rects) With the given rectangular array rects Initialize object .
int[] pick() Returns a random integer point [u, v] In the space covered by a given rectangle .

Example 1:
Input :
[“Solution”, “pick”, “pick”, “pick”, “pick”, “pick”]
[[[[-2, -2, 1, 1], [2, 2, 4, 6]]], [], [], [], [], []]
Output :
[null, [1, -2], [1, -1], [-1, -2], [-2, -2], [0, 0]]

explain :
Solution solution = new Solution([[-2, -2, 1, 1], [2, 2, 4, 6]]);
solution.pick(); // return [1, -2]
solution.pick(); // return [1, -1]
solution.pick(); // return [-1, -2]
solution.pick(); // return [-2, -2]
solution.pick(); // return [0, 0]

Code

Two points + The prefix and

public class Solution 
{
    
    Random _random;
    int[] _sum;
    int[][] _rects;

    public Solution(int[][] rects)
    {
    
        _rects = rects;
        
        _sum = new int[rects.Length + 1];
        for (int i = 1; i <= rects.Length; i++)
            _sum[i] = _sum[i - 1] + (rects[i - 1][2] - rects[i - 1][0] + 1) * (rects[i - 1][3] - rects[i - 1][1] + 1);

        _random = new Random();
    }
    
    public int[] Pick() 
    {
    
        int k = _random.Next(_sum[_sum.Length - 1]);
        int index = BinarySearch(k + 1) - 1;
        k -= _sum[index];
        int[] cnt = _rects[index];
        int col = cnt[3] - cnt[1] + 1;
        return new int[]{
    cnt[0] + k / col, cnt[1] + k % col};
    }

    private int BinarySearch(int k)
    {
    
        var (low, high) = (0, _sum.Length - 1);

        while (low < high)
        {
    
            int mid = low + (high - low) / 2;
            if (_sum[mid] >= k) high = mid;
            else low = mid + 1;
        }

        return high;
    }
}
原网站

版权声明
本文为[Just be interesting]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071515234055.html