[LeetCode] 1828. Queries on Number of Points Inside a Circle

You are given an array points where points[i] = [xi, yi] is the coordinates of the ith point on a 2D plane. Multiple points can have the same coordinates.

You are also given an array queries where queries[j] = [xj, yj, rj] describes a circle centered at (xj, yj) with a radius of rj.

For each query queries[j], compute the number of points inside the jth circle. Points on the border of the circle are considered inside.

Return an array answer, where answer[j] is the answer to the jth query.

Example 1:

Input: points = [[1,3],[3,3],[5,3],[2,2]], queries = [[2,3,1],[4,3,1],[1,1,2]]
Output: [3,2,2]
Explanation: The points and circles are shown above.
queries[0] is the green circle, queries[1] is the red circle, and queries[2] is the blue circle.

Example 2:

Input: points = [[1,1],[2,2],[3,3],[4,4],[5,5]], queries = [[1,2,2],[2,2,2],[4,3,2],[4,3,3]]
Output: [2,3,2,4]
Explanation: The points and circles are shown above.
queries[0] is green, queries[1] is red, queries[2] is blue, and queries[3] is purple.

Constraints:

  • 1 <= points.length <= 500
  • points[i].length == 2
  • 0 <= x​​​​​​i, y​​​​​​i <= 500
  • 1 <= queries.length <= 500
  • queries[j].length == 3
  • 0 <= xj, yj <= 500
  • 1 <= rj <= 500
  • All coordinates are integers.

Follow up: Could you find the answer for each query in better complexity than O(n)?

统计一个圆中点的数目。

给你一个数组 points ,其中 points[i] = [xi, yi] ,表示第 i 个点在二维平面上的坐标。多个点可能会有 相同 的坐标。

同时给你一个数组 queries ,其中 queries[j] = [xj, yj, rj] ,表示一个圆心在 (xj, yj) 且半径为 rj 的圆。

对于每一个查询 queries[j] ,计算在第 j 个圆 内 点的数目。如果一个点在圆的 边界上 ,我们同样认为它在圆 内 。

请你返回一个数组 answer ,其中 answer[j]是第 j 个查询的答案。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/queries-on-number-of-points-inside-a-circle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这是一道数学题,这里我提供一个暴力的思路。

题目给了每个圆心的坐标和半径,那么判断一个坐标是否在某个圆里面,我们就判断这个坐标到圆心的距离是否 <= 这个圆的半径即可。

时间O(mn)

空间O(n) - output array

Java实现

 1 class Solution {
 2     public int[] countPoints(int[][] points, int[][] queries) {
 3         int n = queries.length;
 4         int[] res = new int[n];
 5         for (int i = 0; i < n; i++) {
 6             int x = queries[i][0];
 7             int y = queries[i][1];
 8             int r = queries[i][2] * queries[i][2];
 9             for (int[] p : points) {
10                 res[i] += (p[0] - x) * (p[0] - x) + (p[1] - y) * (p[1] - y) <= r ? 1 : 0;
11             }
12         }
13         return res;
14     }
15 }

 

LeetCode 题目总结

posted @ 2023-01-24 02:36  CNoodle  阅读(43)  评论(0编辑  收藏  举报