门户网站是网络表达吗,代理平台注册网站建设,深圳网站设计建设,营销型网站的设计与建设题目 求两个视图的最近公共父视图 暴力解法
采用的是两个 while 循环嵌套迭代来查询最近的公共父视图, 时间复杂度 O(n), 详见 Masonry 的实现#xff1a;
- (instancetype)mas_closestCommonSuperview:(MAS_VIEW *)view {MAS_VIEW *closestCommonSuperview nil;MAS_VIEW *…题目 求两个视图的最近公共父视图 暴力解法
采用的是两个 while 循环嵌套迭代来查询最近的公共父视图, 时间复杂度 O(n²), 详见 Masonry 的实现
- (instancetype)mas_closestCommonSuperview:(MAS_VIEW *)view {MAS_VIEW *closestCommonSuperview nil;MAS_VIEW *secondViewSuperview view;while (!closestCommonSuperview secondViewSuperview) {MAS_VIEW *firstViewSuperview self;while (!closestCommonSuperview firstViewSuperview) {if (secondViewSuperview firstViewSuperview) {closestCommonSuperview secondViewSuperview;}firstViewSuperview firstViewSuperview.superview;}secondViewSuperview secondViewSuperview.superview;}return closestCommonSuperview;
}空间换时间的优化解法
- (UIView *)sqi_closestCommonSuperView:(UIView *)view {UIView *closestCommonSuperview nil;// 用于存放fooView的所有父视图NSMutableSet *cacheViews [NSMutableSet set];UIView *fooViewSuperview view;while (fooViewSuperview) {[cacheViews addObject:fooViewSuperview];fooViewSuperview fooViewSuperview.superview;}UIView *barViewSuperview self;while (!closestCommonSuperview barViewSuperview) {// containsObject方法的时间复杂度为1if ([cacheViews containsObject:barViewSuperview]) {closestCommonSuperview barViewSuperview;}barViewSuperview barViewSuperview.superview;}return closestCommonSuperview;
}