牛客剑指offer66题汇总(一)

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

public class Solution {
    public boolean Find(int target, int [][] array) {
        if(array == null || array.length == 0) return false;
        int i= 0,j= array[0].length-1 ;
        while(i<array.length &&j>=0){
            if(array[i][j] == target) return true;
            else if(array[i][j]>target) j--;
            else if(array[i][j]<target) i++;
        }
        return false;
    }
}

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

public class Solution {
    public String replaceSpace(StringBuffer str) {
         
         
        int count = 0;
        String s = str.toString();
        for(int i = 0;i<s.length();i++){
            if(str.charAt(i) == ' '){
                count++;
            }
        }
        int len = s.length();
        str.setLength(len+count*2);
        for(int i = len -1;i>=0;i--){
            if(str.charAt(i) == ' '){
                count -- ;
                str.setCharAt(i+2*count+2,'0');
                str.setCharAt(i+2*count+1,'2');
                str.setCharAt(i+2*count,'%');
            }else{
                str.setCharAt(i+2*count,str.charAt(i));
            }
        }
        return str.toString();
    }
}

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

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

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

import java.util.HashMap;
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
       if(pre == null || pre.length == 0 || in == null || in.length ==0)  return null;
       HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        for(int i =0;i<in.length;i++){
            map.put(in[i],i);
        }
        return reConstructTree(pre,0,pre.length-1,in,0,in.length-1,map);
    }
    public TreeNode reConstructTree(int[]pre,int prei,int prej,int[]in,int ini,int inj,HashMap<Integer,Integer> map){
        if(prei>prej) return null;
        int index = map.get(pre[prei]) ;
        TreeNode node = new TreeNode(pre[prei]);
        node.left = reConstructTree(pre,prei+1,prei+index-ini,in,ini,index-1,map);
        node.right = reConstructTree(pre,prei+index-ini+1,prej,in,index+1,inj,map);
        return node;
    }
}

中序与后序遍历建立二叉树:

 public TreeNode buildTree(int []in,int ini,int inj,int[] post,int posi,int posj) {
		  if(ini>inj || posi>posj) return null;
		  int index = 0;
		  TreeNode root = new TreeNode(post[posj]);
		  for(int i = ini;i<=inj;i++) {
			 if(in[i] == post[posj]) {
				 index = i;
				 break;
			 }
		  }
		 root.left = buildTree(in,ini,index-1,post,posi,posi+index-ini-1);  
		 root.right = buildTree(in,index+1,inj,post,posi+index-ini,posj-1);
		 return root;
	  }
	 

5.用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

import java.util.Stack;
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() {
      if(stack2.isEmpty()){
          while(!stack1.isEmpty()){
              stack2.push(stack1.pop());
          }
           
      }
          return stack2.pop();   
   }
}

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

import java.util.ArrayList;
public class Solution {
    public int minNumberInRotateArray(int [] array) {
      if(array == null || array.length == 0) return -1;
         
        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 if(array[mid] == array[high]){
                high = high -1;
            }else{
                high = mid;
            }
        }
        return array[low];
    }
}

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

public class Solution {
    public int Fibonacci(int n) {
       if(n ==0) return 0;
       if(n<=2) return 1;
         
        int a = 1,b=1,c=0;
        for(int i = 3;i<=n;i++){
            c = a+b;
            a= b;
            b =c;
             
        }
        return c;
    }
}

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

public class Solution {
    public int JumpFloor(int target) {
     int a = 1, b =2 ,c =0;
        if(target<0)return -1;
        if(target == 0)return 0;
        if(target == 1)return 1;
        if(target ==2)return 2;
        for(int i=3;i<=target ;i++){
            c=a+b;
            a=b;
            b=c;
        }
        return c;
    }
}

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

public class Solution {
    public int JumpFloorII(int target) {
        if (target <= 0) {
            return -1;
        } else if (target == 1) {
            return 1;
        } else {
            return 2 * JumpFloorII(target - 1);
        }
    }
}

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

public class Solution {
    public int RectCover(int target) {
   if(target<=1) return target;
        else if(target ==2) return 2;
        else return RectCover(target-1)+RectCover(target-2);
         
    }
}

10.输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

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

11.给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。保证base和exponent不同时为0

public class Solution {
    public double Power(double base, int exponent) {
        if(exponent == 0) return 1;
         
        double sum = 1;
        int exp= Math.abs(exponent);
        for(int i = 1;i<=exp;i++){
            sum = base*sum;
        }
        if(exponent>0){
           return sum;
        }else{
            return  1/sum;
        }
  }
}

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

public class Solution {
    public void reOrderArray(int [] a) {
      
if(a==null||a.length==0)
        return;
    int i = 0,j;
    while(i<a.length){
        while(i<a.length&&!isEven(a[i]))
            i++;
        j = i+1;
        while(j<a.length&&isEven(a[j]))
            j++;
        if(j<a.length){
            int tmp = a[j];
            for (int j2 = j-1; j2 >=i; j2--) {
                a[j2+1] = a[j2];
            }
            a[i++] = tmp;
        }else{// 查找失敗
            break;
        }
    }
    }
     
    boolean isEven(int n){
    if(n%2==0)
        return true;
    return false;
}
}

13.输入一个链表,输出该链表中倒数第k个结点。

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

14.输入一个链表,反转链表后,输出新链表的表头。

public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode newHead = ReverseList(head.next);
         head.next.next =head;
        head.next = null;
        return newHead;
    }
}

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

public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
        if(list1 == null) return list2;
        if(list2 == null) return list1;
        if(list1.val<list2.val){
          list1.next = Merge(list1.next,list2);
            return list1;
        }else{
            list2.next = Merge(list2.next,list1);
            return list2;
        }
    }
}

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

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

17.操作给定的二叉树,将其变换为源二叉树的镜像。

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

18.输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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.

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
       ArrayList<Integer> list = new ArrayList<Integer>();
        if(matrix == null || matrix.length == 0) return list;
        printMatrix2(matrix,0,0,matrix.length-1,matrix[0].length-1,list);
       return list;
    }
    public void printMatrix2(int [][] matrix,int startRow,int startCol,int endRow,int endCol,ArrayList<Integer>list){
        if(startRow<endRow && startCol<endCol){
         for(int i = startCol;i<=endCol;i++) list.add(matrix[startRow][i]);
         for(int j = startRow+1;j<endRow;j++) list.add(matrix[j][endCol]);
         for(int i = endCol;i>=startCol;i--)  list.add(matrix[endRow][i]);
         for(int j = endRow-1;j>=startRow+1;j-- ) list.add(matrix[j][startCol]);
         printMatrix2(matrix,startRow+1,startCol+1,endRow-1,endCol-1,list);
        }else if(startRow == endRow && startCol<endCol){
            for(int i = startCol;i<=endCol;i++){
                list.add(matrix[startRow][i]);
            }
        }else if(startCol == endCol && startRow<endRow){
            for(int i = startRow;i<=endRow;i++){
                list.add(matrix[i][startCol]);
            }
        }else if(startCol == endCol && startRow == endRow){
            list.add(matrix[startRow][startCol]);
        }
         
    }
}

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

import java.util.Stack;
public class Solution {
    Stack<Integer> st = new Stack<Integer>();
    Stack<Integer> min = new Stack<Integer>();
    public void push(int node) {
         st.push(node); 
        if(min.isEmpty()) min.push(node);
        else if(node<min.peek()) min.push(node); 
    }
     
    public void pop() {
      int temp = st.pop();
        if(temp == min.peek()){
            min.pop();
        }
    }
     
    public int top() {
      
        return st.peek();
    }
    public int min() {
       return min.peek();
    }
}

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

import java.util.ArrayList;
import java.util.Stack;
public class Solution {
    public boolean IsPopOrder(int [] pushA,int [] popA) {
      Stack<Integer> st = new Stack<Integer>();
        int j = 0;
      for(int i = 0;i<pushA.length;i++){
          st.push(pushA[i]);
          
              while(!st.isEmpty() &&st.peek() == popA[j]){
                  st.pop();
                  j++;
              }
           
      } 
        if(st.isEmpty()) return true;
        return false;
    }
}

21.从上往下打印出二叉树的每个节点,同层节点从左至右打印。

public class Solution {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
       ArrayList<Integer> list = new ArrayList<Integer>();
       if(root == null) return list;
       LinkedList<TreeNode> list2 = new LinkedList<TreeNode>();
        list2.add(root);
        while(!list2.isEmpty()){
            TreeNode temp = list2.pop();
            list.add(temp.val);
            if(temp.left!=null){
                 list2.add(temp.left);
            }
            if(temp.right!=null){
                list2.add(temp.right);
            }
        }
        return list;
    }
}

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

public class Solution {
    public boolean VerifySquenceOfBST(int [] sequence) {
        if(sequence == null || sequence.length == 0) return false;
        return verifySequence(sequence,0,sequence.length-1);
         
    }
    public boolean verifySequence(int [] sequence,int start,int end){
        if(start>=end) return true;
        int i = start;
        for(;i<end;i++){
            if(sequence[i]>sequence[end]){
                 
                break;
            }
        }
        for(int j =i;j<end;j++){
            if(sequence[j]<sequence[end]) return false;
        }
        return verifySequence(sequence,start,i-1)&&verifySequence(sequence,i,end-1);
    }
}

23.输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)

public class Solution {
    
     
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
       ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>> ();
        if(root == null) return list;
        ArrayList<Integer> list2 = new ArrayList<Integer>();
        int sum = 0;
        pa(root,list,list2,target,sum);
        return list;
    }
    public void pa(TreeNode root,ArrayList<ArrayList<Integer>> list,ArrayList<Integer> list2,int target,int sum){
       if(root == null) return;
        sum+=root.val;
        if(root.left == null && root.right == null){
            if(target == sum){
                list2.add(root.val);
                list.add(new ArrayList<Integer>(list2));
                list2.remove(list2.size()-1);
            }
        }
        list2.add(root.val);
        pa(root.left,list,list2,target,sum);
        pa(root.right,list,list2,target,sum);
        list2.remove(list2.size()-1);
    }
}

24.输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

public class Solution {
    public RandomListNode Clone(RandomListNode pHead)
    {
        if(pHead == null) return pHead;
          
        RandomListNode p = pHead;
        while(p!=null){
            RandomListNode t = new RandomListNode(p.label);
            t.next = p.next;
            p.next = t;
            p= t.next;
        }
         p = pHead;
          
        while(p!=null){
            RandomListNode t = p.next;
            if(p.random!= null) t.random = p.random.next;
            p= t.next;
             
        }
       RandomListNode s = new RandomListNode(0);
        RandomListNode s1 = s;
        while(pHead!=null){
            RandomListNode q = pHead.next;
            pHead.next = q.next;
            q.next = s.next;
            s.next = q;
            s = s.next;
            pHead = pHead.next;
        }
        return s1.next;
    }
}

25.输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。

public class Solution {
    TreeNode pre = null;
    TreeNode head = null;
    public TreeNode Convert(TreeNode root) {
        if(root == null) return null;
         
        convert2(root);
        return head;
    }
    public void convert2(TreeNode root){
        if(root == null) return ;
        convert2(root.left);
         
        if(head == null){
            pre = root;
            head = root;
        }else{
            root.left = pre;
            pre.right = root;
            pre = root;
        }
        convert2(root.right);
    }
}

26.输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。

import java.util.*;
public class Solution {
    public ArrayList<String> Permutation(String str) {
       ArrayList<String> list = new ArrayList<String>();
         
        if(str == null || str.length() == 0)return list;
        char [] c = str.toCharArray();
        pa(c,0,c.length,list);
        Collections.sort(list);
        return list;
    }
    public void pa(char []c,int start,int len,ArrayList<String> list){
        if(start == len-1){
            String s = new String(c);
            if(!list.contains(s))
            list.add(new String(c));
        }else{
            for(int i =start;i<len;i++){
                swap(c,i,start);
                pa(c,start+1,len,list);
                swap(c,i,start);
            }
        }
    }
     
    public void swap(char[] c,int i,int j){
        char temp;
        temp = c[i];
        c[i] = c[j];
        c[j] = temp;  
    }
}

27.数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。

public class Solution {
    public int MoreThanHalfNum_Solution(int [] array) {
        if(array == null || array.length <1) return 0;
        int time = 1;
        int temp = array[0];
        for(int i = 1;i<array.length;i++){
            if(temp == array[i]){
                time++;
            }else{
                time --;
                if(time == 0){
                    temp = array[i];
                    time = 1;
                }
            }
        }
        time = 0;
        for(int i = 0;i<array.length;i++){
            if(array[i] == temp) time++;
        }
        if(time>array.length/2) return temp;
        return 0;
    }
}

28.输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。

import java.util.*;
public class Solution {
  public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
           ArrayList<Integer> list = new ArrayList<Integer>();
           if(input == null || input.length == 0 ||k>input.length) return list;
           PriorityQueue<Integer> p = new PriorityQueue<Integer>(
           );
           for(int i=0;i<input.length;i++) {
               p.add(input[i]);
           }
           for(int i = 0;i<k;i++) {
               list.add(p.poll());
           }
        return list;            
      }
 }

29.HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢?例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。给一个数组,返回它的最大连续子序列的和,你会不会被他忽悠住?(子向量的长度至少是1)

public class Solution {
    public int FindGreatestSumOfSubArray(int[] array) {
        int max = array[0];
        int result = array[0];
        for(int i=1;i<array.length;i++){
           max = Math.max(array[i],max+array[i]);
           result = Math.max(max,result);
        }
        return result;
    }
}

30.求出113的整数中1出现的次数,并算出1001300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数)。

public class Solution {
    public int NumberOf1Between1AndN_Solution(int n) {
     if(n<=0) return 0;
        int count = 0;
        for(int i = 1;i<=n;i*=10){
            int a= n/i,b = n%i;
            count=count+ (a+8)/10*i +((a%10 == 1)?1:0)*(b+1);
        }
        return count;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值