考道前端 iOS 算法题( Easy)

2016-11-27 14:02:39 +08:00
 nagato

给你两个 UIView 或者其子类的对象 viewAviewB.

如果它们同属一个父view的话, 请找到并返回这个父 view, 否则请返回nil.

- (UIView *) findCommonSuperViewBetween: (UIView *)viewA
                                    and: (UIView *)viewB 
{

}

大家先写,一会儿贴下我写的答案。

2565 次点击
所在节点    问与答
21 条回复
xieguobihaha
2016-11-27 17:15:32 +08:00
我的思路是将 viewA 和 viewB 的所有父 view 分别放入两个数组,数组数量少的那个说明位于视图上层,取它的第一个父视图即可,代码如下
https://gist.github.com/hiXgb/6cf33f97fa2439a44d23be3e4691b16e
starqoq
2016-11-27 17:29:19 +08:00
求 lca ?
xieguobihaha
2016-11-27 17:30:18 +08:00
nagato
2016-11-27 17:31:17 +08:00
@starqoq 哈哈哈,比 LCA 还要简单好多
nagato
2016-11-27 17:35:49 +08:00
@xieguobihaha 说实话有点惨不忍睹,面试应该是挂的
xieguobihaha
2016-11-27 17:39:43 +08:00
@nagato 求指教
kimown
2016-11-27 17:41:30 +08:00
题目真没看懂, uiview ,这是前端?
xieguobihaha
2016-11-27 17:51:47 +08:00
@nagato 我自己发现一个错误了, while 循环里最后跳出条件得改一下,不然死循环了。
nagato
2016-11-27 17:57:52 +08:00
@xieguobihaha
且不说你做的是不是正确。单从你的代码就能看出你的编码能力还挺一般的😂. 比如你想把所有的 superview 全加数组里,为啥可以写出这么多代码和变量,不是两个 while loop 就好了吗
不过我挺喜欢你的态度👍
nagato
2016-11-27 18:00:30 +08:00
@kimown iOS

其实换个讲法。 给 classA, classB ,求 lowest common super class , 应该对哪个语言都适用
wy315700
2016-11-27 18:04:47 +08:00
@nagato 其实就是 求两个单链表是否相交的问题吧。。。。
binux
2016-11-27 18:06:45 +08:00
多重继承怎么办
nagato
2016-11-27 18:07:12 +08:00
@wy315700 哈哈对的,想到这个就差不多了
nagato
2016-11-27 18:09:37 +08:00
@binux 你厉害
fengyunSmlie
2016-11-27 18:14:51 +08:00
菜鸟前来膜拜大佬
a412739861
2016-11-27 18:14:52 +08:00
贴个现成的吧。源代码在 Masonry 中,查看 View+MASAdditions.h/m 文件即可。

这是个实例方法,类方法也一样;只是 self 变成 view1 罢了。

遍历 self 的 superview ,去匹配 view 。
然后取 view 得 superview ,再遍历一遍 self 的 superview 。循环不到,也就返回 nil 了。
记得回复不能 markdown 的样子,就直接复制下代码,不会太好看。

- (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;
}
xieguobihaha
2016-11-27 18:38:50 +08:00
@nagato ![]( ) 我用你的方法代入上面那张图貌似有问题,假设 A 是 2 , B 是 9 ,你试一下。
nagato
2016-11-27 18:44:47 +08:00
@xieguobihaha 你再仔细看看
binux
2016-11-27 18:55:10 +08:00
@nagato 假如 A 是 3 , B 是 6
itqls
2016-11-27 22:39:11 +08:00
@binux hhh 打脸~

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/323610

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX