剑指offer习题JAVA实现(一)

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

public class Solution {
    public boolean Find(int [][] array,int target) {
        int len = array.length-1;
        int i = 0;
        while((len >= 0)&& (i < array[0].length)){
            if(array[len][i] > target){
                len--;
            }else if(array[len][i] < target){
                i++;
            }else{
                return true;
            }
        }
        return false;
    }
}
2. 请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

public class Solution {
    public String replaceSpace(StringBuffer str) {
    	char a[]=str.toString().toCharArray();
   
    	int orilen=a.length;
    	int blank=0;
    	for(int i=0;i<a.length;i++){
    		if(a[i]==' '){
    			blank++;
    		}
    	}
    	int newlen=orilen+blank*2;
    	char b[]=new char[newlen];
    	int j=0;
    	for(int i=0;i<orilen;i++){
    		if(a[i]==' '){
    			b[j++]='%';
    			b[j++]='2';
    			b[j++]='0';  			
    		}else{
    			b[j++]=a[i];
    		}
    	}
    	return String.valueOf(b);
    }
}


3. 输入一个链表,从尾到头打印链表每个节点的值

public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
       Stack <Integer>stack=new Stack<Integer>();
       while(listNode!=null){
    	   stack.push(listNode.val);
           listNode=listNode.next;
       }
       ArrayList list=new ArrayList();
       while(!stack.isEmpty()){
    	   list.add(stack.pop());
       }
       return list;
    }
}
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) {
    TreeNode root=new TreeNode(pre[0]);//前序的第一个数定为根 
    int len=pre.length; //当只有一个数的时候 
    if(len==1){ 
        root.left=null; 
        root.right=null; 
        return root; 
    }  
    int rootval=root.val; 
    int i; 
    for(i=0;i<len;i++){ 
        if(rootval==in[i]) 
            break; 
    } //找到中序中的根位置
    //创建左子树 
    if(i>0){ 
        int[] pr=new int[i]; 
        int[] ino=new int[i]; 
        for(int j=0;j<i;j++){ 
            pr[j]=pre[j+1]; 
        } 
        for(int j=0;j<i;j++){ 
            ino[j]=in[j]; 
        } 
        root.left=reConstructBinaryTree(pr,ino); 
    }else{ 
        root.left=null; 
    } 
    //创建右子树 
    if(len-i-1>0){ 
        int[] pr=new int[len-i-1]; 
        int[] ino=new int[len-i-1]; 
        for(int j=i+1;j<len;j++){ 
            ino[j-i-1]=in[j]; 
            pr[j-i-1]=pre[j]; 
        } 
        root.right=reConstructBinaryTree(pr,ino); 
    }else{ 
        root.right=null; 
    } 
    	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 first=stack2.pop();
    	 while(!stack2.isEmpty()){
    		 stack1.push(stack2.pop());
    	 }  	
    	return first;
    }
}
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){
    		return 0;
    	}
    	for(int i=0;i<array.length;i++){
    		if(array[i]>array[i+1]){
    			return array[i+1];
    		}
    	}
    	return array[0];
    }
}

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

public class Solution { 
    public int Fibonacci(int n) {  //这种写法模拟了递归写法的逆过程,降低时间复杂度
	int[] a={0,1};
    	if(n<=1){
    		return a[n]; 
    	}
    	int fmiuone=1;
    	int fmiutwo=0;
    	int fnew=0;
    	for(int i=2;i<=n;++i){
    		fnew=fmiuone+fmiutwo;
    		fmiutwo=fmiuone;
    		fmiuone=fnew;
    	}
    	return fnew;   
    }
}
8. 一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。

public class Solution {
    public int JumpFloor(int target) {//其实就是斐波那契的变形
	  int[] a={0,1,2};
          if(target<=2){
              return a[target];
          }
          int fmiuone=1;
          int fmiutwo=2;
          int fnew=0;
          for(int i=2;i<target;i++){
              fnew=fmiuone+fmiutwo;
              fmiuone=fmiutwo;
              fmiutwo=fnew;
          }
          return fnew;
    }
}
9. 一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。

public class Solution {
    public int JumpFloorII(int target) {//数学归纳法求出通项公式
       int sum=1;
        for(int i=0;i<target-1;i++){
            sum *=2;
        }
        return sum;
    }
}
10. 我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?

public class Solution {
    public int RectCover(int target) {
		int a[]={0,1,2};
    	if(target<=2){
    		return a[target];
    	}
    	int fone=1;
    	int ftwo=2;
    	int fnew=0;
    	for(int i=2;i<target;i++){
    		fnew=fone+ftwo;	
    		fone=ftwo;
    		ftwo=fnew;
    	}
    	return fnew;
    }
}
11. 输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

public class Solution {
    public int NumberOf1(int n) {
	char []a=Integer.toBinaryString(n).toCharArray();//1是通过调用JAVA函数将整数变为二进制表示2是通过位运算进行计算的
    	int sum=0;
    	for(int i=0;i<a.length;i++){
    		if(a[i]=='1')
    			sum++;
    	}
    	return sum;	
    }
   public static int NumberOf2(int n) {
	int count=0;
	for(int i=0;i<=32;i++){
		count += (n&1);
		n=n>>1;
	}
	return count;
}
}


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

public class Solution {
    public void reOrderArray(int [] array) {//水题的话,能不能考虑一些复杂度更小的方法
        ArrayList list1=new ArrayList();
        for(int i=0;i<array.length;i++){
        	if(array[i]%2!=0){
        		list1.add(array[i]);
        	}
        }
        for(int i=0;i<array.length;i++){
        	if(array[i]%2==0){
        		list1.add(array[i]);
        	}
        }
        for(int i=0;i<array.length;i++){
        	array[i]=(Integer) list1.get(i);
        }
    }
}
13. 输入一个链表,输出该链表中倒数第k个结点。

public class ListNode {//JAVA中针对链表的定义
    int val;
    ListNode next = null;
    ListNode(int val) {
        this.val = val;
    }
}
public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {//这个可以自己画图理解一下,就是p2先走k格,p1与p2保持k格距离再走,p2停止的时
							//刚好是最后一个节点,p1就是我们要求的倒数的节点
	 if(k<=0) return null;
         ListNode p1 = head;
         ListNode p2 = head;
         //p2向前移动k个节点
         for(int i=0;i<k-1;i++) {
             if(p2==null) return null;
             p2 = p2.next;
         }
         if(p2==null) return null;
         while(p2.next!=null) {
             p1=p1.next;
             p2=p2.next;
         }
         return p1;
    }
}


13. 输入一个链表,反转链表后,输出链表的所有元素。

public class Solution {
    public ListNode ReverseList(ListNode head) {//画图理解,算法笔试必考必会的题目
	if(head==null) return null;
    	ListNode node=head;
    	ListNode pre=null;
    	ListNode lastnode=null;
    	while(node!=null){
    		if(node.next==null){
    			lastnode=node;
    		}
    		ListNode next=node.next;
    		node.next=pre;
    		pre=node;
    		node=next;
    	}
    	return lastnode;
    }
}
14. 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

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


第一部分主要题目是基本的递归算法(斐波那契),数组的操作,栈与队列的认识和使用。

JAVA编写算法虽然时间复杂度较高,时间较c、c++会长一点,但是对于笔者来说具有一定的可读性,理解上也更加容易!


















猜你喜欢

转载自blog.csdn.net/qq_31278903/article/details/71296133