一道面试题,帮忙看看

migo2008 2008-06-06 08:27:02
算法一:

for(int i=0;i<N;i++){
if(condition){
dosomething;
}
else{
doanything;
}
}


算法二:


if(condition){
for(int i=0;i<N;i++){
dosomething;
}
}
else{
for(int i=0;i<N;i++){
doanything;
}
}


=================================
比较这两个算法的优缺点并加以说明
...全文
181 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
lhy011 2008-06-16
  • 打赏
  • 举报
回复
算法一: for(int i=0;i<N;i++){
if(condition){
dosomething;
}
else{
doanything;
}
}
算法2
if(condition){
for(int i=0;i<N;i++){
dosomething;
}
}
else{
for(int i=0;i<N;i++){
doanything;
}
}
我来晚了
如果condition不变,两者算法复杂度一样。
不过不应该仅仅在算法效率上比较,最重要的是算法1和算法2有可能得到的是根本不同的两个结果,出现这中情况的条件是。
在方法2中,dosomething会改变condition。
林g 2008-06-06
  • 打赏
  • 举报
回复
第二种好,效率会快点
smartapp 2008-06-06
  • 打赏
  • 举报
回复
if condition is not changed by dosomething and doanything. the second one is best.
otherwise,both are different result.
wareza 2008-06-06
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 lastsweetop 的回复:]
从效率上讲第二种好于第一种,因为不用循环判断

但是从功能上,如果condition是根据dosomething和doanything变化的
就只能用第一种了
[/Quote]

如果condition是根据i变化的也只能用第一种了
zapdos 2008-06-06
  • 打赏
  • 举报
回复
差不多吧,不是效率瓶颈,我觉得都没所谓
jayflee 2008-06-06
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 lastsweetop 的回复:]
从效率上讲第二种好于第一种,因为不用循环判断

但是从功能上,如果condition是根据dosomething和doanything变化的
就只能用第一种了
[/Quote]

因为第二种只需执行一次if-else,而第一种需执行N次if-else

for语句执行情况都是一样的。
南南北北 2008-06-06
  • 打赏
  • 举报
回复
第一种好,循环一次。
wangse11 2008-06-06
  • 打赏
  • 举报
回复
第二种效率高,第二种先先判断后循环,而第一种是先循环后判断
吴冬冬 2008-06-06
  • 打赏
  • 举报
回复
从效率上讲第二种好于第一种,因为不用循环判断

但是从功能上,如果condition是根据dosomething和doanything变化的
就只能用第一种了
ayudongming 2008-06-06
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 smartapp 的回复:]
if condition is not changed by dosomething and doanything. the second one is best.
otherwise,both are different result.
[/Quote]

I Think So!!1
happy002 2008-06-06
  • 打赏
  • 举报
回复
根华为的面试题真像~
SantaRosa 2008-06-06
  • 打赏
  • 举报
回复
关键是看看condition有没有变化啊,如果condition没有变化,肯定是第二种.如果condition有变化,那么第二种方法根本就不对啊.

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧