剑指offer编程整理(一)

1、二维数组中的查找

2、替换空格

3、从头到尾打印链表

4、重建二叉树

5、用两个栈实现队列

6、旋转数组的最小数字

7、斐波那契数列

8、跳台阶

9、变态跳台阶

10、矩形覆盖

11、二进制中1的个数

1、二维数组中的查找

(1)问题描述:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。(2)解题思路:将target与二维数组array第一行最后一个数做比较,如果target大于该行数,则不考虑第一行,相反不考虑最后一列,相等返回true。

(3)代码实现:

public boolean Find(int target,int[][] array){
        if (array==null || array.length<1 ||  array[0].length<1){
            return false;
        }

        int rows = array.length;
        int cols = array[1].length;

        int row = 0;
        int col = cols - 1;

        while (row<rows && col<cols && row>=0 && col>=0){
            if (array[row][col] == target){
                return true;
            }else if (array[row][col] > target){
                col--;
            }else {
                row++;
            }
        }

        return false;
    }

2、替换空格

(1)问题描述:

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

(2)解题思路:

法一:直接使用替换函数

replace的参数是char和CharSequence,即可以支持字符的替换,也支持字符串的替换(CharSequence即字符串序列,也就是字符串);

replaceAll的参数是regex,即基于规则表达式的替换;

相同点:都是全部替换,即把源字符串中的某一字符或字符串全部换成指定的字符或字符串;

不同点:replaceAll支持正则表达式,因此会对参数进行解析(两个参数均是),而replace则不会解析为正则。

注意:“\”在Java中是一个转义字符,所以需要用两个代表一个。例如:\\\\被java转换成\\,\\又被正则表达式转换成\,因此用replaceAll替换“\”为"\\",

就要用replaceAll("\\\\","\\\\\\\\"),而replace则replace("\\","\\\\")。

法二:遍历每一个字符,追加或替换后追加到一个新的字符串中

(3)代码实现:

法一:

 public static String replace(StringBuffer str){
        return str.toString().replaceAll("\\s","%20");
    }
法二:

public static String replaceReplace(StringBuffer str){
        StringBuffer out = new StringBuffer();
        for (int i = 0;i<str.toString().length();i++){
            char b = str.charAt(i);
            if (String.valueOf(b).equals(" ")){
                out.append("%20");
            }else {
                out.append(b);
            }
        }
        return out.toString();
    }

3、从尾到头打印链表

(1)问题描述:

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

链表的定义;

 public class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }

(2)解题思路:

法一:利用栈

法二:递归

法三:依次存入列表,前后交换输出

(3)代码实现:

法一:

public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {

        Stack<Integer> stack = new Stack<Integer>();
        while (listNode!=null){
            stack.push(listNode.val);
            listNode = listNode.next;
        }

        ArrayList<Integer> list = new ArrayList<Integer>();
        while (!stack.isEmpty()){
            list.add(stack.pop());
        }

        return list;
    }

法二:

public ArrayList<Integer> printList(ListNode listNode){
        ArrayList<Integer> list = new ArrayList<Integer>();
        ListNode node = listNode;
        if (node != null){
            if (node.next != null){
                list = printList(node);
            }

            list.add(node.val);
        }

        return list;
    }
法三:

public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> a = new ArrayList<Integer>();  
        ListNode temp = listNode;  
        while(temp != null){  
            a.add(new Integer(temp.val));  
            temp = temp.next;  
        }  
        Integer b ;  
        for(int i=0; i<a.size()/2;i++){  
            b = a.get(i);  
            a.set(i, a.get(a.size()-i-1));  
            a.set(a.size()-i-1,b);  
        }  
        return a;  
    }

4、重建二叉树

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

前序遍历第一个数字是根节点;

在中序遍历中找到根节点,该节点的左边是左子树,右边是右子树;

左右子树递归遍历。

(3)代码实现:

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、用两个栈实现队列

(1)问题描述:

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

(2)解题思路:

将所有数依次入栈;

依次出栈并入入另一个栈;

再次出栈即可。

(3)代码实现:

public class QueueImplementByTwoStacks {  
              
      Stack<Integer> a=new Stack<Integer>();   
      Stack<Integer> b=new Stack<Integer>();  
      public void add(int num){  
          a.push(num);  
      }  
      public int pop(){  
          if(!b.empty()){  
              return b.pop();  
          }  
          else{  
              while(!a.empty()){  
                  b.push(a.pop());  
              }  
              return b.pop();  
          }  
      }  

6、旋转数组的最小数字

(1)问题描述:

把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。 例如

数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。

(2)解题思路:

旋转之后的数组可划分成两个有序的子数组,前面子数组的大小都大于后面子数组中的元素,最小的元素就是两个子数组的分界线。

优化:用二分法。

(3)代码实现:

public int minNumberInRotateArray(int [] array) {
 
         
                if(array.length==0){
            return 0;
        }
        if(array.length==1){
            return array[0];
        }
 
        for(int i=0;i<array.length-1;i++){
            if(array[i]>array[i+1]){
                return array[i+1];
            }else{
 
                if(i==array.length-2){
                    return array[0];
                }
 
 
            }
        }
 
 
        return 0;
    }
优化:

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

7、斐波那契数列

(1)问题描述:

要求输入一个整数n,输出斐波那契数列的第n项。n<=39

(2)解题思路:

法一:递归;

法二:空间换时间;

法三:迭代。

(3)代码实现:

法一:

public int Fibonacci1 (int n){
        if (n == 0 || n==1){
            return n;
        }else {
            return Fibonacci1(n-1) + Fibonacci1(n-2);
        }
    }

法二:

public int Fibonacci2(int n){
        int[] record = new int[n+1];

        if (n == 0 || n== 1){
            return n;
        }
        record[0] = 0;
        record[1] = 1;
        for (int i = 2;i<n+1;i++){
            record[i] = record[i-1] + record[i-2];
        }

        return record[n];

    }
法三:

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

8、跳台阶

(1)问题描述:

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

(2)解题思路:

找规律,斐波那契数列的变体;

(3)代码实现:

public static int jumpFloor(int n){
        if (n <= 0){
            return 0;
        } else if (n==1 || n==2){
            return n;
        }else {
          return jumpFloor(n-1) + jumpFloor(n-2);
        }

    }

9、变态跳台阶

(1)问题描述:

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

(2)解题思路:

第一步有n种跳法:跳1级、跳2级、...跳n级;

跳1级,剩下n-1级,则剩下跳法是f(n-1);

跳2级,剩下n-2级,则剩下跳法是f(n-2);

所以f(n)=f(n-1)+f(n-2)+...+f(1)

因为f(n-1)=f(n-2)+f(n-3)+...+f(1)

所以f(n)=2*f(n-1)

(3)代码实现:

public static int jumpFloor(int n){
        if (n <= 0){
            return 0;
        } else if (n==1 || n==2){
            return n;
        }else {
            return 2*jumpFloor(n-1);
        }

    }

10、矩形覆盖

(1)问题描述:

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

(2)解题思路:

同跳台阶,画图归纳找规律

(3)代码实现:

11、二进制中1的个数

(1)问题描述:

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

(2)解题思路:

法一:将二进制转换为String,将0全部用替换为"",然后返回String长度;

法二:将n与(n-1)相与,会将n最右边的1去掉。

例如:n=10 1010&1001=1000 --> 1000&0111=0000;两次,即10的二进制数中有两个1。

(3)代码实现:

法一:

public static int NumberOf1(int n) {
        return Integer.toBinaryString(n).replaceAll("0","").length();
    }

法二:

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




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值