一、题目描述
定义:二维平面中,如果某个点的右上方没有其他点,则定义该点为[完美点],找出所有的完美点。
二、代码实现
(1)最简单显然是暴力枚举,两层for循环,
points = [[4, 0], [0, 4], [2, 2]]
def func(points):
ans = []
n = len(points)
# 1. 遍历每个节点
for i in range(n):
tag = True
# 2. 判断当前节点是否满足条件(和所有其他节点比较横纵坐标)
for j in range(n):
# 3. 如果不满足则跳过当前节点
if points[i][0] < points[j][0] and points[i][1] < points[j][1]:
tag = False
break
# 4. 当前节点和其他所有节点比较完毕
if tag == True:
ans.append(points[i])
return ans
ans = func(points)
ans
# [[4, 0], [0, 4], [2, 2]]
(2)不用两层for,可以先对x横坐标进行节点排序,然后从右到左遍历所有节点,用max_y
记录当前的最大y坐标,只要遍历到的节点y坐标比这个max_y
大,就满足题意;从n方的时间复杂度降低为nlogn(因为一开始sorted
了,不是n)。
points = [[4, 0], [0, 4], [2, 2]]
def func(points):
ans = []
n = len(points)
max_y = float('-inf')
# 1. 先对所有节点按照x坐标从小到大排序
sorted_points = sorted(points, key = lambda x: x[0])
# 2. 从右到左所有节点
for i in range(n-1, -1, -1):
# 3. 如果当前节点的y坐标是截至当前最大的,则符合题意
if sorted_points[i][1] > max_y:
ans.append(sorted_points[i])
# 4. 更新max_y
max_y = sorted_points[i][1]
return ans
ans_points = func(points)
ans_points
# [[4, 0], [2, 2], [0, 4]]