牛客网剑指Offer刷题

文章目录

  • 1. 二维数组中的查找
  • 2. 替换空格
  • 3. 从尾到头打印链表
  • 4. 重建二叉树
  • 5. 用两个栈实现队列
  • 6. 旋转数组的最小数字
  • 7. 斐波那契数列
  • 8. 跳台阶
  • 9. 变态跳台阶
  • 10. 矩形覆盖
  • 11. 二进制中1的个数
  • 12.数值的整数次方
  • 13. 调整数值顺序使奇数位于偶数前面
  • 14. 链表中倒数第K个结点
  • 15. 反转链表
  • 16. 合并两个排序的链表
  • 17. 树的子结构
  • 18. 二叉树的镜像
  • 19. 顺时针打印矩阵
  • 20. 包含min函数的栈
  • 21. 栈的压入弹出序列
  • 22. 从上往下打印二叉树
  • 23. 二叉搜索树的后序遍历数列

1. 二维数组中的查找

题目描述:在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

public class Solution {
     
    // 思路:从右上角开始查找,如果当前值小于目标值,向下查找,否则向左查找
    public boolean Find(int target, int [][] array) {
     
        int row = array.length-1;
        int column = array[0].length-1;
        int i = 0;
        int j = column;
        while(i<=row && j>=0){
     
            if(array[i][j] == target){
     
                return true;
            }else if(array[i][j] > target){
     
                j--;
            }else{
     
                i++;
            }
        }
        return false;
    }
}

2. 替换空格

题目描述:请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

public class Solution {
     
    // 用Java的API做真的无耻
    public String replaceSpace(StringBuffer str) {
     
        return str.toString().replaceAll(" ","%20");
    }
}

3. 从尾到头打印链表

输入一个链表,按链表从尾到头的顺序返回一个ArrayList。

public class Solution {
     
    ArrayList<Integer> ret = new ArrayList<>();
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
     
        if(listNode != null){
     
            printListFromTailToHead(listNode.next);
            ret.add(listNode.val);
        }
        return ret;
    }
}

4. 重建二叉树

题目描述:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

public class Solution {
     
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
     
        if(pre.length == 0 || in.length==0){
     
            return null;
        }
        TreeNode root = new TreeNode(pre[0]);
        for(int i=0;i<pre.length;i++){
     
            if(in[i] == pre[0]){
     
                root.left = reConstructBinaryTree(Arrays.copyOfRange(pre,1,i+1),
                                                  Arrays.copyOfRange(in,0,i));
                root.right = reConstructBinaryTree(Arrays.copyOfRange(pre,i+1,pre.length),
                                                   Arrays.copyOfRange(in,i+1,in.length));
                break;
            }
        }
        return root;
    }
}

5. 用两个栈实现队列

题目描述:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

public class Solution {
     
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    public void push(int node) {
     
        stack1.push(node);
    }
    public int pop() {
     
        while(!stack1.isEmpty()){
     
            stack2.push(stack1.pop());
        }
        int ret = stack2.pop();
        while(!stack2.isEmpty()){
     
            stack1.push(stack2.pop());
        }
        return ret;
    }
}

6. 旋转数组的最小数字

题目描述:把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。

public class Solution {
     
    public int minNumberInRotateArray(int [] array) {
     
        if(array==null || array.length==0){
     
            return 0;
        }
        int low = 0;
        int high = array.length-1;
        while(low < high){
     
            int mid = (low+high)>>1;
            if(array[mid] > array[high]){
     
                low = mid+1;;
            }else{
     
                high = mid;
            }
        }
        return array[low];
    }
}

7. 斐波那契数列

题目描述:大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0,n<=39)。

public class Solution {
     
    public int Fibonacci(int n) {
     
        int f = 0;
        int g = 1;
        while(n-- > 0){
     
            f = f+g;
            g = f-g;
        }
        return f;
    }
}

8. 跳台阶

题目描述:一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。

public class Solution {
     
    // 其实就是斐波那契数列F(n) = F(n-1) + F(n-2)
    public int JumpFloor(int target) {
     
        int f = 1;
        int g = 1;
        while(target-- > 1){
     
            f = f+g;
            g = f-g;
        }
        return f;
    }
}

9. 变态跳台阶

题目描述:一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。

public class Solution {
     
    // F(n) = 2F(n-1) = 2^(n-1)
    public int JumpFloorII(int target) {
     
        return 1<<(target-1);
    }
}

10. 矩形覆盖

题目描述:我们可以用21的小矩形横着或者竖着去覆盖更大的矩形。请问用n个21的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?

public class Solution {
     
    public int RectCover(int target) {
     
        /*
        if(target <= 2){
            return target;
        }else{
            return RectCover(target-1)+RectCover(target-2);
        }*/
        if(target <= 2){
     
            return target;
        }
        int f = 2;
        int g = 1;
        while(target-- > 2){
     
            f = f+g;
            g = f-g;
        }
        return f;
    }
}

11. 二进制中1的个数

题目描述:输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

public class Solution {
     
    public int NumberOf1(int n) {
     
        int num = 0;
        while(n !=0){
     
            n = n&(n-1);
            num++;
        }
        return num;
    }
}

12.数值的整数次方

题目描述:给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方(保证base和exponent不同时为0)。

public class Solution {
     
    public double Power(double base, int exponent) {
     
        double num = 1.0;
        int exp = exponent>0 ? exponent : -exponent;
        for(int i=0;i<exp;i++){
     
            num *= base;
        }
        if(exponent < 0){
     
            num = 1.0/num;
        }
        return num;
  }
}

13. 调整数值顺序使奇数位于偶数前面

题目描述:输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。

public class Solution {
     
    public void reOrderArray(int [] array) {
     
        for(int i=1;i<array.length;i++){
     
            if(array[i]%2 == 1){
     
                int temp = array[i];
                int j = i-1;
                while(j>=0 && array[j]%2==0){
     
                    array[j+1] = array[j];
                    j--;
                }
                array[j+1] = temp;
            }
        }
    }
}

14. 链表中倒数第K个结点

题目描述:输入一个链表,输出该链表中倒数第k个结点。

public class Solution {
     
    public ListNode FindKthToTail(ListNode head,int k) {
     
        if(head==null||k<=0){
     
            return null;
        }
        ListNode pre=head;
        ListNode last=head;       
        for(int i=1;i<k;i++){
     
            if(pre.next!=null){
     
                pre=pre.next;
            }else{
     
                return null;
            }
        }
        while(pre.next!=null){
     
            pre = pre.next;
            last=last.next;
        }
        return last;
    }
}

15. 反转链表

题目描述:输入一个链表,反转链表后,输出新链表的表头。

public class Solution {
     
    public ListNode ReverseList(ListNode head) {
     
        /*
        // 循环
        ListNode pre = null;
        ListNode next = null;
        while(head != null){
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
        */
        // 递归
        if(head == null || head.next == null){
     
            return head;
        }
        ListNode newHead = ReverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
}

16. 合并两个排序的链表

题目描述:输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

public class Solution {
     
    public ListNode Merge(ListNode list1,ListNode list2) {
     
        ListNode head = new ListNode(0);
        ListNode temp = head;
        while(list1!=null && list2!=null){
     
            if(list1.val <= list2.val){
     
                temp.next = list1;
                list1 = list1.next;
            }else{
     
                temp.next = list2;
                list2 = list2.next;
            }
            temp = temp.next;
        }
        if(list1 != null){
     
            temp.next = list1;
        }
        if(list2 != null){
     
            temp.next = list2;
        }
        return head.next;
    }
}

17. 树的子结构

题目描述:输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)。

public class Solution {
     
    private boolean isSubtree(TreeNode root1,TreeNode root2){
     
        if(root2 == null){
     
            return true;
        }
        if(root1 == null){
     
            return false;
        }
        if(root1.val == root2.val){
     
            return isSubtree(root1.left,root2.left) && isSubtree(root1.right,root2.right);
        }else{
     
            return false;
        }
    }
    public boolean HasSubtree(TreeNode root1,TreeNode root2) {
     
        if(root1 == null || root2==null){
     
            return false;
        }
        return isSubtree(root1,root2) || HasSubtree(root1.left,root2) || HasSubtree(root1.right,root2);
    }
}

18. 二叉树的镜像

题目描述:操作给定的二叉树,将其变换为源二叉树的镜像。

public class Solution {
     
    public void Mirror(TreeNode root) {
     
        if(root == null){
     
            return;
        }
        TreeNode node = root.left;
        root.left = root.right;
        root.right = node;
        Mirror(root.left);
        Mirror(root.right);
    }
}

19. 顺时针打印矩阵

题目描述:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10。

public class Solution {
     
    public ArrayList<Integer> printMatrix(int [][] matrix) {
     
        ArrayList<Integer> result = new ArrayList<Integer> ();
        int n = matrix.length;
        int m = matrix[0].length;
        int layers = (Math.min(n,m)-1)/2+1;//层数
        for(int i=0;i<layers;i++){
     
            for(int k = i;k<m-i;k++){
     
                result.add(matrix[i][k]);//左至右
            }
            for(int j=i+1;j<n-i;j++){
     
                result.add(matrix[j][m-i-1]);//右上至右下
            }
            for(int k=m-i-2;(k>=i)&&(n-i-1!=i);k--){
     
                result.add(matrix[n-i-1][k]);//右至左
            }
            for(int j=n-i-2;(j>i)&&(m-i-1!=i);j--){
     
                result.add(matrix[j][i]);//左下至左上
            }
        }
        return result; 
    }
}

20. 包含min函数的栈

题目描述:定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。

public class Solution {
     
    private Stack<Integer> stack = new Stack<>();
    private Stack<Integer> minStack = new Stack<>();
    public void push(int node) {
     
        stack.push(node);
        if(minStack.empty())
            minStack.push(node);
        else if(node <= minStack.peek()){
     
            minStack.push(node);
        }
    }
    public void pop() {
     
        if(stack.peek() == minStack.peek()){
     
            minStack.pop();
        }
        stack.pop();
    }
    public int top() {
     
        return stack.peek();
    }
    public int min() {
     
        return minStack.peek();
    }
}

21. 栈的压入弹出序列

问题描述:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

public class Solution {
     
    public boolean IsPopOrder(int [] pushA,int [] popA) {
     
        if(pushA.length == 0 || popA.length == 0){
     
            return false;
        }
        Stack<Integer> pushStack = new Stack<>();
        int index = 0;
        for(int i=0;i<pushA.length;i++){
     
            pushStack.push(pushA[i]);
            while(!pushStack.empty() && pushStack.peek() == popA[index]){
     
                pushStack.pop();
                index++;
            }
        }
        return pushStack.empty();
    }
}

22. 从上往下打印二叉树

题目描述:从上往下打印出二叉树的每个节点,同层节点从左至右打印。

public class Solution {
     
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
     
        ArrayList<Integer> list = new ArrayList<>();
        ArrayList<TreeNode> queue = new ArrayList<>();
        if(root == null){
     
            return list;
        }
        queue.add(root);
        while(queue.size() != 0){
     
            TreeNode temp = queue.remove(0);
            if(temp.left != null){
     
                queue.add(temp.left);
            }
            if(temp.right != null){
     
                queue.add(temp.right);
            }
            list.add(temp.val);
        }
        return list;
    }
}

23. 二叉搜索树的后序遍历数列

题目描述:输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。

public class Solution {
     
    public boolean VerifySquenceOfBST(int [] sequence) {
     
        if(sequence.length == 0){
     
            return false;
        }
        return verify(sequence,0,sequence.length-1);
    }
    private boolean verify(int[] arr,int start,int end){
     
        if(start >= end){
     
            return true;
        }
        int root = arr[end];
        int i = 0;
        for(;i<end;i++){
     
            if(arr[i]>root){
     
                break;
            }
        }
        int j = i;
        for(;j<end;j++){
     
            if(arr[j]<root){
     
                return false;
            }
        }
        boolean left = true;
        if(i > start){
     
            left = verify(arr, start, i-1);
        }
        boolean right = true;
        if(i < end){
     
            right = verify(arr, i, end -1); 
        }
        return (left && right);
    }
}

你可能感兴趣的:(算法与数据结构)