📣 黑五网一特惠|VIP一年通行证5折,蓝莓、Offer多多同步特惠
楼主: cc11328
跳转到指定楼层
上一主题 下一主题
收起左侧

11.23 Google onsite

🔗
bobzhang2004 2016-3-30 05:49:55 | 只看该作者
全局:
returning 发表于 2015-11-30 02:15
第一题可以bst吧,bst按照这个节点的位置排序,先从高到低sort,然后根据f(x)插入,f(x)表示x前面有多少 ...

用list直接插入时间复杂度是O(n^2)吧,如果用balanced bst确实是O(nlgn)
回复

使用道具 举报

🔗
bobzhang2004 2016-3-30 05:57:41 | 只看该作者
全局:
returning 发表于 2015-11-30 02:15
第一题可以bst吧,bst按照这个节点的位置排序,先从高到低sort,然后根据f(x)插入,f(x)表示x前面有多少 ...

我以前看到讨论说是用list就行,不过我觉得用list的话,时间复杂度还是O(n^2)啊
  1. public class HeightSort {

  2.         private static class Person {
  3.                 String name;
  4.                 int height;
  5.                 int tallCount;

  6.                 Person(int h, int t, String n) {
  7.                         name = n;
  8.                         height = h;
  9.                         tallCount = t;
  10.                 }

  11.                 @Override
  12.                 public String toString() {
  13.                         return "<" + name + "," + height + "," + tallCount + ">";
  14.                 }
  15.         }

  16.         static class HeightComparator implements Comparator<Person> {
  17.                 public int compare(Person p1, Person p2) {
  18.                         int ret = p2.height - p1.height;
  19.                         return (ret == 0) ? p2.tallCount - p1.tallCount : ret;
  20.                 }
  21.         }

  22.         public static List<Person> orderByHeightAndTaller(Person[] people) {
  23.                 Arrays.sort(people, new HeightComparator());
  24.                 LinkedList<Person> ret = new LinkedList<>();
  25.                 for (Person p : people) {
  26.                         ret.add(p.tallCount, p);
  27.                 }
  28.                 return ret;
  29.         }

  30.         public static void main(String[] args) {
  31.                 Person[] people = { new Person(6, 2, "A"), new Person(1, 4, "B"),
  32.                                 new Person(11, 0, "C"), new Person(5, 1, "D"),
  33.                                 new Person(5, 3, "K"), new Person(10, 0, "E"),
  34.                                 new Person(4, 0, "F")

  35.                 };
  36.                 System.out.println(orderByHeightAndTaller(people));

  37.         }
  38. }
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表