剑指offer刷题

一些链接

JAVA版本全解

https://www.nowcoder.com/discuss/198840?type=1

数据结构

JZ1 二维数组中的查找

描述

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

[

[1,2,8,9],
[2,4,9,12],
[4,7,10,13],
[6,8,11,15]
]

给定 target = 7,返回 true。

给定 target = 3,返回 false。

0 <= array.length <= 500
0 <= array[0].length <= 500

结题思路

  • 参考剑指offer

public class Solution {
    public boolean Find(int target, int [][] array) {
        int line=array.length-1,row=array[0].length-1;
        int i=0,j=row;//最开始设置为右上角坐标
        while(true)
        {
            if(i>line||i<0||j>row||j<0)
                return false;
            if(array[i][j]==target)
                return true;
            else if(array[i][j]>target)//如果比目标值大,则减去该列,即右上角坐标j-1
                j--;
            else if(array[i][j]<target)//如果比目标值小,则减去该行,即右上角坐标i+1
                i++;
        }
        
    }
}

JZ2 替换空格

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vCP0pr5l-1639377419343)(剑指offer刷题.assets/image-20210817105146611.png)]

剑指offer官方思路是采用双指针法

时间复杂度: O(n)

空间复杂度: O(1)

但是需要StringBuffer类

public String replaceSpace(StringBuffer str) {
    int P1 = str.length() - 1;
    for (int i = 0; i <= P1; i++)
        if (str.charAt(i) == ' ')
            str.append("  ");

    int P2 = str.length() - 1;
    while (P1 >= 0 && P2 > P1) {
        char c = str.charAt(P1--);
        if (c == ' ') {
            str.setCharAt(P2--, '0');
            str.setCharAt(P2--, '2');
            str.setCharAt(P2--, '%');
        } else {
            str.setCharAt(P2--, c);
        }
    }
    return str.toString();
}

空间复杂度为O(N)

直接创建一个数组进来改

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @return string字符串
     */
    public String replaceSpace (String s) {
        // write code here
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ' ') {
                sb.append("%20");
            } else {
                sb.append(s.charAt(i));
            }
        }
        return sb.toString();
    }
}

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @return string字符串
     */
    public String replaceSpace (String s) {
       return s.replace(" ","%20");
    }
}

JZ3 从尾到头打印链表

Java中ArrayList类

传送门

Java Stack 类 直接查找java api文档

使用栈的方式,即不改变链表结构

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.ArrayList;
import java.util.Stack;
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<Integer> re = new ArrayList<>();//创建一个动态数组
        while(stack.empty()!=true)
        {
            re.add(stack.pop());//添加进数组
        }
        return re;
        
    }
}

递归本质上是栈,使用递归方式

但是测试结果栈溢出,所以是作为一个思路参考

/**
*    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) {
        ArrayList<Integer> re =new ArrayList<Integer>();
        if(listNode !=null)
        {
            re.addAll(printListFromTailToHead(listNode.next));
            re.add(listNode.val);
        }
        return re;
    }
}

JZ4 重建二叉树

剑指offer思路

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.*;
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] vin) {
        if (pre.length == 0 || vin.length == 0) {
            return null;
        }
        TreeNode root = new TreeNode(pre[0]);
        // 在中序中找到前序的根
        for (int i = 0; i < vin.length; i++) {
            if (vin[i] == pre[0]) {
                // 左子树,注意 copyOfRange 函数,左闭右开
                root.left = reConstructBinaryTree(Arrays.copyOfRange(pre, 1, i + 1), Arrays.copyOfRange(vin, 0, i));
                // 右子树,注意 copyOfRange 函数,左闭右开
                root.right = reConstructBinaryTree(Arrays.copyOfRange(pre, i + 1, pre.length), Arrays.copyOfRange(vin, i + 1, vin.length));
                break;
            }
        }
        return root;
    }
}

JZ5 用两个栈实现队列

书上思路

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.empty()==true)//删除从栈2删除,必须保证不为空
        {
            while(!stack1.empty())
                stack2.push(stack1.pop());
        }
        return stack2.pop();
    }
}

算法和数据操作

斐波那契数列

public class Solution {
    public int Fibonacci(int n) {
        if (n <= 1)
            return n;
        int[] fib = new int[n + 1];
        fib[1] = 1;
        for (int i = 2; i <= n; i++)
            fib[i] = fib[i - 1] + fib[i - 2];
        return fib[n];
    }
    
}

跳台阶问题

其实就是上面斐波那契数列的变种

从后面考虑,跳到第N阶有两种跳法,一种是跳一步,一种是跳两步,所以跳法为n-1的跳法+n-2时候的跳法

public class Solution {
    public int jumpFloor(int target) {
        if(target<=2)
            return target;
        int[] fib = new int[target];
        fib[0]=1;
        fib[1]=2;
        for (int i=2;i<target;i++)
            fib[i]=fib[i-1]+fib[i-2];
        return fib[target-1];
    }
}

注意跳台阶的两个变种问题

跳台阶拓展

public class Solution {
    public int jumpFloorII(int target) {
        if(target==0||target==1)
            return 1;
        int bushu=1;
        for(int i=1;i<target;i++)
        {
            bushu=bushu*2;
        }
        return bushu;
    }
}

矩阵中的路径

https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/

https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/solution/mian-shi-ti-12-ju-zhen-zhong-de-lu-jing-shen-du-yo/

class Solution {
    public boolean exist(char[][] board, String word) {
        char[] words = word.toCharArray();
        for(int i = 0; i < board.length; i++) {
            for(int j = 0; j < board[0].length; j++) {
                if(dfs(board, words, i, j, 0)) return true;
            }
        }
        return false;
    }
    boolean dfs(char[][] board, char[] word, int i, int j, int k) {
        if(i >= board.length || i < 0 || j >= board[0].length || j < 0 || board[i][j] != word[k]) return false;
        if(k == word.length - 1) return true;
        board[i][j] = '\0';
        boolean res = dfs(board, word, i + 1, j, k + 1) || dfs(board, word, i - 1, j, k + 1) || 
                      dfs(board, word, i, j + 1, k + 1) || dfs(board, word, i , j - 1, k + 1);
        board[i][j] = word[k];
        return res;
    }
}

机器人的运动范围

官方解答

https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof/solution/ji-qi-ren-de-yun-dong-fan-wei-by-leetcode-solution/

dfs解法

class Solution {
    public int movingCount(int m, int n, int k) {
        boolean[][] visit = new boolean[m][n];
        return dfs(0,0,m,n,k,visit);
    }
    
    public int dfs(int i,int j,int m,int n,int k,boolean[][] visit)
    {
        if(i>=m||j>=n||k<getsum(i)+getsum(j)||visit[i][j])
            return 0;
        visit[i][j]=true;
        
        return 1+dfs(i+1,j,m,n,k,visit)+dfs(i,j+1,m,n,k,visit);
    }
    private int getsum(int a)
    {
        int sum=0;
        while(a>0)
        {
            sum+=a%10;
            a=a/10;
        }
        return sum;
    }

}

广度优先搜索

class Solution {
    public int movingCount(int m, int n, int k) {
        if (k == 0)
            return 1;
        Queue<int[]> queue = new LinkedList<int[]>();

        int[] dx = {0,1};
        int[] dy = {1,0};
        boolean[][] vis = new boolean[m][n];
        queue.offer(new int[]{0,0});
        vis[0][0]=true;
        int cnt=1;

        while(!queue.isEmpty())
        {
            int[] cell = queue.poll();
            int x=cell[0];
            int y=cell[1];

            for(int i=0;i<2;i++)
            {
                int tx=x+dx[i];
                int ty=y+dy[i];
                if(tx>=m||ty>=n||getsum(tx)+getsum(ty)>k||vis[tx][ty])
                    continue;
                queue.offer(new int[]{tx,ty});
                vis[tx][ty]=true;
                cnt++;     
            }
        }
        
        return cnt;
    }

    private int getsum(int a)
    {
        int sum=0;
        while(a>0)
        {
            sum+=a%10;
            a=a/10;
        }
        return sum;
    }    
}

剪绳子

使用动态规划法

public class Solution {
    public int cutRope(int target) {
        int[] shuzu = new int[target+1];
        shuzu[1]=1;shuzu[2]=2;shuzu[3]=3;
        if(target<2)
            return 0;
        if(target==3)
            return 2;
        
        for(int i=4;i<=target;i++)
        {
            int max=0;
            for(int j=1;j<=i/2;j++)
                if(shuzu[j]*shuzu[i-j]>max)
                    max=shuzu[j]*shuzu[i-j];
            shuzu[i]=max;
        }
        return shuzu[target];
        
    }
}

2进制中1的个数

关于移位运算和算术运算的速度比较

https://blog.csdn.net/adgarshi/article/details/113839730

注意这道题引起死循环的原因

这个做法是在死循环上进行的改进,原先是移动n,现在改成移动flag

public class Solution {
    public int NumberOf1(int n) {
        int cnt=0;
        int flag=1;
        while(flag!=0)
        {
            if((flag & n)!=0)
                cnt++;
            flag=flag<<1;
        }
        return cnt;
    }
}

利用把一个整数减去1之后再和原来的整数做位于运算,得到的结果相当于把整数的二进制表示中最右边的1变成0,这个性质进行解题

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

数值的整数次方

这道题目就是考虑的情况要全,要考虑指数为负数情况,底数情况

做乘法的时候用幂次优化其乘法

public class Solution {
    public double Power(double base, int exponent) {
        if(exponent==0)
            return 1;
        if(exponent==1)
            return base;
        boolean flag = false;
        if(exponent<0)
        {
            exponent=-exponent;
            flag = true;
        }
        double result=Power(base,exponent>>1);
        result *= result;
        if(exponent %2 == 1)
            result *= base;
        if (flag == true)
            result = 1/result;
    
        return result;
  }
}

,要考虑指数为负数情况,底数情况

做乘法的时候用幂次优化其乘法

public class Solution {
    public double Power(double base, int exponent) {
        if(exponent==0)
            return 1;
        if(exponent==1)
            return base;
        boolean flag = false;
        if(exponent<0)
        {
            exponent=-exponent;
            flag = true;
        }
        double result=Power(base,exponent>>1);
        result *= result;
        if(exponent %2 == 1)
            result *= base;
        if (flag == true)
            result = 1/result;
    
        return result;
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王蒟蒻

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值