楼主: williamwjs
跳转到指定楼层
上一主题 下一主题
收起左侧

Google 电面(准备二面求人品)

🔗
wangmengcathy 2015-10-8 08:44:59 | 只看该作者
全局:
按我的理解写了一段可以跑通的代码 求指正!
  1. public static int inferNthElement(int[] arr, int i, int n) {
  2.                 List<Integer> items = new ArrayList<Integer>();
  3.                 int cycle = 0;
  4.                 int start = 0;
  5.                 for(int j = 0; j <= n; j++) {
  6.                         if(j == 0) items.add(arr[i]);
  7.                         else if(!items.contains(arr[items.get(j - 1)])) {
  8.                                 items.add(arr[items.get(j - 1)]);
  9.                         }else {
  10.                                 start = items.indexOf(arr[items.get(j - 1)]);
  11.                                 cycle = j - start;
  12.                         }
  13.                 }
  14.                 if(items.size() != n + 1) {
  15.                         return items.get((n - start) % cycle + start);
  16.                 }else {
  17.                         return items.get(items.size() - 1);
  18.                 }
  19.         }
复制代码
回复

使用道具 举报

🔗
tangvictor 2015-10-19 08:02:30 | 只看该作者
全局:
python代码粘过来以供大家参考,多谢楼主分享。
第一个函数是k不大的时候,第二个是k可能很大的情况,考虑有环的解法。
  1. def arrayIndex(A, N, k, init):
  2.         a = init
  3.         for i in range(1, N + 1):
  4.                 a = A[a]

  5.         return a

  6. def indexCycle(A, N, k, init):
  7.         cycle = []
  8.         a = init
  9.         i = 1
  10.         while i <= N:
  11.                 if a not in cycle:
  12.                         cycle.append(a)
  13.                         a = A[a]
  14.                         i += 1
  15.                 else:
  16.                         break

  17.         if i == N:
  18.                 return a
  19.         else:
  20.                 return cycle[N % len(cycle)]
复制代码
回复

使用道具 举报

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

本版积分规则

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