JAVA 剑指offer

1.二维数组中的查找

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

public class Solution {
    /*
    *思路是:数组中的数是有大小顺序的
    选取左下角的元素进行比较
    如果目标元素<左下角元素,往上走
    如果目标元素>左下角元素,往右走
    */
    
    public boolean Find(int target, int [][] array) {
        int i=array.length-1;
        int j=0;
        while(i>=0 && j<=array[0].length-1){
            if(target==array[i][j])
                return true;
            else if(target<array[i][j])
                i--;
            else
                j++;
        }
        return false;
    }
}

2.替换空格

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

public class Solution {
    /*
    思路:先找出一种有多少个空格
    从后往前搜索,将空格变成‘%20’
    */
    public String replaceSpace(StringBuffer str) {
       int num=0;
       for(int i=0;i<str.length();i++){
           if(str.charAt(i)==' ')
               num++;
       }
        int oldIndex=str.length()-1;//原字符串最后的索引
        int newIndex=oldIndex+2*num;//新字符串最后的索引
        int newLen=newIndex+1;//新字符串的长度
        str.setLength(newLen);//为新的字符串申请空间
        for(int i=oldIndex;i>=0;i--){
            if(str.charAt(i)==' '){
                str.setCharAt(newIndex--,'0');
                str.setCharAt(newIndex--,'2');
                str.setCharAt(newIndex--,'%');
            }
            else
                str.setCharAt(newIndex--,str.charAt(i));
        }
        return str.toString();
    }
}

3.从尾到头打印链表

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

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.*;
public class Solution {
    //把链表的值从头到尾加入到栈中,输出栈中的内容及为链表从尾到头的值
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> list=new ArrayList<Integer>();
        if(listNode==null)
            return list;
        Stack<Integer> s=new Stack<Integer>();
        ListNode temp=listNode;
        while(temp!=null){
            s.push(temp.val);
            temp=temp.next;
        }
        while(!s.empty()){//易错:判断栈为空
            list.add(s.pop());
        }
        return list;
    }
}

4.重建二叉树(**)

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

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
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 i=0;
        for(i=0;i<len;i++){
            if(in[i]==root.val) 
                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(i<len-1){  
            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类型。

import java.util.Stack;
/*
思路:用stack1来实现队列的push操作,用stack2来实现队列的pop操作,当stack2为空时,将stack1的数据全部压入stack2,等待队列的pop操作。
*/
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() {
        int re;   
       if(!stack2.empty()){  // 如果栈2不是空的,那么把最上面那个取出来  
           re=stack2.pop();   
       }else{   
               //如果栈2是空的,就把栈1里的数一个个取出来,放到栈2里  
           while(!stack1.empty()){     
                re=stack1.pop();   
                stack2.push(re);   
                             }   
                  //栈2里有数之后,再次把里面的数取出来  
                  if(!stack2.empty()){   
                         re=stack2.pop();   
                   }   
       }   
       return re;   
    }

}

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.length==0) return 0;
        int i=0;
        while(array[i]<=array[i+1]){
            i++;
        }
        return array[i+1];
    }
}

7. 斐波那契数列

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

n<=39

public class Solution {
    /*
    斐波那契数列指的是这样一个数列: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,
    987,1597,2584,4181,6765,10946,17711,28657,46368。

    可以观察到,从第3个数开始,每个数的值都等于前面两个数之和。
    */
    public int Fibonacci(int n) {
        int re[]=new int[n+1];
        if(n==0)return 0;
        else
            if(n==1)return 1;
        else{
            re[0]=0;
            re[1]=1;
            for(int i=2;i<=n;i++){
                re[i]=re[i-2]+re[i-1];
            }
             return re[n];
        }
    }
}

8. 跳台阶

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

public class Solution {
    /*
    *本质是斐波那契数列
    */
    public int JumpFloor(int target) {
        int re[]=new int[target+1];
        if(target==0)return 0;
        else
            if(target==1)return 1;
        else
            if(target==2)return 2;
        else{
            re[1]=1;
            re[2]=2;
            for(int i=3;i<=target;i++)
                re[i]=re[i-1]+re[i-2];
            return re[target];
        }
    }
}

9. 变态跳台阶

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

public class Solution {
    /*
    这个可以用数学来解释
    F(n) = F(n-1)+F(n-2)+...+F(1)
    F(n-1) = F(n-2)+F(n-3)+...+F(1)

    两个式子相减,很容易得出F(n)=2F(n-1)
    */
    public int JumpFloorII(int target) {
        int jump=1;
        if(target==0)return 0;
        else
            if(target==1)return 1;
        else{
            for(int i=2;i<=target;i++)
                jump=jump*2;
            return jump;
        }
    }
           
}

10 矩形覆盖

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

public class Solution {
    /*
    本质斐波那契数列
    从第三项开始,后一项是前两项的和
    */
    public int RectCover(int target) {
        int re[]=new int[target+1];
        if(target==0)return 0;
        else
            if(target==1) return 1;
        else 
            if(target==2)return 2;
        else{
            re[1]=1;
            re[2]=2;
            for(int i=3;i<=target;i++)
                re[i]=re[i-1]+re[i-2];
            return re[target];
        }
    }
}

11. 二进制中1的个数

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

法一:

public class Solution {
    public int NumberOf1(int n) {
        int count=0;
        //有现成的函数可以吧Integer中int型的数转化成二进制的String型
        String str=Integer.toBinaryString(n);
            for(int i=0;i<str.length();i++){
                if (str.charAt(i)=='1')
                    count++;
            }
        return count;
    }
}

法二

public class Solution {
    public int NumberOf1(int n) {
        //因为返回值是int型,4位32个字节,所以可以通过无符号右移,计算每一位是不是1
        int count=0;
        for(int i=0;i<32;i++){
            if((n >>> i & 1)==1)//别忘加()
                count++;
        }
        return count;
    }
}
12.
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值