[小米面试题]小米Git

来源:互联网 发布:卖钣金展开软件 编辑:程序博客网 时间:2024/04/29 19:36

题目描述

git是一种分布式代码管理工具,git通过树的形式记录文件的更改历史,比如: base'<--base<--A<--A' ^ | --- B<--B' 小米工程师常常需要寻找两个分支最近的分割点,即base.假设git 树是多叉树,请实现一个算法,计算git树上任意两点的最近分割点。 (假设git树节点数为n,用邻接矩阵的形式表示git树:字符串数组matrix包含n个字符串,每个字符串由字符'0'或'1'组成,长度为n。matrix[i][j]=='1'当且仅当git树种第i个和第j个节点有连接。节点0为git树的根节点。) 
输入例子:
[01011,10100,01000,10000,10000],1,2

输出例子:
1

问题就是求 多叉树寻找最近公共父节点问题 ,不要被GIt影响,问题前面都是废话。。

思路:

     

解题思路

  1. 从矩阵构造出father数组,father数组保存每个节点的父节点。
  2. 记录从根节点到带求节点A和B的路径。
  3. 比较路径,找到最近的公共节点。

参考代码:

import java.util.*;public class getSplit {/** * @param args */public int getSplitNode(String[] matrix, int indexA, int indexB) {int res=0;if(indexA==indexB)return indexA;int len=matrix.length;int father[]=new int[len];int flag[]=new int[len];father[0]=-1;flag[0]=1;Deque<Integer> children = new ArrayDeque<Integer>();children.offer(0);while(!children.isEmpty()){int parent=children.poll();char ch[]=matrix[parent].toCharArray();for(int i=0;i<len;i++){if(flag[i]!=1&&ch[i]=='1'){flag[i]=1;father[i]=parent;children.offer(i);}}}Deque<Integer> qa = new ArrayDeque<Integer>();Deque<Integer> qb = new ArrayDeque<Integer>();while(indexA!=-1){qa.addFirst(indexA);indexA=father[indexA];}while(indexB!=-1){qb.addFirst(indexB);indexB=father[indexB];}while(qa.peekFirst()==qb.peekFirst()){res=qa.peekFirst();qa.pollFirst();qb.pollFirst();}return res;    }public static void main(String[] args) {// TODO Auto-generated method stubString a[]={"01011","10100","01000","10000","10000"};System.out.println(new getSplit().getSplitNode(a, 1, 2));}}



代码来源 https://www.nowcoder.com/questionTerminal/e9ff41269a7e49519b87fe7d9fd0d477

原创粉丝点击