记一些常见的手撕算法

怕什么真理无穷,进一寸有进一寸的欢喜

1.二分查找

    public int binarySearch(int[] arr,int key){
        int low = 0;
        int high = arr.length - 1;
        int mid = 0;

        if(key>arr[high]||key<arr[low]||low>high){
            return -1;
        }

        while(low<=high){
            mid = (low + high)/2;
            if(arr[mid] > key){
                high = mid - 1;
            }else if(arr[mid] < key){
                low = mid +1;
            }else {
                return mid;
            }
        }
        return -1;
    }

2.快速排序

    public void quickSort(int[] arr,int low,int high){
        int start = low;
        int end = high;
        int key = arr[low];

        while(start < end){
            //从后向前找
            while(start < end && arr[end] >= key){
                end--;
            }
            //交换arr-end和arr-start
            if(arr[end] >= key){
                int temp = arr[end];
                arr[end] = arr[start];
                arr[start] = temp;
            }
            //从前向后找
            while(start < end && arr[start] <= key){
                start++;
            }
            //交换
            if(arr[start] >= key){
                int temp = arr[start];
                arr[start] = arr[end];
                arr[end] = temp;
            }
        }
        //递归
        if(start > low){
            quickSort(arr,low,start-1);
        }
        if(end < high){
            quickSort(arr,end+1,high);
        }
    }

3.二叉树的层次遍历

    public void LaywerTraversal(TreeNode root){
        if(root==null){
            return;
        }
        LinkedList<TreeNode> list = new LinkedList<TreeNode>();
        list.add(root);
        TreeNode temp;
        while (!list.isEmpty()){
            temp = list.poll();
            System.out.println(temp.val);
            if(temp.left != null){
                list.add(temp.left);
            }
            if(temp.right!=null){
                list.add(temp.right);
            }
        }
    }

4.蛇形打印二叉树

    public void snakePrint(TreeNode root){
        if(root == null){
            return;
        }
        //用2个栈解决
        Li
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值