查看: 2194| 回复: 5
跳转到指定楼层
上一主题 下一主题
收起左侧

[CareerCup] 【第四轮】6.28 - 7.4 Career Cup 4.3

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
4.3 Given a sorted (increasingorder) array with unique integer elements, write analgorithm to create a binary search tree with minimal height.

请参加活动的童鞋跟帖回复自己的解法,回复请参考以下格式:


【解题思路】
【时间复杂度】
【空间复杂度】
【gist link】
【test case】(optional,如果觉得比较好,欢迎贴出来分享)

Notice:
1、记得在程序注释中表明自己算法的时间、空间复杂度
2、代码难懂之处加注释
3、每道题目有对应的帖子,除了贴解法,欢迎探讨各种follow up questions,集思广益
4、任何未尽之处,欢迎回报名帖提问,我会进一步作出修改


上一篇:Skyline Problem的Priority Queue重写Comparator的疑问
下一篇:textbox similarity
全局:
本帖最后由 @南岸的风 于 2015-7-1 06:48 编辑

【解题思路】
  Use binary search, divide and conquer, and recursion to create a balance tree,which has the min height.
【时间复杂度】
  each element is visited once, so time complexity is O(n)
【空间复杂度】
O(n) space for the tree, and O(log(n)) stack space for the recursion
【gist link】
https://gist.github.com/zhongyn/718996e13de82d5f44ff
class Node {
  int val;
  Node left = null;
  Node right = null;
  public Node(int v) {
    val = v;
  }
}

class Solution {
  public Node createBST(int[] a) {
    return subTree(a, 0, a.length - 1);
  }

  public Node subTree(int[] a, int start, int end) {
    if (start > end) {
      return null;
    }
    int m = (start + end) / 2;
    Node p = new Node(a[m]);
    p.left = subTree(a, start, m - 1);
    p.right = subTree(a, m + 1, end);
    return p;
  }
}



回复

使用道具 举报

🔗
iFighting 2015-7-1 09:36:18 | 只看该作者
全局:
【解题思路】递归分治建树
【时间复杂度】
每个节点访问一次所以是O(N)
【空间复杂度】
O(N)存储二叉树,递归空间O(logN)
【gist link】

https://gist.github.com/iFighting/742fab34d4f8d4d6bc0a

回复

使用道具 举报

🔗
水逼一枚 2015-7-5 04:36:28 | 只看该作者
全局:
【解题思路】divide & conquer
【时间复杂度】O(n)
【空间复杂度】递归深度O(logn)消耗system stack + 结果O(n)
【gist link】
https://gist.github.com/zhangxin0804/23a3bf44ad4526102d3e
回复

使用道具 举报

地里匿名用户
🔗
匿名用户-878YE  2015-7-7 03:23:05
【解题思路】
递归构造二叉平衡树
【时间复杂度】
O(n)
【空间复杂度】
O(n)
【gist link】
https://gist.github.com/alikewmk ... 8#file-4-3-bst-java
回复

使用道具 举报

🔗
frozenfire 2015-7-7 03:51:48 | 只看该作者
全局:
【解题思路】recursive in C++.
【时间复杂度】O(N)
【空间复杂度】O(N)
【gist link】
gist.github.com/frozenfire888/9230ce43d9c76430c934
回复

使用道具 举报

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

本版积分规则

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