剑指Offer/1-10


1. 二维数组中的查找

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

解题思路:
每次选取矩阵右上角的元素 array[i][j] 与target进行比较。
当target小于元素 array[i][j] 时,由于此列向下递增,那么此列一定不存在符合题意的数,排除,即 j–;
当target大于元素 array[i][j] 时,由于此行向左递减,那么此行一定不存在符合题意的数,排除,即 i++;

public class Solution {
    public boolean Find(int target, int [][] array) {
        //方法1:暴力方法
//         if(array.length == 0)
//             return false;
//         for(int i = 0; i < array.length; i++){
//             for(int j=0; j < array[i].length; j++){
//                 if(target == array[i][j])
//                     return true;
//             }
//         }
//         return false;
 
        //方法2:采用二分查找的方式,把二分值定在右上角
        int i = 0;
        int j = array[i].length-1;
        while(i<array.length && j>=0){
            if(array[i][j] > target){
                j--;
            }else if(array[i][j] < target){
                i++;
            }else{
                return true;
            }
        }        return false;
    }
}

2. 替换空格

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

解题思路:
创建一个新的字符串,从前往后遍历原字符串,遇到字母添加原字母,遇到空格添加“%20”,最后输出新字符串。

public class Solution {
    public String replaceSpace(StringBuffer str) {
//         //方法1:调用内置函数
//         return str.toString().replace(" ","%20");
        
        //方法2:当遇到 " ",就追加 "%20",否则遇到什么追加什么
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < str.length(); i++){
            char c = str.charAt(i);
            if(c == ' ')
                sb.append("%20");
            else
                sb.append(c);
        }
        return sb.toString();
    }
}

3. 从尾到头打印链表

题目描述:
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。

解题思路:
方法1:利用 ArraList 的 add(index, value) 方法在遍历链表的同时将每一次遍历得到的数据插入到 List 的头部
方法2:采用头插法翻转链表,然后重新遍历反转后的链表。

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
//         //方法1:非递归,利用ArrayList中 add(index, value) 方法
//         ArrayList<Integer> list = new ArrayList<>();
//         ListNode temp = listNode;
//         while(temp != null){
//             list.add(0,temp.val);//指定位置插入元素
//             temp = temp.next;
//         }
//         return list;
        
        //方法1:头插法
        ArrayList<Integer> list =  new ArrayList<>();
        ListNode newHead = new ListNode(-1);
        newHead.next = null;
        while(listNode != null){
            ListNode next = listNode.next;
            listNode.next = newHead.next;
            newHead.next = listNode;
            listNode = next;
        }
        ListNode next = newHead.next;
        while(next != null){
            list.add(next.val);
            next = next.next;
        }
        return list;
    }
}

4. 重建二叉树

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

解题思路:
1.根据前序序列第一个结点确定根结点
2.根据根结点在中序序列中的位置分割出左右两个子序列
3.对左子树和右子树分别递归使用同样的方法继续分解

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.Arrays;
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 < in.length; i++){
            if(in[i] == pre[0]){
                //copyOfRange 函数,左闭右开
                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类型。

解题思路:
push操作就直接往stack1中push;
pop操作需要分类一下:如果stack2为空,那么需要将stack1中的数据转移到stack2中,然后在对stack2进行pop,如果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() {
        if(stack2.isEmpty()){
            while(!stack1.isEmpty()){
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
}

6. 旋转数组的最小数组

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

解题思路:
二分查找的变种。这种二分查找难就难在,arr[mid]跟谁比。
我们的目的是:当进行一次比较时,一定能够确定答案在mid的某一侧。一次比较为 arr[mid]跟谁比的问题。
一般的比较原则有:

如果有目标值target,那么直接让arr[mid] 和 target 比较即可。
如果没有目标值,一般可以考虑 端点
这里我们把target 看作是右端点,来进行分析,那就要分析以下三种情况,看是否可以达到上述的目标(左端点会查找失败)。
在这里插入图片描述
在这里插入图片描述

令low和high分别指向数组的开始和结束位置,然后计算mid位置,然后与high处的值进行比较,有三种情况:
(1)array[high] < array[mid],让low = mid + 1
(2)array[high] > array[mid],让high = mid
(3)否则,high–

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

正常二分法的代码为:

public static int BinarySearch(int[] array,int key){
		int low = 0;
		int high = arr.length - 1;
		int middle;	
				
		if(key < array[low] || key > array[high] || low > high){
			return -1;				
		}
		
		while(low <= high){
			middle = (low + high) / 2;
			if(array[middle] > key){
				//比关键字大则关键字在左区域
				high = middle - 1;
			}else if(array[middle] < key){
				//比关键字小则关键字在右区域
				low = middle + 1;
			}else{
				return middle;
			}
		}	
			
		return -1;		//最后仍然没有找到,则返回-1
	}

7. 斐波那契数列

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

解题思路:
F(0) = 0;
F(1) = 1;
F(2) = F(0)+F(1) = 1;
F(3) = F(1)+F(2) = 2;
F(4) = F(2)+F(3) = 3;

F(n) = F(n-2)+F(n-1)

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

8. 跳台阶

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

解题思路:
假设 F[i]表示在第 i 个台阶上可能的方法数。逆向思维。
如果我从第n个台阶进行下台阶,下一步有2中可能,一种走到第n-1个台阶,一种是走到第n-2个台阶。所以 F[n] = F[n-1] + F[n-2].

显然初始条件 F[0] = F[1] = 1

public class Solution {
    public int JumpFloor(int target) {
        //f[n] = f[n-1] + f[n-2]
        if(target == 1 || target == 2){
            return target;
        }
        int a = 1;
        int b = 2;
        for(int i = 3; i <= target; i++){
            b = a + b;
            a = b - a;
        }
        return b;
    }
}

9. 变态跳台阶

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

解题思路:
F[i] 表示 当前跳道第 i 个台阶的方法数。
假设现在已经跳到了第 n 个台阶,那么前一步可以从哪些台阶到达呢?

如果上一步跳 1 步到达第 n 个台阶,说明上一步在第 n-1 个台阶。已知跳到第n-1个台阶的方法数为 F[n-1]

如果上一步跳 2 步到达第 n 个台阶,说明上一步在第 n-2 个台阶。已知跳到第n-2个台阶的方法数为 F[n-2]

… …

如果上一步跳 n 步到达第 n 个台阶,说明上一步在第 0 个台阶。已知跳到 第0个台阶的方法数为f[0]

那么总的方法数就是所有可能的和。也就是 F[n] = F[n-1] + F[n-2] + … + F[0]

显然初始条件 F[0] = F[1] = 1

public class Solution {
    public int JumpFloorII(int target) {
//         if(target == 0 || target == 1){
//             return 1;
//         }
//         return (int)Math.pow(2, target-1);

        return 1<<(target-1);
    }
}

10. 矩形覆盖

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

解题思路:
F[n]表示 2*n 大矩阵的方法数。
可以得出:F[n] = F[n-1] + F[n-2]
初始条件 F[1] = 1, F[2] =2

public class Solution {
    public int RectCover(int target) {
        if(target <= 2){
            return target;
        }
        int a = 1;
        int b = 2;
        for (int i=3; i <= target; i++){
            b = a + b;
            a = b - a;
        }
        return b;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值