Java常见算法题解析面试题(上)

1.冒泡排序。【重点】
int[]  arrs= {3,656,43,76,123};
for(int i=0;i for(int j=0;j if(arrs[j]>arrs[j+1]) {
      int temp=arrs[j];
      arrs[j]=arrs[j+1];
      arrs[j+1]=temp;
}
}
}
2.两个有序数组的合并。【重点】
int[] num1=new int[]{1,2,4,6,7,123,411,5334,1414141,1314141414};
int[] num1=new int[]{0,2,57,89,113,5623,6353,134134};
//变量用于存储两个集合应该被比较的索引(存入新集合就加一)
int a=0;
int b=0;
int[] num3=new int[num1.length+num2.length];
for(int i=0;i     if(a         if(num1[a]>num2[b]){
            num3[i]=num2[b];
            b++;
        }else{
            num3[i]=num2[a];
            a++;
        }
    }else if(a         num3[i]=num1[a];
        a++;
    }else if(b         num3[i]=num2[b];
        b++;
    }
}
System.out.println("排序后:"+Arrays.toString(num3));
3.一个数组的倒序。【重点】
public static int[] reverse(int[] a){
   int[] b=a;
    for( int start=0,end-b.length-1;start        int temp=b[start];
       b[start]=b[end];
       b[end]=temp;
    }
    return b;
}
4.计算一个正整数的正平方根。【了解】
public static double MySqrt(int value,double t){
    if(value<0||t<0)
        return 0;
    double left=0;
    double right=value;
    double mid=(right+left)/2;
    double offset=2*t;
    while(offset>t){
        double temp=mid*mid;
        if(temp>value){
            right=(left+right)/2;
            offset=temp-value;
        }
        if(temp<=value){
            left=(left+right)/2;
            offset=value-temp;
        }
        mid=(left+right)/2;
    }
    return mid;
}
5.快速排序算法。【重点】
public class QuickSort {
private int[] array;
public QuickSort(int[] array) { this.array = array; }
public void sort() { quickSort(array, 0, array.length - 1); }
public void print() {
for (int i = 0; i < array.length; i++) { System.out.println(array[i]); }
}
private void quickSort(int[] src, int begin, int end) {
if (begin < end) {
int key = src[begin];
int i = begin;
int j = end;
while (i < j) {
while (i < j && src[j] > key) { j--; }
if (i < j) { src[i] = src[j]; i++; }
while (i < j && src[i] < key) { i++; }
if (i < j) { src[j] = src[i]; j--; }
}
src[i] = key;
quickSort(src, begin, i - 1);
quickSort(src, i + 1, end);
}
}
}
6.二叉树的遍历算法。【了解】
节点类:
public class TreeNode {
   public int val;
   public TreeNode left;
   public TreeNode right;
   public TreeNode(int x) { val = x; }
   public TreeNode() { }
   @Override
   public String toString() { return "[" + val + "]"; }
}

二叉树算法类:
public class BinaryTree {
    //前序遍历
    public static void preOrder(TreeNode tree) {
        if (tree == null) return;
        System.out.printf(tree.val + "");
        preOrder(tree.left);
        preOrder(tree.right);
    }
    //非递归写法
    public static void preOrder2(TreeNode tree) {
         if (tree == null) return;
         Stack q1 = new Stack<>();
         q1.push(tree);//压栈
         while (!q1.empty()) {
            TreeNode t1 = q1.pop();//出栈
            System.out.println(t1.val);
            if (t1.right != null) { q1.push(t1.right); }
            if (t1.left != null) { q1.push(t1.left); }
        }
    }
    //中序遍历
    public static void inOrderTraversal(TreeNode node) {
        if (node == null) 
return;
        inOrderTraversal(node.left);
        System.out.println(node.val);
        inOrderTraversal(node.right);
     }
//非递归的写法
     public static void inOrderTraversal2(TreeNode tree) {
         Stack stack = new Stack<>();
         while (tree != null || !stack.isEmpty()) {
             while (tree != null) {
                 stack.push(tree);
                 tree = tree.left;
             }
             if (!stack.isEmpty()) {
                 tree = stack.pop();
                System.out.println(tree.val);
                tree = tree.right;
            }
        }
     }
//后续遍历
     public static void postOrder(TreeNode tree) {
            if (tree == null) return;
            postOrder(tree.left);
            postOrder(tree.right);
            System.out.println(tree.val);
         }
//非递归的写法
         public static void postOrder2(TreeNode tree) {
             if (tree == null) return;
             Stack s1 = new Stack<>();
             Stack s2 = new Stack<>();
             s1.push(tree);
             while (!s1.isEmpty()) {
                 tree = s1.pop();
                 s2.push(tree);
                if (tree.left != null) { s1.push(tree.left); }
                if (tree.right != null) { s1.push(tree.right); }
            }
            while (!s2.isEmpty()) { System.out.print(s2.pop().val + " "); }
         }
//或者
         public static void postOrder3(TreeNode tree) {
             if (tree == null) return;
             Stack stack = new Stack<>();
             stack.push(tree);
             TreeNode c;
             while (!stack.isEmpty()) {
                c = stack.peek();
                if (c.left != null && tree != c.left && tree != c.right) {
                    stack.push(c.left);
                } else if (c.right != null && tree != c.right) {
                    stack.push(c.right);
                } else {
                    System.out.print(stack.pop().val + " ");
                    tree = c;
                }
            }
        }
         //BFS(宽度优先搜索(又称广度优先搜索))
         public static void levelOrder(TreeNode tree) {
             if (tree == null) return;
             LinkedList list = new LinkedList<>();//链表,这里我们可以把它看做队列
             list.add(tree);//相当于把数据加入到队列尾部
             while (!list.isEmpty()) {
                TreeNode node = list.poll();//poll方法相当于移除队列头部的元素
                System.out.println(node.val);
                if (node.left != null) list.add(node.left);
                if (node.right != null) list.add(node.right);
            }
         }
//递归的写法
         public static void levelOrder(TreeNode tree) {
            int depth = depth(tree);
            for (int level = 0; level < depth; level++) { printLevel(tree, level); }
         }
         private static int depth(TreeNode tree) {
            if (tree == null) return 0;
            int leftDepth = depth(tree.left);
            int rightDepth = depth(tree.right);
            return Math.max(leftDepth, rightDepth) + 1;
        }
        private static void printLevel(TreeNode tree, int level) {
            if (tree == null) 
return;
            if (level == 0) {
                System.out.print(" " + tree.val);
            } else {
                printLevel(tree.left, level - 1);
                printLevel(tree.right, level - 1);
            }
        }
//如果想把遍历的结果存放到list中,我们还可以这样写
         public static List> levelOrder(TreeNode tree) {
             if (tree == null) return null;
             List> list = new ArrayList<>();
             bfs(tree, 0, list);
             return list;
         }
         private static void bfs(TreeNode tree, int level, List> list) {
            if (tree == null) return;
            if (level >= list.size()) {
                List subList = new ArrayList<>();
                subList.add(tree.val);
                list.add(subList);
            } else { list.get(level).add(tree.val); }
            bfs(tree.left, level + 1, list);
            bfs(tree.right, level + 1, list);
        }
         //DFS(深度优先搜索)
         public static void treeDFS(TreeNode root) {
             Stack stack = new Stack<>();
             stack.add(root);
             while (!stack.empty()) {
                TreeNode node = stack.pop();
                System.out.println(node.val);
                if (node.right != null) { stack.push(node.right); }
                if (node.left != null) { stack.push(node.left); }
            }
        }

//递归的写法
        public static void treeDFS(TreeNode root) {
            if (root == null) return;
            System.out.println(root.val);
            treeDFS(root.left);
            treeDFS(root.right);
        }
}
7.时间类型转换。【掌握】
public class DateFormat{
    public static void fun(){
        SimpleDateFormat sdf=new  SimpleDateFormat("yyyy年MM月dd日");
        String newDate;
        try{
            newDate=sdf.format(new  SimpleDateFormat("yyyyMMdd").parse("20121115"))
            System.out.println(newDate);
        }
    }
    public static void main(String args[]){
        fun();
    }
}
8.逆波兰计算器。【了解】
public class PolandNotation{
    public static void main(String[] args){
        //4*5-8+60+8/2
        String expression="4 5 * 8 - 60 + 8 2 / +";
        List list=getStrList(expression);
        System.out.println(list);
        //计算值,得结果
        int res=calc(list);
        System.out.println(res);
    }
    public static List getStrList(String exp){
        String arr[]=exp.split(" ");//将字符串遍历得到数组
        List list=new ArrayList<>();
        for(String str:arr){
            list.add(str);
        }
        return list;
    }
    //计算表达式
    public static int calc(List list){
        Stack stack=new Stack<>();
        //遍历list
        for(int i=0;i             //正则表达式匹配是否是数字
            if(list.get(i).matcher("\\d+")){
                stack.push(list.get(i)); //是数字则放入栈中
            }else{
                int num2=Integer.parseInt(stack.pop()); //弹出数字1
                int num1=Integer.parseInt(stack.pop()); //弹出数字2
                int res=0;
                //进行运算
                if(list.get(i).equals("+")){
                    res=num1+num2;
                }else if(list.get(i).equals("-")){
                    res=num1-num2;
                }else if(list.get(i).equals("*")){
                    res=num1*num2;
                }else if(list.get(i).equals("/")){
                    res=num1/num2;
                }else{
                    throw new RuntimeException("不是操作符号!");
                }
                stack.push(""+res);
            }
        }
        //留在栈中的值就是最后的计算表达式结果
        return Integer.parseInt(stack.pop());
    }
}
9.阶乘。【重点】
public class Multiply { 
    public static int multiply(int num) {
        if (num < 0) { 
            System.out.println("请输入大于 0 的数!");
            return -1;
        } else if (num == 0 || num == 1) {
            return 1; 
        } else {
            return multiply(num - 1) * num; 
        } 
    }
    public static void main(String[] args) { 
        System.out.println(multiply(10));
    } 
}
10.斐波那契数列。【了解】
问题描述:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
// 这是一个菲波拉契数列问题 
public class lianxi{ 
    public static void main(String[] args) { 
        System.out.println("第1个月的兔子对数: 1");
        System.out.println("第2个月的兔子对数: 1");
        int f1 = 1, f2 = 1, f, M=24; 
        for(int i=3; i<=M; i++) { 
            f = f2; 
            f2 = f1 + f2;
            f1 = f; 
            System.out.println("第" + i +"个月的兔子对数: "+f2); 
        }
    }
}

你可能感兴趣的:(Java,java,算法,面试)