加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – TripAdvisor访谈有没有比我给出的算法更好的算法?

发布时间:2020-12-15 08:47:49 所属栏目:Java 来源:网络整理
导读:刚接到TripAdvisor的电话采访(并没有削减). 我得到了下面的代码,并要求实现findBestTravelAlert(在Java中). 给定TravelAlert对象列表,找到要显示特定位置的最佳旅行警报.见http://www.tripadvisor.com/Tourism-g147306-Haiti-Vacations.html的例子 class Tra
刚接到TripAdvisor的电话采访(并没有削减).

我得到了下面的代码,并要求实现findBestTravelAlert(在Java中).

给定TravelAlert对象列表,找到要显示特定位置的最佳旅行警报.见http://www.tripadvisor.com/Tourism-g147306-Haiti-Vacations.html的例子

class TravelAlert {
      int id;
      String message;
      int locationId;
 }

 class Location {
      int locationId;
      int parentLocationId; // -1 if no parent,location is hierarchy
      String name;

      static Location findLocation(int locationId) {...}
 }

 class TravelAlertStore {
      private List<TravelAlert> lAlerts; // already populated,static

      // Return null if no alert
      TravelAlert findBestTravelAlert(int locationId) {
      // implement this
      }
  }

示例:如果我们有3个旅行提醒,一个在波士顿,一个在马萨诸塞,一个在美国:

>查看波士顿特定页面的用户应该看到波士顿的旅行警报而不是马萨诸塞州的旅行警报
>查看马萨诸塞州页面的用户应该会看到旅行提醒
马萨诸塞
>查看牛顿特定页面的用户应该看到
马萨诸塞州的旅行警报
>查看NYC特定页面的用户
应该看看美国旅行警报
>查看蒙特利尔特定用户的用户
页面应该看不到旅行警报.

我这样做的方式相当天真,但这是我在压力下想出的一切:
搜索TravelAlerts列表,查看locationId是否与locationId匹配.如果没有,请重复搜索并检查与父项的locationId的匹配项.如果在此过程中的任何时候我们找到匹配项,则返回TravelAlert.如果我们到达进程的末尾(即没有父位置),则返回null.

这是代码:

TravelAlert findBestTravelAlert(int locationId) {
    TravelAlert current_alert = searchList(locationId,lAlerts);
    if(current_alert != null) {
        return current_alert;
    }
    else {
        int parentLocationId = findLocation(locationId).parentLocationId;
        if(parent_locId == -1)
            return null;
        else {
            return findBestTravelAlert(parentLocationId);
        }
    }
}
TravelAlert searchList(int locationId,List<TravelAlert> cur_list) {
    if(cur_list == null) {
        return null;
    }
    else if(cur_list.locationId == locationId) {
        return cur_list;
    }
    else {
        searchList(locationId,cur_list.next())
    }
}

时间复杂度为O(nk),其中n是TravelAlerts列表的长度,k是位置层次树的高度.

所以,我的问题是:

  • Is there a better algorithm for doing this,and
  • Is there a better way of implementing my algorithm?

我确定第二个问题的答案是肯定的;必须有我可以使用的内置方法,我是否更熟悉Java.

任何帮助,将不胜感激.祝所有未来的申请人好运!

解决方法

1)您的searchList()方法不起作用(甚至编译). List上没有locationId字段,当您尝试进行递归调用时,您尝试将列表中的元素传递到第二个参数,其中列表是预期的.

2)您没有遵循Sun事实上的标准编码约定或示例的编码约定.

3)通常,递归的效率低于循环(因为你必须保留大量的堆栈帧而不是单个指针/索引到数组中) – 并且因为你的两个递归函数都是尾递归的,所以它们都可以被循环取代.

如果没有建立更好的数据结构(例如,旅行警报的位置ID地图),或者知道旅行警报列表已经排序(您可能已经获得了一些信用),您可以节省一些时间计算位置ID列表(即从树的位置到顶部的链)然后走一次旅行警报列表(假设它比位置树的深度大得多)并将每个警报与列表进行比较位置ID确定最佳匹配.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读