Input: points =[[6,2],[4,4],[2,6]]Output: 2Explanation:
* The left one is the pair `(points[1], points[0])`, where `points[1]`is on the upper left side of `points[0]` and the rectangle is empty.* The middle one is the pair `(points[2], points[1])`, same as the left one it is a valid pair.* The right one is the pair `(points[2], points[0])`, where `points[2]`is on the upper left side of `points[0]`, but `points[1]`is inside the rectangle so it's not a valid pair.
Input: points =[[3,1],[1,3],[1,1]]Output: 2Explanation:
* The left one is the pair `(points[2], points[0])`, where `points[2]`is on the upper left side of `points[0]` and there are no other points on the line they form. Note that it is a valid state when the two points form a line.* The middle one is the pair `(points[1], points[2])`, it is a valid pair same as the left one.* The right one is the pair `(points[1], points[0])`, it is not a valid pair as `points[2]`is on the border of the rectangle.
We want to count pairs (A, B) such that A is strictly upper-left of B and there are no other points inside or on the rectangle defined by A and B. By sorting points and using a 2D Fenwick Tree, we can efficiently count the number of valid pairs by processing points in order and querying for emptiness.
classSolution {
funnumberOfPairs(points: Array<IntArray>): Int {
val n = points.size
points.sortWith(compareBy({ it[0] }, { -it[1] }))
var ans = 0for (i in0 until n) {
val first = points[i]
for (j in i + 1 until n) {
val second = points[j]
if (first[0] > second[0] || first[1] < second[1]) continuevar valid = truefor (k in i + 1 until j) {
val third = points[k]
if (first[0] <= third[0] && third[0] <= second[0] && first[1] >= third[1] && third[1] >= second[1]) {
valid = falsebreak }
}
if (valid) ans++ }
}
return ans
}
}
classSolution:
defnumberOfPairs(self, points: list[list[int]]) -> int:
n = len(points)
points.sort(key=lambda x: (x[0], -x[1]))
ans =0for i in range(n):
first = points[i]
for j in range(i+1, n):
second = points[j]
if first[0] > second[0] or first[1] < second[1]:
continue valid =Truefor k in range(i+1, j):
third = points[k]
if first[0] <= third[0] <= second[0] and first[1] >= third[1] >= second[1]:
valid =Falsebreakif valid:
ans +=1return ans
impl Solution {
pubfnnumber_of_pairs(points: Vec<Vec<i32>>) -> i32 {
letmut pts = points;
pts.sort_by(|a, b|if a[0] != b[0] { a[0].cmp(&b[0]) } else { b[1].cmp(&a[1]) });
let n = pts.len();
letmut ans =0;
for i in0..n {
let first =&pts[i];
for j in (i+1)..n {
let second =&pts[j];
if first[0] > second[0] || first[1] < second[1] { continue; }
letmut valid =true;
for k in (i+1)..j {
let third =&pts[k];
if first[0] <= third[0] && third[0] <= second[0] && first[1] >= third[1] && third[1] >= second[1] {
valid =false;
break;
}
}
if valid { ans +=1; }
}
}
ans
}
}