经历了很多次面试,总结现在面试常考的数据结构算法,可能会手写哦
1,快速排序
随便选取一个基数(一般为第一个数),然后将数组遍历,小于基数换到右面,大于放左面。递归左面,右面。
public static void quickSort(int[] array){
if(array == null || array.length == 0)
throw new RuntimeException("array is null");
sort(array, 0, array.length - 1);
}
private static void sort(int[] array, int start, int end){
int povit = array[start];
int left = start;
int right = end;
while(left < right){
while(left < right && array[right] >= povit){
right--;
}
// 右边数大于基数,赋值到left位置。这里应该是交换,使
// 用技巧,最后进行赋值。
if(left < right){
array[left] = array[right];
left++;
}
while(left < right && array[left] <= povit){
left++;
}
if(left < right){
array[right] = array[left];
right--;
}
}
// 在这里进行赋值,否则数组中会有两个一样数值
array[left] = povit;
if(start < left - 1){
sort(array, start, left - 1);
}
if(left + 1 < end){
sort(array, left + 1, end);
}
}
2, 插入排序
插入排序是每次排列前面有序n个数,将后面一个数插入其中。[ 时间复杂度o(n ^ 2)].
pubic void insertSort(int[] array){
int j = 0;
for(int i = 1; i < array.length; i++){
int temp = array[i];
for(j = i; j > 0 && array[j] < array[j - 1]; j--){
array[j] = array[j -1];
}
array[j] = temp;
}
}
3,二叉树的逐层遍历
一共有三种方法:
1,求k层的元素,再用深度去遍历。
2,把tree放入数组中,用两个指针控制层数。每次输出当前>data,以及压入下一层tree。
3,队列广度搜索。(暂时没研究)
需要用到的方法。
/**
* Tree类.
* filed : {data, leftTree, rightTree}
*/
class Tree{
int data;
Tree leftTree;
Tree rightTree;
public Tree(){}
public Tree(int data) {
this.data = data;
}
public Tree(int data, Tree leftTree, Tree rightTree){
this.data = data;
this.leftTree = leftTree;
this.right = rightTree;
}
}
// 获取树的深度
public int getTreeDeep(Tree root){
if(root == null) return 0;
return Math.max(get(root.leftTree), get(root.rightTree)) + 1;
}
// 获取树的节点个数
public int getTreeNum(Tree root){
if(root == null) return 0;
return get(root.leftTree) + get(root.rightTree) + 1;
}
// 树的初始化
/**
* 1
* 2 3
* 4 5 6
* 78
*/
Tree tree = new Tree(1,
new Tree(2, new Tree(4),
new Tree(5,
new Tree(7),
new Tree(8))),
new Tree(3, null,
new Tree(6)));
第一种方式
public void forPrint(Tree root){
int deep = getTreeDeep(root);
for(int i = 1; i <= deep; i++){
print(root, i);
}
}
public int print(Tree root, int level){
if(root == null || level < 0) return 0;
// root为1层
if(level == 1){
System.out.print(root.data + " ");
return 1;
}
return print(root.leftTree, level - 1) + print(root.rightTree, level - 1);
}
第二种方式
public void forEachTree(Tree root){
Tree[] array = new Tree[getTreeNum(root)];
array[0] = root;
int rowEnd = 0;
int rowStart = 0;
int eSize = 1;
while (rowStart < eSize) {
rowEnd = eSize;
while(rowStart < rowEnd){
System.out.print(array[rowStart].data + " ");
if(array[rowStart].leftTree != null){
array[eSize++] = array[rowStart].leftTree;
}
if(array[rowStart].rightTree != null){
array[eSize++] = array[rowStart].rightTree;
}
rowStart++;
}
System.out.println();
}
}
<meta http-equiv="Content-Type" content="快排,二叉树的逐层遍历(面试常考)"/>