Java 剑指Offer 题目分类汇总

文章目录

  • 1、数组
    • 01 二维数组中的查找
    • 06 旋转数组的最小数字
    • 13 调整数组顺序使奇数位于偶数前面
    • 28 数组中出现次数超过一半的数
    • 29 最小的K个数
    • 30 连续子数组的最大和
    • 32 把数组排成最小的数
    • 37 数字在排序数组中的个数
    • 50 数组中的重复数字
    • 51 构建乘积数组
    • 65 矩阵中的路径
    • 66 机器人的运动范围
  • 2、字符串
    • 02 替换空格
    • 19 顺时针打印矩阵
    • 27 字符串排列
    • 34 第一个只出现一次的字符
    • 35 数组中的逆序对
    • 43 左旋转字符串
    • 44 翻转单词顺序
    • 45 扑克牌顺子
    • 49 把字符串转换为整数
    • 52 正则表达式的匹配
    • 53 表示数值的字符串
    • 54 字符流中第一个不重复的字符
  • 3、链表
    • 03 从尾到头打印链表
    • 14 链表中倒数第K个节点
    • 15 反转链表
    • 16 合并两个排序的链表
    • 25 复杂链表的复制
    • 36 两个链表的第一个公共节点
    • 46 孩子们的游戏(圆圈中最后剩下的数)
    • 55 链表中环的入口节点
    • 56 删除链表中的重复值
  • 4、树
    • 04 重建二叉树
    • 17 树的子结构
    • 18 二叉树的镜像
    • 22 从上往下打印二叉树
    • 23 二叉搜索树树的后序遍历
    • 24 二叉树中和为某一值的路径
    • 26 二叉搜索树与双向列表
    • 38 二叉树的深度
    • 39 平衡二叉树
    • 57 二叉树的下一个节点
    • 58 对称的二叉树
    • 59 按之字形顺序打印二叉树
    • 60 把二叉树打印成多行
    • 61 序列化二叉树
    • 62 二叉搜索树的第k个节点
  • 5、位运算
    • 11 二进制中1的个数
    • 40 数组中只出现一次的数字
  • 6、栈和队列
    • 05 用两个栈实现队列
    • 20 包含min函数的栈
    • 21 栈的压入、弹出序列
    • 64 滑动窗口的最大值
  • 7、其他
    • 07 斐波那契数列
    • 08 跳台阶
    • 09 变态跳台阶
    • 10 矩形覆盖
    • 12 数值的整数次方
    • 31 整数1出现的次数
    • 33 丑数
    • 41 和为S的连续正数序列
    • 42 和为S的两个数
    • 47 求 1+2+3+...+n
    • 48 不用加减乘除做加法
    • 63 数据流中的中位数
    • 76 剪绳子

1、数组

01 二维数组中的查找

标签
查找、数组、字符串
要求
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
思路
目标为target,从数组左上角开始检索,a[i][j]>target则往左走,a[i][j] 代码

public class Solution {
    public boolean Find(int target, int [][] array) {
        if(array.length == 0 || array[0].length == 0  )
            return false;
        int rows = array.length-1;
        int cols = array[0].length-1;
        int i = 0;
        int j = cols;
        while(i <= rows && j >= 0)
        {
            if(array[i][j] < target)
            {
                i++;
            }else if(array[i][j] > target)
            {
                j--;
            }else{
                return true;
            }
        }
        return false;
    }
}

06 旋转数组的最小数字

标签
数组、二分查找
要求
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。
例如数组 {3,4,5,1,2} 为 {1,2,3,4,5} 的一个旋转,该数组的最小值为 1。
NOTE:给出的所有元素都大于 0,
思路
1、若arr[L] 2、否则,证明数组里有循环的部分,二分法查mid,若arr[L]>arr[M]则最小值只会出现在L-M上(因为此时L-M是循环部分)
3、否则,最小值只会在M-R上
备注
L 代码

import java.util.ArrayList;
public class Solution {
    public int minNumberInRotateArray(int [] array) {
        
        if(array[0] < array[array.length-1])//证明数组有序
        {
            return array[0];
        }else{//已经经历过循环
            int l = 0;
            int r = array.length-1;
            while(l+1!=r)
            {
                 int mid =l+(r-l)/2;//取中间值
                if(array[l] < array[mid] )//证明在右边
                {
                    l=mid;
                }else if(array[r] > array[mid]){
                    r=mid;
                }else
                    l++;               
            }
            return array[r];
        }
    }
}

13 调整数组顺序使奇数位于偶数前面

标签
数组
要求
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
思路
备注
代码

import java.util.ArrayList;
public class Solution {
   public void reOrderArray(int [] array) {
       ArrayList odd = new ArrayList<>();
       ArrayList even = new ArrayList<>();
       for(int i=0;i

28 数组中出现次数超过一半的数

标签
数组
要求
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为 9 的数组 {1,2,3,2,2,2,5,4,2}。由于数字 2 在数组中出现了 5 次,超过数组长度的一半,因此输出 2。如果不存在则输出 0。
思路
使用一个计数 count = 1,当前数 num, 每当数组中数和当前数 num 相同,那么 count 就加 1,不相同就减一,因为是找出现的数超过数组的长度的一半,所以最后如果有出现的数超过数组长度一半的,count 肯定是大于 0 的数
找到后还要从头遍历一遍这个数出现的次数,原因开备注
备注
如果count大于0说明有可能存在这样的数,是出现次数大于数组的一半的
还有一种可能是最后刚好一个数连续出现了2次,导致count>0
代码

public class Solution {
   public int MoreThanHalfNum_Solution(int [] array) {
       if(array.length == 0)
           return 0;
       int count = 1;
       int number = array[0];
       for(int i=1;i 0)
       {//如果count大于0说明有可能存在这样的数,是出现次数大于数组的一半的
        //还有一种可能是最后刚好一个数连续出现了2次,导致count>0
           count = 0;
           for(int i=0;i array.length/2)
               return number;//出现超过一半
       }
       return 0;
   }
}

29 最小的K个数

标签
数组、堆
要求
输入 n 个整数,找出其中最小的 K 个数。例如输入 4,5,1,6,2,7,3,8 这 8 个数字,则最小的 4 个数字是 1,2,3,4,。
思路
建立一个容量为k的大顶堆,一开始是先是0 - k-1个进堆,调整完(0位为最大)时,堆后移以1-k建堆,接下来1弹出,如此类推,到n时堆内的数为最小的k个数
备注
这里采用的是优先队列模拟最大堆(效率快一点),要重写comparable
代码

import java.util.*;
public class Solution {
   public ArrayList GetLeastNumbers_Solution(int [] input, int k) {
       ArrayList resultList = new ArrayList<>();
       if(k > input.length || k<=0)
           return resultList;
       //使用优先级队列建堆,优先级队列默认是最小堆,所以要重写比较器
       PriorityQueue maxHeap = new PriorityQueue<>(new Comparator(){
           public int compare(Integer o1,Integer o2){
               return o2.compareTo(o1);
           }
       }
       );
       for(int i=0;i input[i])
               {//堆顶的数比数组当前的数大,那么就堆顶出堆
                   maxHeap.poll();
                   maxHeap.add(input[i]);//把当前数加入堆中
               }
           }
       }
       while(maxHeap.isEmpty() != true)
           resultList.add(maxHeap.poll());//把堆中的数出堆添加到结果数组中
       return resultList;
   }
}

30 连续子数组的最大和

标签
数组
要求
HZ 偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢?例如:{6,-3,-2,7,-15,1,2,2}, 连续子向量的最大和为 8 (从第 0 个开始,到第 3 个为止)。给一个数组,返回它的最大连续子序列的和,你会不会被他忽悠住?(子向量的长度至少是 1)
思路
从0开始,从左往右依次加入,一开始加6,然后加-3,等等,若加入一个数后sum<新加入的数,此时最大和为这个新加入的数(舍弃前面的)
备注
代码

public class Solution {
    public int FindGreatestSumOfSubArray(int[] array) {
        if(array == null || array.length == 0)return 0;
        
        int i = 0;//用于遍历
        int len = array.length;
        int sum = 0;
        int max = array[0];
        
        while (i< len){
            sum += array[i];
            if (sum < array[i]) sum = array[i];
            if (sum > max)max=sum;
            i++;
        }
        return max;
    }
}

32 把数组排成最小的数

标签
数组
要求
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组 {3,32,321},则打印出这三个数字能排成的最小数字为 321323。
思路
定义新排序,A+B>B+A 则A小于B
备注
代码

import java.util.*;

public class Solution {
public String PrintMinNumber(int [] numbers) {
    if(numbers == null || numbers.length == 0){
        return "";
    }
    List list = new ArrayList();
    for(int num : numbers){
        list.add(num);
    }
    Collections.sort(list, new MyComparator());
    StringBuilder res = new StringBuilder("");
    for(Integer integer : list){
        res.append(integer.toString());
    }
    return res.toString();
}


}
class MyComparator implements Comparator{
    public int compare(Integer i1, Integer i2){
        String s1 = i1.toString() + i2.toString();
        String s2 = i2.toString() + i1.toString();
        return Integer.parseInt(s1) - Integer.parseInt(s2);
    }
}

37 数字在排序数组中的个数

标签
二分查找、数组
要求
统计一个数字在排序数组中出现的次数。
思路
1、暴力办法直接遍历
优解
1、因为排序树组,同一个数的个数可视为该数最右位置-该数最左位置+1
2、用两次二分查找分别查找该数字的最左和最右位置,找到是只是记录位置,继续二分查找知道start=end
备注
代码

public class Solution {
    public int GetNumberOfK(int [] array , int k) {
        int leftIndex = -1,start=0,end=array.length-1,rightIndex=-1;
       while(start <= end)
       {
           int mid = (start+end)/2;
           if(array[mid] > k)
           {
               end = mid-1;
           }else if(array[mid] < k){
               start = mid+1;
           }else{
               leftIndex = mid;
               end = mid-1;
           }
       }
       start = 0;
       end = array.length-1;
       while(start <= end)
       {
           int mid = (start+end)/2;
           if(array[mid] > k)
           {
               end = mid-1;
           }else if(array[mid] < k){
               start = mid+1;
           }else{
               rightIndex = mid;
               start = mid+1;
           }
       }
       if(array.length == 0 || rightIndex == -1)
           return 0;
       return rightIndex-leftIndex+1;
    }
}

50 数组中的重复数字

标签
数组
要求
在一个长度为 n 的数组里的所有数字都在 0 到 n-1 的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为 7 的数组 {2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字 2。
思路
1、简单的用hash表也可以
2、对于这种数组元素在 [0, n-1] 范围内的问题,可以将值为 i 的元素调整到第 i 个位置上进行求解。
以 (2, 3, 1, 0, 2, 5) 为例,遍历到位置 4 时,该位置上的数为 2,但是第 2 个位置上已经有一个 2 的值了,因此可以知道 2 重复。
备注
代码

public class Solution {

   // public static void main(String[] args) {

   //     int[] nums = new int[]{2, 3, 1, 0, 2, 5};
   //     int n = nums.length;
   //     int[] dup = new int[1];
   //     boolean flag = duplicate(nums, n, dup);
   //     System.out.println(flag + "," + dup[0]);
   // }

    public static void swap(int nums[], int m, int n) {

        int temp = nums[m];
        nums[m] = nums[n];
        nums[n] = temp;
    }

    public static boolean duplicate(int nums[], int length, int[] duplication) {

        if (nums == null || length <= 0) {
            return false;
        }

        for (int i = 0; i < nums.length; i++) {
            while (nums[i] != i) {
                if (nums[i] == nums[nums[i]]) {
                    duplication[0] = nums[i];
                    return true;
                }
                swap(nums, nums[i], i);
            }
        }
        return false;
    }
}

51 构建乘积数组

标签
数组
要求
给定一个数组 A [0,1,…,n-1], 请构建一个数组 B [0,1,…,n-1], 其中 B 中的元素 B [i]=A [0]* A [1] A [i-1]* A [i+1]*…*A [n-1]。不能使用除法。
思路
思路:题目要求B的i个元素等于A中除了i个元素所以元素乘积
画图可知,氛可以氛围上半部分和下半部分计算
备注
代码


public class Solution {
    public int[] multiply(int[] A) {
        int length = A.length;
        int[] B = new int[length];
        if(length != 0 ){
            B[0] = 1;
            //计算下三角连乘
            for(int i = 1; i < length; i++){
                B[i] = B[i-1] * A[i-1];
            }
            int temp = 1;
            //计算上三角
            for(int j = length-2; j >= 0; j--){
                temp *= A[j+1];
                B[j] *= temp;
            }
        }
        return B;
    }
}

65 矩阵中的路径

标签
数组、搜索、匹配
要求
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。
思路
用回溯的方法就可以了,不断尝试,主要返回false的条件即可
备注
一个递归里不满足的话要将visit设置回false;
代码

public class Solution {
    public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
    {
        if(matrix==null || rows<=0 || cols<=0 || str==null){
            return false;
        }
        if(str.length==0){
            return true;
        }
        boolean[] visited = new boolean[matrix.length];
        for(int i=0; i=rows || col<0 || col>=cols || str[k]!=matrix[row*cols+col] || visited[row*cols+col]){
            return false;
        }
        if(k==str.length-1){
            return true;
        }
        visited[row*cols+col] = true;
        if(findPath(matrix, row+1, col, rows, cols, k+1, visited, str) || findPath(matrix, row, col+1, rows, cols, k+1, visited, str) || findPath(matrix, row-1, col, rows, cols, k+1, visited, str) || findPath(matrix, row, col-1, rows, cols, k+1, visited, str)){
            return true;
        }
        visited[row*cols+col] = false;
        return false;
    }
}

66 机器人的运动范围

标签
数组、回溯
要求
地上有一个 m 行和 n 列的方格。一个机器人从坐标 0,0 的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于 k 的格子。 例如,当 k 为 18 时,机器人能够进入方格(35,37),因为 3+5+3+7 = 18。但是,它不能进入方格(35,38),因为 3+5+3+8 = 19。请问该机器人能够达到多少个格子?
思路
1、一直回溯即可,当(i,j)可以时,将return(1+ 上下左右的count),注意每成功判定成功一次,数组对应位置的标志要记为false,以防重复计算
2、计算值可以用取余相加来获得
备注
代码

public class Solution {

	public int movingCount(int threshold,int rows,int cols){
		boolean[] visted = new boolean[rows*cols];
		for(int i = 0; i < visted.length; i++)
			visted[i] = false;
		
		int count = movingCountCore(threshold,rows,cols,0,0,visted);
		return count;
	}
	
	/*
	递归回溯方法:
	@param threshold	约束值
	@param rows			方格行数
	@param cols			方格列数
	@param row			当前处理的行号
	@param col			当前处理的列号
	@param visted		访问标记数组
	@return				最多可走的方格
	*/
	public int movingCountCore(int threshold,int rows,int cols,int row,int col,boolean[] visted){
		int count = 0;
		if(check(threshold,rows,cols,row,col,visted)){
			visted[row*cols + col] = true;
			
			count = 1 + movingCountCore(threshold,rows,cols,row - 1,col,visted) +
					movingCountCore(threshold,rows,cols,row,col - 1,visted) + 
					movingCountCore(threshold,rows,cols,row + 1,col,visted) +
					movingCountCore(threshold,rows,cols,row,col + 1,visted);
		}
		return count;
	}
	
	boolean check(int threshold,int rows,int cols,int row,int col,boolean[] visted){
		if(row >= 0 && row < rows && col >= 0 && col < cols
				&& (getDigitSum(row) + getDigitSum(col) <= threshold)
				&& !visted[row* cols + col])
			return true;
		return false;
	}
	
	/*
	一个数字的位数之和
	@param	number 数字
	@return 数字的位数之和
	*/
	public int getDigitSum(int number){
		int sum = 0;
		while(number > 0){
			sum += number%10;
			number /= 10;
		}
		return sum;
	}

}

2、字符串

02 替换空格

标签
字符串、替换、数组
要求
请实现一个函数,将一个字符串中的每个空格替换成 “%20”。例如,当字符串为 We Are Happy. 则经过替换之后的字符串为 We%20Are%20Happy。
思路
"%20"比空格多占两个位置
1、先检索空格数量
2、创造长度为字符串长度+2*空格数的字符数组
备注
1、检索前要先将字符串.toCharArray();
2、返回时要return new String(newStrArray);
3、如果题目要求在原有str上做更改,要从后往前遍历以免替换掉有用的数据。
代码

public class Solution {
    public String replaceSpace(StringBuffer str) {
    	String str1 = str.toString();
        if(str1.equals(""))return str1;
        char [] strArray = str1.toCharArray();
        
        int i = 0;
        int lengthSpace = 0;
        while(i < strArray.length){
            if(strArray[i] == ' ')
                lengthSpace++;
            i++;
        }
        
        int newLengthSpace = strArray.length+2*lengthSpace;
        char[] newStrArray = new char[newLengthSpace];
        
        i = strArray.length-1;
        int j =  newLengthSpace-1;
        while(i>=0){
            if(strArray[i]!= ' '){
                newStrArray[j--]=strArray[i--];
            }else{
                newStrArray[j--]='0';
                newStrArray[j--]='2';
                newStrArray[j--]='%';
            i--;
            }
        }
        return new String(newStrArray);    
    }
}

19 顺时针打印矩阵

标签
数组
要求
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下 4 X 4 矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字 1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
思路
设定上、下、左、右的索引
从最上行开始,从左到右打印,结束后上的索引向下移(对应数值+1);
从最右开始,从上到下打印,结束后最右索引向下移(对应数值-1);
如此类推,知道打印数=数组的数
备注
代码

import java.util.ArrayList;
public class Solution {
    public ArrayList printMatrix(int [][] matrix) {
       
       ArrayList resultList = new ArrayList<>();
       int cols = matrix[0].length;
       int rows = matrix.length;    
       int left=0,top=0,bottom=rows-1,right=cols-1;
       int count = 0;//计数,count如果达到数组的全部个数,那么结束。
       int total = cols*rows;
        
       while(count < total){
           //先向右
           for(int i = left ; i<=right;i++){
               resultList.add(matrix[top][i]);
               count++;
               if(count >= total)return resultList;
           }
           top++;
           //从上到下
           for(int i = top;i<=bottom;i++){
               resultList.add(matrix[i][right]);
               count++;
               if(count >= total)return resultList;
           }
           right--;
           //从you到zuo
           for(int i = right;i>=left;i--){
               resultList.add(matrix[bottom][i]);
               count++;
               if(count >= total)return resultList;
           }
           bottom--;
           //cong下到上
           for(int i = bottom;i>=top;i--){
               resultList.add(matrix[i][left]);
               count++;
               if(count >= total)return resultList;
           } 
           left++;
       }
       return resultList;
    }
}

27 字符串排列

标签
递归、字符串
要求
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串 abc, 则打印出由字符 a,b,c 所能排列出来的所有字符串 abc,acb,bac,bca,cab 和 cba。
思路
递归的方式换
首次传进来的i为0,代表首位字符
依次处理i与i后面的每个字符(索引j)交换
备注
换了之后获得递归结果,要再换回来,不影响整体的顺序(其他情况已经默默加入到集合里)
代码

import java.util.*;
public class Solution {
    public ArrayList Permutation(String str) {
        ArrayList result = new ArrayList<>();
        if(str.length()==0 ||str == null){
            return result;
        }
        PermutationHelper(str.toCharArray(),0,result);
        Collections.sort(result);
        return result;
    }
    private void PermutationHelper(char[] chars,int i,ArrayList result){
        //已经递归到了字符串最后一位,判断集合中有没有这个字符串,没有则加入
        if(i== chars.length-1){
            if(!result.contains(new String(chars))){
                result.add(new String(chars));
                return;
            }
        }else{
            //首次传进来的i为0,代表首位字符
            //依次处理i与i后面的每个字符(索引j)交换
            for(int j=i; j

34 第一个只出现一次的字符

标签
字符串、查找
要求
在一个字符串 (0<= 字符串长度 <=10000,全部由字母组成) 中找到第一个只出现一次的字符,并返回它的位置,如果没有则返回 -1(需要区分大小写).
思路
将字符串转化为字符数组,遍历数组,利用hash表,若不存在则以array[i]的值为key传入1,存在则修改原来的hash表该位置的值,结束时返回第一个带1的key即可
备注
判断条件 if(!map.containsKey(array[i]))
代码

import java.util.HashMap;
import java.util.Map;
public class Solution {
    public int FirstNotRepeatingChar(String str) {
        if(str==null||str.length()==0){
            return -1;
        }
        Map map = new HashMap();
        char[] array = str.toCharArray();
        for(int i=0; i < str.length(); i++ ){
            if(!map.containsKey(array[i])){
                map.put(array[i],1);
            }else {
                map.put(array[i], map.get(array[i])+1);
            }
        }
        //System.out.println(map.toString());
        for(int i = 0; i

35 数组中的逆序对

标签
数组、归并
要求
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数 P。并将 P 对 1000000007 取模的结果输出。 即输出 P%1000000007
思路
先理解好题目
首先是可以采用暴力排序,每个数与之后面的数最比较
于是可以采用归并来加速运算过程,
备注
明白count + end - start2+1的含义,当前一半有数大于后一半时,证明后面剩下的数会与该数生成逆序对
代码


public class Solution{
	int count = 0; 
	public int InversePairs(int [] array) {
		if(array != null && array.length != 0){
            int[] tmpArr = new int[array.length];
            mergeSort(array,0,array.length-1,tmpArr);
        }
        return count;
	}
 
	public void mergeSort(int[] array,int start,int end,int[] tmpAddr) {
		if(start>=end) {
			return;
		}
		int mid = (start+end)/2;
		mergeSort(array, start, mid, tmpAddr);
		mergeSort(array, mid+1, end, tmpAddr);
		merge(array, start, mid, end, tmpAddr);
	}
	public void merge(int[] array ,int start,int mid,int end,int[] tmpAddr) {
		int tmpIndex = start;
		int start2 = mid+1;
		int i = start;
		while(start<=mid&&start2<=end) {
			if(array[start] > array[start2]) {
				tmpAddr[tmpIndex++] = array[start++];
				count = (count + end - start2+1) % 1000000007;//逆序对
			}else {
				tmpAddr[tmpIndex++] = array[start2++];
			}
		}
 
		if (start2 <= end) {
			System.arraycopy(array, start2, tmpAddr, tmpIndex, end - start2 + 1);
		}
		if (start <= mid) {
			System.arraycopy(array, start, tmpAddr, tmpIndex, mid - start + 1);
		}
		System.arraycopy(tmpAddr, i, array, i, end - i + 1); 
	}
}

43 左旋转字符串

标签
字符串、陷阱
要求
汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列 S,请你把其循环左移 K 位后的序列输出。例如,字符序列 S=”abcXYZdef”, 要求输出循环左移 3 位后的结果,即 “XYZdefabc”。是不是很简单?OK,搞定它!
思路
左移n位=前 n%=字符串长度 位放到后面,截取再合并即可
备注
这题难就难在能不能想到n大于字符串长度的情况喝空字符串的情况
代码

public class Solution {
    public String LeftRotateString(String str,int n) {
        if (str == "" || str.length()==0)return str;
        n%=str.length();
        String str1 = str.substring(0, n);
        str1 = str.substring(n)+str1;
        return str1;
    }
}

44 翻转单词顺序

标签
字符串、翻转、陷阱
要求
牛客最近来了一个新员工 Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事 Cat 对 Fish 写的内容颇感兴趣,有一天他向 Fish 借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是 “I am a student.”。Cat 对一一的翻转这些单词顺序可不在行,你能帮助他么?
思路
先总体翻转,以空格为单位翻转
备注
要小心最后一个单词不是空格结尾的
代码

public class Solution {
  public String ReverseSentence(String str)
	  {
	       if(str == null ||str.length()<2) 
	       {
	    	   return str;
	       }
	       char[] array = str.toCharArray();
	       reserve(array,0,array.length-1);
	       int start = 0;//记录每个单词的起始位置
	       int end = 0;//单词的终止位置
	       while(end < array.length)
	       {
	    	   if(array[end] !=' ')
	    	   {
	    		   if(end == array.length-1)//最后一个单词无空格
	    		   {
	    			   reserve(array,start,end);
	    		   }
	    		   end++;
	    	   }
	    	   else if(array[end]== ' ')//当遇到空格时,把空格之前的单词翻转,并且把start置为end
	    	   {
	    		   reserve(array,start,end-1);
	    		   end++;
	    		   start = end;//下一个单词的起始位置
	    	   }
	       }
	       return String.valueOf(array);
	  }
	  private void reserve(char[] array,int start,int end)
	  {
		  char temp = ' ';
		  while(start < end)
		  {
			  temp = array[start];
			  array[start++] = array[end];
			  array[end--] = temp;
		  }
	  }
}

45 扑克牌顺子

标签
字符串
要求
LL 今天心情特别好,因为他去买了一副扑克牌,发现里面居然有 2 个大王,2 个小王 (一副牌原本是 54 张 _)… 他随机从中抽出了 5 张牌,想测测自己的手气,看看能不能抽到顺子,如果抽到的话,他决定去买体育彩票,嘿嘿!!“红心 A, 黑桃 3, 小王,大王,方片 5”,“Oh My God!” 不是顺子…LL 不高兴了,他想了想,决定大 \ 小 王可以看成任何数字,并且 A 看作 1,J 为 11,Q 为 12,K 为 13。上面的 5 张牌就可以变成 “1,2,3,4,5”(大小王分别看作 2 和 4),“So Lucky!”。LL 决定去买体育彩票啦。 现在,要求你使用这幅牌模拟上面的过程,然后告诉我们 LL 的运气如何, 如果牌能组成顺子就输出 true,否则就输出 false。为了方便起见,你可以认为大小王是 0。
思路
取得王牌数
取得空缺数,王牌
备注
代码

import java.util.*;
public class Solution {
    public boolean isContinuous(int [] numbers) {
    
        if(numbers.length < 4)return false;
         Arrays.sort(numbers);
        
        int zero =0;//大小王
        int zeroNeed = 0;//空(需要大小王去填)
            
        for (int i = 0 ; i= zeroNeed)return true;
        else return false;
    }
}

49 把字符串转换为整数

标签
字符串
要求
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为 0 或者字符串不是一个合法的数值则返回 0
思路
用ascll判断是否为0-9,第一个数可以是正负符号
备注
不要忽略符号,sum的值要设置为long防止溢出
代码

public class Solution {
    public int StrToInt(String str) {
		int len = str.length();
		if(len==0 || str=="")
			return 0;
		if((str.charAt(0)=='+'||str.charAt(0)=='-')&& str.length()==1) {
			return 0;
		}
		long sum=0;
		int fuhao=1; //当第一位为正或者无符号时,置符号位为1
		if(str.charAt(0)=='-')
			fuhao = -1;
		if(str.charAt(0)=='+' || str.charAt(0)=='-')
			str = str.substring(1,str.length());
		
		char[] a = str.toCharArray();
		for(int i=0;i (a[i]-'0') || (a[i]-'0') > 9 )
				return 0;
			sum = sum*10+a[i]-48;
		}
		sum = sum*fuhao;
		if(sumInteger.MAX_VALUE)
			return 0;
		else
		   return (int)sum;
		}        
    }

52 正则表达式的匹配

标签
字符串
要求
请实现一个函数用来匹配包括 ‘.’ 和 ’ * '的正则表达式。模式中的字符 ‘.’ 表示任意一个字符,而 ’ * '表示它前面的字符可以出现任意次(包含 0 次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串 “aaa” 与模式 “a.a” 和 “abaca” 匹配,但是与 “aa.a” 和 “ab* a” 均不匹配
思路
第一个字符不相等的话,就直接返回 false。return false;
第二个字符就要分情况讨论了
1、当模式中的第二字符不是* 时,文本和模式都往后移一步。
2 当模式中第二个字符是* 时,这个情况就有四种情况要考虑了
第一个字符不相等,例子 ab 和 c * ab,一个 a 一个 c,且模式串第二个 * 则,直接 patten 向后跳两个指针:
第一个字符相等时,就有三种情况要考虑在内了
1、abc 和 a * bc 模式后移 2 字符,相当于 * 被忽略
2、abc 和 a * abc 模式后移 2 字符,相当于 x * 被忽略;
3、aaaabc 和 a * abc 字符串后移 1 字符,模式不变,即继续匹配字符下一位,因为 * 可以匹配多位;
备注
注意这里的*和一般理解的不一样
代码

public class Solution {
    public boolean match(char[] str, char[] pattern)
    {
         if(str==null||pattern==null)
        {
            return false;
        }
        int strIndex = 0;
        int patternIndex = 0;
        return matchCore(str,strIndex,pattern,patternIndex);
    }
 
    private boolean matchCore(char[] str, int strIndex, char[] pattern, int patternIndex) {
        if (strIndex == str.length && patternIndex == pattern.length)
        {
            return  true;
        }
        if (strIndex!=str.length &&  patternIndex==pattern.length)
        {
            return  false;
        }
         //有*的情况
        if (patternIndex+1 < pattern.length && pattern[patternIndex+1] == '*')
        {
            // 1 匹配一个 2 匹配多个 3 忽略星号
            if(( strIndex != str.length && pattern[patternIndex]==str[strIndex] )||( pattern[patternIndex]=='.' && strIndex!=str.length))
            {
                return matchCore(str,strIndex,pattern,patternIndex+2) || matchCore(str,strIndex+1,pattern,patternIndex) || matchCore(str,strIndex+1,pattern,patternIndex+2);
            }
            else
            {
                return  matchCore(str,strIndex,pattern,patternIndex+2);
            }
        }
        //1、不要越界2、逐个字符比对(因为这是没有*的情况)
        if ((strIndex!=str.length&&str[strIndex]==pattern[patternIndex])||(pattern[patternIndex]=='.'&&strIndex!=str.length))
        {
            return matchCore(str,strIndex+1,pattern,patternIndex+1);
        }
        return false;       
    }
}

53 表示数值的字符串

标签
字符串、判断
要求
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串 “+100”,“5e2”,"-123",“3.1416” 和 “-1E-16” 都表示数值。 但是 “12e”,“1a3.14”,“1.2.3”,“±5” 和 “12e+4.3” 都不是。
思路
//e只有一个且不再最后
//符号只能再第1或者e前
//小数点前不能有e
//小数点只有一个,且不再最后
备注
代码

public class Solution {

        //e只有一个且不再最后
        //符号只能再第1或者e前
        //小数点前不能有e
        //小数点只有一个,且不再最后

	public boolean isNumeric(char[] str) {
		StringBuffer sb = new StringBuffer();
		for(int i = 0;i < str.length;i ++) {
			sb.append(str[i]);
		}
		
		//判断输入的是否为非法字符
		for(int i = 0;i < sb.length();i ++) {
			if(!((sb.charAt(i) >= '0' && sb.charAt(i) <= '9')
			  || sb.charAt(i) == 'e' || sb.charAt(i) == 'E' 
			  || sb.charAt(i) == '+' || sb.charAt(i) == '-' || sb.charAt(i) == '.')) {
				return false;
			}		
		}
		
		//判断是否包含多个小数点
		if(sb.indexOf('.' + "") != sb.lastIndexOf('.' + "")) {
			return false;
		}
		
		//正负号在末尾
		if(sb.charAt(sb.length() - 1) == '+' || sb.charAt(sb.length() - 1) == '-') {
			return false;
		}
		
		//存在正负号但是不在开头、末尾,判断正负号的位置是否有误
		for(int i = 1;i < sb.length() - 1;i ++) {
			if(sb.charAt(i) == '+' || sb.charAt(i) == '-') {
				//正负号的前面一个数不是e/E,或者后面一个数不是数字
				if((sb.charAt(i - 1) != 'e' && sb.charAt(i - 1) != 'E') ||
				   !(sb.charAt(i + 1) >= '0' && sb.charAt(i + 1) <= '9')){
					return false;
				}
			}
		}
		
		//关于e/E的判断
		for(int i = 0;i < sb.length();i ++) {
			if(sb.charAt(i) == 'e' || sb.charAt(i) == 'E') {
				if(i + 1 == sb.length())	return false;	// e/E出现在了末尾
				if(sb.charAt(i + 1) == '+' || sb.charAt(i + 1) == '-') {
					if(sb.indexOf('.' + "", i + 2) != -1) {		//正负号后又出现了小数点,类似12e+4.3
						return false;
					}
				}
			}
		}
		
		return true;
	}

}

54 字符流中第一个不重复的字符

标签
字符串、查找
要求
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符 “go” 时,第一个只出现一次的字符是 “g”。当从该字符流中读出前六个字符 “google"时,第一个只出现一次的字符是"l"。
思路
设置一个容量256 的char[]数组对应所有的字符,当存入char时,以char为索引的位置+1;只需要选出第一个为1的索引返回即可。
备注
代码

import java.util.*;
public class Solution {
    //Insert one char from stringstream
    //数组存储每个字符出现的次数
    char [] cn = new char[256];
    StringBuffer sb = new StringBuffer();
    public void Insert(char ch)
    {
        ++cn[ch];
        sb.append(ch+"");
    }
  //return the first appearence once char in current stringstream
    public char FirstAppearingOnce()
    {
    	char [] t = sb.toString().toCharArray();
        for(int i=0;i

3、链表

03 从尾到头打印链表

标签
链表、逆序、递归
要求
输入一个链表,按链表从尾到头的顺序返回一个 ArrayList。
思路
递归调用改方法直到结尾再打印即可
代码

import java.util.ArrayList;
public class Solution {

    ArrayList arr=new ArrayList();
    public ArrayList printListFromTailToHead(ListNode listNode) {
        if(listNode!=null)
        {
            this.printListFromTailToHead(listNode.next);
            arr.add(listNode.val);
        }
        return arr;

    }
}

14 链表中倒数第K个节点

标签
链表
要求
输入一个链表,输出该链表中倒数第 k 个结点。
思路
其实很简单,两个指针,先行指针先走K步,然后两个指针同时移动,等先行指针到末尾是输出后行指针即可
备注
代码

public class Solution {
   public ListNode FindKthToTail(ListNode head,int k) {
       int length = 0;
       ListNode tempHead = head;
       while(tempHead != null)
       {
           length++;//这里计算链表的长度
           tempHead = tempHead.next;
       }
       if(k > length || k <=0)//因为倒数第K个节点,如果超过链表长度可不行呀
           return null;
       ListNode before = head;
       ListNode after = head;
       for(int i=0;i

15 反转链表

标签
链表
要求
输入一个链表,反转链表后,输出新链表的表头。
思路
当前指针指向前一个指针,前一个指针等于当前指针,当前指针等于后一个指针,后一个指针等于后一个指针指向的下一个指针
备注
记得保留末尾指针来返回
注意多个指针移动的顺序
代码

public class Solution {
    public ListNode ReverseList(ListNode head) {
       if(head == null || head.next == null)
           return head;
        
        ListNode pre = head;
        ListNode p = head.next;
        ListNode last = p.next;

        head.next = null;
        while(last.next != null){
            p.next = pre;
            pre = p;
            p = last;
            last = last.next;
        }
        last.next=p;
        p.next = pre;
        return last;
    }
}

16 合并两个排序的链表

标签
链表、合并
要求
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
思路
比较简单,创造一个结果链表,分别创建两个遍历一二链表的指针
比较两个指针,选择比较小的节点复制到结果链表,对应的指针指向下一个
当其中一个指针到达末尾时,剩下一条链表直接粘贴到结果链表末尾
备注
代码

public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
        if(list1 ==null && list2 == null)return null;
        if(list1 == null)return list2;
        if(list2 == null)return list1;
        
        ListNode p=new ListNode(0);
        ListNode head=p;
        ListNode p1=list1;
        ListNode p2=list2;
               
        while(true){
            if(p1==null){
                p.next = p2;
                return head.next;
            }
            if(p2 == null){
                p.next= p1;
                return head.next;
            }
            
            if(p1.val < p2.val){
                p.next=p1;
                p1=p1.next;
            }else{
                p.next=p2;
                p2=p2.next;
            }
            p=p.next;
        }
    }
}

25 复杂链表的复制

标签
链表、复制
要求
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的 head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
思路
为了避免随机指针复制时目标节点还没生成
1、先将每个节点复制(123变1 1’ 2 2’ 3 3’)
2、复制节点复制随机节点
3、将所有的复制节点单独移出当做一列
备注
时刻记住指针的走向,最好画下图不然会乱指
代码

public class Solution {
    public RandomListNode Clone(RandomListNode pHead)
    {
        RandomListNode p=pHead;
            
        if(pHead == null)return null;
        if(p.next == null){
            RandomListNode head = new RandomListNode(p.label);
            head.next = p.next;
            head.random=p.random()
        }
        
        while(p!=null){
            
            RandomListNode copy=new RandomListNode(p.label); 
            copy.next=p.next;
            copy.random=null;
            p.next=copy;
            p=copy.next;
        }
        p=pHead;

        while(p!=null){            
            if (p.random != null)
            p.next.random=p.random.next;
            if(p.next == null)break;
            p=p.next.next;
        }
        
        p=pHead;
        RandomListNode head=new RandomListNode(0); 
        RandomListNode p2=head; 
        while(p!=null){
            p2.next=p.next;
            p2=p2.next;
            if(p.next == null)break;
            p=p.next.next;
        }

        return head.next;
    }
}

36 两个链表的第一个公共节点

标签
链表
要求
输入两个链表,找出它们的第一个公共结点。
思路
最优解,遍历各自的链表,统计长度,N M 设 N>M
此时 N 的链表先走 N-M 步,再同时开始,相同节点则相交
备注
若无空间限制,使用 hash 表,先遍历 1 再遍历 2 即可
代码

public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        
        if(pHead1 == null || pHead2 == null)return null;
        
        ListNode i=pHead1,j=pHead2;//用于遍历1 2链表
        int i_len=0,j_len=0;//用于记录链表12长度
        
        //遍历1
        while(i != null){
            i=i.next;
            i_len++;
        }
        //遍历j
            while(j != null){
            j=j.next;
            j_len++;
        }
        //重置ij
        i=pHead1;
        j=pHead2;
        
        if (i_len < j_len){
            for(int k = 0;k

46 孩子们的游戏(圆圈中最后剩下的数)

标签
链表、数学、约瑟夫环
要求
每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF 作为牛客的资深元老,自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数 m, 让编号为 0 的小朋友开始报数。每次喊到 m-1 的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续 0…m-1 报数… 这样下去… 直到剩下最后一个小朋友,可以不用表演,并且拿到牛客名贵的 “名侦探柯南” 典藏版 (名额有限哦!!_)。请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从 0 到 n-1)

如果没有小朋友,请返回 - 1
思路
约瑟夫环,照做就好
备注
代码

import java.util.LinkedList;
public class Solution {
    public int LastRemaining_Solution(int n, int m) {
        LinkedList list = new LinkedList<>();
        //初始化圈圈
        for(int i=0;i1){
            p=(p+m-1) % list.size();
            list.remove(p);
        }
        if(list.size()==1)return list.get(0);
        return -1;
    }
}

55 链表中环的入口节点

标签
链表、查找
要求
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出 null。
思路
若无空间限制最简单可以用 hash 表实现,无环的话直走到结尾也不会重复,有环返回第一个重复节点即可
最优解:头结点开始用快慢指针遍历,快指针一次两步,慢指针依次一步,如果无环则会快速到达 null,若有环则会快慢环中相遇则证明有环,此时快指针从头开始遍历,慢指针从相遇点遍历,两个指针每次只走一步,再次相遇时为进入环的节点
备注
解释下原理
设链长w,环长n,相遇时在环入口走了y步
假设第一圈就相遇了
w + n + y = 2 (w + y)
经过化简,我们可以得到:w = n - y;
所以,这种情况下,我们就可以直接把 p2 放在 pHead 处,然后让两个指针以同样的速度走,那么,两者下一次就一定在入口节点相遇了。
同理走了k圈时,w + nk + y = 2 (w + y)
w=nk-y,快指针从头再一步一步走一样能在入口点相遇
代码

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

    ListNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {

    public ListNode EntryNodeOfLoop(ListNode pHead)
    {
        if (pHead == null)return pHead;
        if (pHead.next == null)return null;
        ListNode fast = pHead;
        ListNode slow = pHead;
        
        while(fast != null){
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow ){
                fast = pHead;
                while(fast != slow){
                    fast = fast.next; 
                    slow = slow.next;
                }
                return fast;
            }
        }
        return null;
    }
}

56 删除链表中的重复值

标签
链表
要求
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表 1->2->3->3->4->4->5 处理后为 1->2->5
思路
删除链表中的重复节点
1、新建一个头节点,以防止第一个节点被删除。
2、保存当前节点的前一个节点,循环遍历整个链表,如果当前节点的值与下一个节点的值相等,则将当前节点的值与 next.next节点的值比较,直到不相等或者null为止,
最后将当前节点的前一个节点 pre指向最后比较不相等的节点
3、如果当前节点与next节点不相等,则直接让节点指针全部向后移动一位
备注
代码

public class Solution {
    public ListNode deleteDuplication(ListNode pHead)
    {
        // 非递归思路
        if(pHead == null || pHead.next == null) return pHead;
        ListNode Head = new ListNode(-1);
        Head.next = pHead;
        ListNode pre = Head;
        ListNode cur = Head.next;
        while(cur != null){
            if(cur.next!=null && cur.val == cur.next.val){
                while(cur.next != null && cur.val == cur.next.val){
                    cur = cur.next;
                }
                pre.next = cur.next;
            }else{
                pre = pre.next;
            }
            cur = cur.next;
        }
        return Head.next;
    }
}

4、树

04 重建二叉树

标签
二叉树、前中后序遍历、递归
要求
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列 {1,2,4,7,3,5,6,8} 和中序遍历序列 {4,7,2,1,5,3,8,6},则重建二叉树并返回。
思路
1、前序遍历数组第一个数为根节点
2、中序遍历可知472为左子树,5386为右子树
3、递归调用该方法
备注
不要漏掉子节点为空、以及只有一个节点(传入的数为叶子节点)时的情况
代码

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;i0){
		int[] pr=new int[i];
		int[] ino=new int[i];
		for(int j=0;j0){
		int[] pr=new int[len-i-1];
		int[] ino=new int[len-i-1];
		for(int j=i+1;j

17 树的子结构

标签
二叉树、判定
要求
输入两棵二叉树 A,B,判断 B 是不是 A 的子结构。(ps:我们约定空树不是任意一个树的子结构)
思路
备注
判断AB的root是否值相同,如果是则开始对AB进行子树判定,否则对A的左子节点和B,A的右子节点和B进行判断
判断:
1、当B子节点为空时,证明B树已经遍历完(且前面的节点符合子树要求)返回true
2、当A子节点为空时,B不为空,则证明不是,返回false;
3、若AB子节点都不为空,判断节点值是否相等,若不相等则返回false,相等则进行这两个节点左右孩子的判断
代码

public class Solution {
    public boolean HasSubtree(TreeNode root1,TreeNode root2) {
        if(root1 == null || root2 ==null){
            return false;
        }
        
        boolean flag = false;
        if (root1.val == root2.val){
            flag = judge(root1,root2);
            if(flag)return true;
            else{
                flag=judge(root1.left,root2);
                if(flag)return true;
                else{flag=judge(root1.right,root2);
                    if(flag)return true;
                    }
            }
        }
        return false;
    }
    
    public boolean judge(TreeNode root1,TreeNode root2){
        if(root2 == null)return true;
        if(root1 == null)return false;
        if(root1.val != root2.val)return false;
        return judge(root1.left,root2.left)&&judge(root1.right,root2.right);
    }
}

18 二叉树的镜像

标签
二叉树、镜像、递归
要求
操作给定的二叉树,将其变换为源二叉树的镜像。
思路
根节点不变,子节点开始左右互换,然后子节点的子节点开始左右互换,知道null
备注
代码

public class Solution {
    public void Mirror(TreeNode root) {
               if(root == null )
           return;
       if(root.left == null && root.right == null)
           return;
       TreeNode tempNode = root.right;
       root.right = root.left;
       root.left = tempNode; //这里三行代码进行 交换左右子树
       Mirror(root.left);//对于左子树 递归调用  就是说对于左子树也进行交换
       Mirror(root.right);//右子树同理
    }
}

22 从上往下打印二叉树

标签
二叉树、遍历
要求
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
思路
创造一个队列,将根节点放入,弹出时打印节点,并将其左右(如果有)节点放入队列
备注
代码

import java.util.ArrayList;
import java.util.Queue;
import java.util.LinkedList;

public class Solution {
    public ArrayList PrintFromTopToBottom(TreeNode root) {
        ArrayList result= new ArrayList<>();
        if (root == null)return result;
        
        
        Queue queue = new LinkedList<>();
        
        queue.offer(root);
        
        while(queue.size()!=0){
            
            TreeNode p = queue.poll();
            result.add(p.val);
            if(p.left!=null)queue.offer(p.left);
            if(p.right!=null)queue.offer(p.right);
        }
        
        return result;
    }
}

23 二叉搜索树树的后序遍历

标签
二叉树、遍历、二叉搜索树
要求
题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出 Yes, 否则输出 No。假设输入的数组的任意两个数字都互不相同
思路
后序遍历最末尾的必定是根节点
搜索二叉树的性质,比父节点小的在左边比父节点大的在右边
若开头数字小于根节点小证明有左子树的开始
遍历找到第一个比根节点大的数为右子树的开始
判定No条件,左子树的边界大于右子树的左边界
若不满足no,则左子节点右子节点分别递归,返回的结果&&

备注
代码

public class Solution {
   public boolean VerifySquenceOfBST(int [] sequence) {
       if(sequence.length == 0)
           return false;
       return verify(sequence,0,sequence.length-1);
   }
   
   public boolean verify(int [] sequence,int begin,int end)
   {
       if(begin == end)
           return true;
      
       int rootValue = sequence[end];
       int leftBegin = -1;//左子树的左边界
       int leftEnd = -1;//左子树的右边界
       int rightBegin = -1;//右子树的左边界
       int rightEnd = -1;//右子树的右边界
       if(sequence[begin] < rootValue)// 说明存在左子树,二叉搜索树的性质
           leftBegin = begin;//记录左子树的左边界
       for(int i=begin;i

24 二叉树中和为某一值的路径

标签
二叉树
要求
输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意:在返回值的 list 中,数组长度大的数组靠前)
思路
创造一个包含链表的链表作为结果的返回
每次进行检索生成一条链表,每访问一个节点则链表add该节点并且记录链表和差多少达到target
当节点没有左右子节点是视为叶节点,此时若target=0,直接返回即可,要把该叶节点删掉,让父节点遍历其他节点
若没到叶节点或者到了二target不为0,则递归左右子节点(非叶节点),结束时删掉该节点可以让父节点遍历其他子节点
备注
注意要到叶节点才算路径
判断节点是否为空
代码

import java.util.ArrayList;

public class Solution {
    ArrayList> result = new ArrayList<>();
    public ArrayList> FindPath(TreeNode root,int target) {
        ArrayList list = new ArrayList<>();
        Find(root,target,list);
        return result;
    }
    
    public void Find(TreeNode root,int target,ArrayList list){
        
       if(root == null)
           return;
       target -= root.val; //target不是引用,所以target在每一层的递归中都是不同的值,记录当前的节点和
       list.add(root.val);        
        
        if(target == 0 && root.left == null && root.right == null){
           result.add(new ArrayList(list));//存入结果数组
           list.remove(list.size()-1);//找到以后还要接着找啊,所以先把当前最后的叶子节点删除
           return;
        }
       Find(root.left,target,list);//左右子树递归进去去找
       Find(root.right,target,list);
       list.remove(list.size()-1);//这里左右子树都找完了,回到了找完的左右子树的父节点
       
    }
}

26 二叉搜索树与双向列表

标签
链表、树
要求
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
思路
先中序遍历二叉搜索树,这样二叉搜索树就按照 val 值的大小从小到大排好序了,存放在数组中

然后要转换为双向链表,由于数组中的存放的树的节点已经按照键值从小到大排好序了,那么就对于每个节点的左子树指向数组的上一个节点,右子树指向数组的下一个节点,这样就完成了变成双向链表。
备注
注意第一个节点和最后一个节点要单独处理(只有一个指针)
代码

import java.util.ArrayList;
public class Solution {
   public TreeNode Convert(TreeNode pRootOfTree) {
       if(pRootOfTree == null || (pRootOfTree.left == null && pRootOfTree.right == null))
           return pRootOfTree;
       ArrayList nodeList = new ArrayList<>();
       BuildArrayList(pRootOfTree,nodeList);//这个函数执行后,数组中每个元素按照大小前后排序
       for(int i=0;i nodeList)
   {//二叉搜索的中序遍历,并把每个节点存入数组中
       if(root == null)
           return;
       if(root.left != null)//左子树
           BuildArrayList(root.left,nodeList);
       if(root != null)//根节点
           nodeList.add(root);
       if(root.right != null)//右子树
           BuildArrayList(root.right,nodeList);
   }
}

38 二叉树的深度

标签
二叉树
要求
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
思路
递归思路,根的高度等于(左子树的高度和右子树的高度重高度较高的那一个高度)+1
备注
代码

public class Solution {
    public int TreeDepth(TreeNode root) {
       if(root == null)
           return 0;//为空高度是0
       if(root != null && root.left == null && root.right == null)
           return 1;//只有一个节点,叶子节点高度是1
      //左右子树高度 中取较高的那一个高度+1
       return TreeDepth(root.left)>TreeDepth(root.right)?TreeDepth(root.left)+1:TreeDepth(root.right)+1;        
    }
}

39 平衡二叉树

标签
二叉树
要求
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
思路
从下往上遍历,如果子树是平衡二叉树,则返回子树的高度;如果发现子树不是平衡二叉树,则直接停止遍历,这样至多只对每个结点访问一次。
备注
代码

public class Solution {
   private boolean flag = true;
   public boolean IsBalanced_Solution(TreeNode root) {
       TreeLength(root);
       return flag;
   }
   private int TreeLength(TreeNode root)
   {
       if(root == null)
           return 0;
       int left = TreeLength(root.left);//左子树的高度
       int right = TreeLength(root.right);//右子树的高度
       if(left-right >= 2 || right - left >= 2)
       {//左右子树高度差大于等于2,标记就不是true
           flag = false;
       }
       return left>right?(left+1):(right+1);
   }
}

57 二叉树的下一个节点

标签
搜索、二叉树、遍历
要求
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
思路
1、根节点返回最左边的节点
2、若是父节点的左子节点,
该点有右子节点,返回右子节点
该点无右子节点,返回父节点
3、若是父节点的右子节点
该点有右子节点,返回右子节点
该点无右子节点,该点为最后一个节点返回null
备注
根节点要单独考虑
代码

/*
public class TreeLinkNode {
    int val;
    TreeLinkNode left = null;
    TreeLinkNode right = null;
    TreeLinkNode next = null;
 
    TreeLinkNode(int val) {
        this.val = val;
    }
}
*/
//中序遍历:先左子节点,其次父节点,最次右节点
public class Solution {
    public TreeLinkNode GetNext(TreeLinkNode pNode)
    {
        TreeLinkNode temp = null;
        if(pNode.next==null){
            //此节点是父节点
            //如果是根节点,返回最左的左叶子节点,如果左叶子节点为空,返回它的父节点
            if(pNode.right!=null){
                temp = pNode.right;
                while(temp.left!=null){
                    temp = temp.left;
                }
                return temp;
            }else{
                return null;
            }
        }
        //第一步判断此节点是父节点的左子节点还是右子节点,还是根节点
        if(pNode.next.left==pNode){
            //如果是父节点的左子节点,判断此节点有没有右儿子
            if(pNode.right!=null) {
                temp = pNode.right;
                while(temp.left!=null){
                    temp = temp.left;
                }
                return temp;
            }else{
                //如果没有右儿子,则返回父节点
                return pNode.next;
            }
        }else{
            //如果是父节点的右儿子,在没有右儿子的情况下,需要判断是在整个树的左边还是在右边
            //判断有没有右儿子,
            if(pNode.right!=null) {
                temp = pNode.right;
                while(temp.left!=null){
                    temp = temp.left;
                }
                return temp;
            }else{
                //在没有右儿子的情况下,需要判断是在整个树的左边还是在右边
                TreeLinkNode node=null;
                TreeLinkNode mark = pNode;
                while(pNode.next!=null){
                    node = pNode;
                    pNode = pNode.next;
                }
                if(node==pNode.left){
                    //如果是左子树
                    return mark.next.next;
                }else{
                    //如果是右子树,则该节点是最后一个叶子节点,则返回null
                	return null;
                }
                
            }
        }
    }
}

58 对称的二叉树

标签
树、递归
要求
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
思路
分析左右子树。可以看出,左右子树刚好是呈镜像的两颗二叉树,所以:对左子树采用(父 - 左 - 右)的前序遍历,右子树采用(父 - 右 - 左)的前序遍历,遍历时判断两个结点位置的值是否相等即可。(也可以这样理解:左树的左子树等于右树的右子树,左树的右子树等于右树的左子树,对应位置刚好相反,判断两子树相反位置上的值是否相等即可)
备注
代码

public class Solution {
     
    public boolean isSymmetrical(TreeNode pRoot){
        if(pRoot==null)
            return true; //根结点为null时,认为是对称二叉树
        return isEqual(pRoot.left,pRoot.right);
    }
     
    private boolean isEqual(TreeNode pRoot1,TreeNode pRoot2){
        if(pRoot1==null && pRoot2==null)
            return true;
        if(pRoot1==null || pRoot2==null)
            return false;
        return pRoot1.val==pRoot2.val && isEqual(pRoot1.left, pRoot2.right) && isEqual(pRoot1.right, pRoot2.left);     
    }
}

59 按之字形顺序打印二叉树

标签
树、队列
要求
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
思路
与之前做过的层序遍历类似,但是弄两个栈,一个奇数层栈,一个偶数层栈。
奇数层:节点弹出后,先右,后左节点进入偶数层栈
偶数层:节点弹出后,先左,后右,进入奇数层栈
备注
不要忘记root为空的情况
代码

import java.util.ArrayList;
import java.util.Stack;

public class Solution {
    public ArrayList > Print(TreeNode pRoot) {
        
        ArrayList> res = new ArrayList<>();
        if (null == pRoot) {
            return res;
        }
        Stack s1 = new Stack<>();
        Stack s2 = new Stack<>();
        s1.push(pRoot);
        int level = 1;
        while (!s1.empty() || !s2.empty()) {
            if (0 != level % 2) {
                ArrayList nodeList = new ArrayList<>();
                while (!s1.empty()) {
                    TreeNode node = s1.pop();
                    nodeList.add(node.val);
                    if (null != node.left) {
                         s2.push(node.left);;
                    }
                    if (null != node.right) {
                         s2.push(node.right);
                    }
                }
                if (!nodeList.isEmpty()) {
                    res.add(nodeList);
                    level++;
                }
            } else {
                ArrayList nodeList = new ArrayList<>();
                while (!s2.empty()) {
                    TreeNode node = s2.pop();
                    nodeList.add(node.val);
                    if (null != node.right) {
                         s1.push(node.right);;
                    }
                    if (null != node.left) {
                         s1.push(node.left);
                    }
                }
                if (!nodeList.isEmpty()) {
                    res.add(nodeList);
                    level++;
                }
            }
        }
        return res;
    }

}

60 把二叉树打印成多行

标签
打印、队列
要求
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
思路
按层序遍历的思路用队列调用即可,但是要注意,每次记录队列里的节点数(目的是只读取本行数量的数,新增加的数留到下一行)
备注
代码

import java.util.ArrayList;
import java.util.Queue;
import java.util.LinkedList;
public class Solution {
    ArrayList > Print(TreeNode pRoot) {
        Queue q = new LinkedList();
        if(pRoot == null) {
            return new ArrayList>();
        }
        else {
            q.add(pRoot);
        }
        ArrayList > res = new ArrayList();
        while(!q.isEmpty()) {
            int size = q.size();
            ArrayList temp_res = new ArrayList();
            for(int i = 0; i < size; i++) {
                TreeNode temp = q.poll();
                temp_res.add(temp.val);
                if(temp.left != null) {
                    q.add(temp.left);
                }
                if(temp.right != null) {
                    q.add(temp.right);
                }
            }
            res.add(temp_res);
        }
        return res;
    }
}

61 序列化二叉树

标签
二叉树、遍历
要求
二叉树的序列化是指:把一棵二叉树按照某种遍历方式的结果以某种格式保存为字符串,从而使得内存中建立起来的二叉树可以持久保存。序列化可以基于先序、中序、后序、层序的二叉树遍历方式来进行修改,序列化的结果是一个字符串,序列化时通过 某种符号表示空节点(#),以 ! 表示一个结点值的结束(value!)。

二叉树的反序列化是指:根据某种遍历顺序得到的序列化字符串结果 str,重构二叉树。
思路
序列化:因为值为数字,为了防止歧义,将值的后面加上一个标记 1 (随便一个符号),在 null 值用一个标记 2(随便一个符号)表示。
反序列化:遇到标记 1,建立节点,剩余的字符串表示其左子节点,遇到标记 2 为 null。
备注
代码

public class Solution {
	String Serialize(TreeNode root) {
		StringBuilder builder = new StringBuilder();
		pre(root, builder);
		return builder.toString();
	}
	
	
	public void pre(TreeNode node, StringBuilder builder) {
		if(node == null) {
			builder.append("#!");
		}
		else {
			builder.append(node.val + "!");
			pre(node.left, builder);
			pre(node.right, builder);
		}
	}
	
	int index = -1;
	
	TreeNode Deserialize(String str) {
		String[] arr = str.split("!");
		TreeNode node = null;
		index++;
		if(!arr[index].equals("#")) {
			node = new TreeNode(Integer.valueOf(arr[index]));
			node.left = Deserialize(str);
			node.right = Deserialize(str);
			
		}
		return node;
	}
}

62 二叉搜索树的第k个节点

标签
二叉树,搜索树,遍历,查找
要求
给定一棵二叉搜索树,请找出其中的第 k 小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为 4。
思路
设定一个计数器,中序遍历即可
备注
递归的话注意计数器要定义为全局变量
代码

public class Solution {
   int index = 0; //计数器
    TreeNode KthNode(TreeNode root, int k)
    {
        if(root != null){ //中序遍历寻找第k个
            TreeNode node = KthNode(root.left,k);
            if(node != null)
                return node;
            index ++;
            if(index == k)
                return root;
            node = KthNode(root.right,k);
            if(node != null)
                return node;
        }
        return null;
    }
}

5、位运算

11 二进制中1的个数

标签
位运算、神仙题
要求
输入一个整数,输出该数二进制表示中 1 的个数。其中负数用补码表示。
思路
分析的得
不为0的整数,至少有一位是1,而这个数减1时,这个数最右边的1会变为0,后面的0会变为1.
例如:1100减一变为1011,两者相与为1000。可以看出,n有多少个1就可以与(n-1)相与多少次。
备注
代码

public class Solution {
   public int NumberOf1(int n) {
       if(n == 0)
           return 0;
       int count = 0;
       while((n&(n-1)) != 0)//这个就是每个整数减一然后与自身相与
       {
           count++;//如果不为0,那么说明还有1,
           n = n & (n-1);
       }
       count++;//比如说循环开始的时候只有一个1,那么循环没进入循环体就结束了,所以这里需要count加一个1来计数
       return count;
   }
}

40 数组中只出现一次的数字

标签
位运算、神仙题
要求
一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。。
思路
1、因为一个数异或自己必定为0,异或整个数组,重复两次的数必定自己抵消掉
创造一个 e,遍历数组,e 异或遍历的数组元素,最后剩下的值为 a 异或 b,因为 ab 不等,所以 e 不为 0,遍历 e 的位,出现 1 的值证明 a 和 b 第 k 位不一样,此时创造一个 p,p 再次遍历数组中第 k 位为 1 的值,最后的 p 必定是 a,b 中的一个,另一个数则为 p 与 e 的异或

备注
代码

//num1,num2分别为长度为1的数组。传出参数
//将num1[0],num2[0]设置为返回结果
public class Solution {
   public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
       int temp = 0;
       for(int i=0;i> 1;
       }
       return index;
   }
   private boolean IsBit1(int number,int index)
   {
       number = number >> index;
       if((number & 1) == 0)
           return false;
       return true;
   }
}

6、栈和队列

05 用两个栈实现队列

标签
栈、队列、实现数据结构
要求
用两个栈来实现一个队列,完成队列的 Push 和 Pop 操作。 队列中的元素为 int 类型。
思路
栈为先进后出,队列为先进先出,只需要把弹出的元素加入栈2,再弹出即可
备注
1、注意栈2弹出后,将栈2的元素放回栈1
2、定义stack时new Stack()而不是new Stack()
代码

import java.util.Stack;

public class Solution {
    Stack stack1 = new Stack();
    Stack stack2 = new Stack();
    
    public void push(int node) {
        stack1.push(node);
    }
    
    public int pop() {
        
        while(! stack1.empty()){
            stack2.push(stack1.pop());
        }
        int a = stack2.pop();
        while(!stack2.empty()){
            stack1.push(stack2.pop());
        }
        return a;
    }
}

20 包含min函数的栈

标签
栈、最小、重写
要求
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的 min 函数(时间复杂度应为 O(1))。
思路
创造普通栈和最小栈两个数,普通栈弹出,重写进栈方法
普通栈进栈时,若最小栈为空,直接进栈,否则与最小栈的栈顶比较大小,比栈顶小,则加入,否则,加入栈顶的值
min函数返回最小栈的栈顶即可
备注
返回min时不要用pop,要用peek(不弹出)
代码

import java.util.Stack;

public class Solution {

   Stack stack1 = new Stack<>();
   Stack stackMin = new Stack<>();
    
    public void push(int node) {
                stack1.push(node);
        if(stackMin.empty()){
           stackMin.push(node);
        }
        else if(node < (int)stackMin.peek()){
           stackMin.push(node);
        }else{
           stackMin.push(stackMin.peek());          
        }
    }
    
    public void pop() {
        stack1.pop();
        stackMin.pop();
    }
    
    public int top() {
        return (int)stack1.peek();
    }
    
    public int min() {
        return (int)stackMin.peek();
    }
}

21 栈的压入、弹出序列

标签

要求
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列 1,2,3,4,5 是某栈的压入顺序,序列 4,5,3,2,1 是该压栈序列对应的一个弹出序列,但 4,3,5,1,2 就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
思路
一个弹出序列,一个压栈序列,弹出序列中的数,比如第一个弹出的数,肯定是在压栈过程中弹出来的,所以在这里新建一个栈 stack, 如果压栈序列中要压入的数和弹出序列当前的数不一样(说明没找到),那么压栈序列继续压,直到压栈序列中找到了和弹出序列当前下标值相等的数,那么弹出序列的下标值就 + 1,。
结束条件就是弹出序列的下标值可以到达序列的末尾。
备注
代码

在这里插入代码片import java.util.*;
public class Solution {
   public boolean IsPopOrder(int [] pushA,int [] popA) {
       if(pushA.length != popA.length) 
           return false;
       Stack stack1 = new Stack<>();//栈记录压栈
       int j = 1;
       stack1.push(pushA[0]);//栈中先压入push压栈序列的第一个数
       for(int i=0;i= pushA.length && stack1.peek() != popA[i])
               return false;//如果j已经到达压栈序列的末尾,但是栈顶的数还是和弹出序列当前的数不一致
                            //说明没有这个序列
           stack1.pop();
       }
       return true;
   }
}

64 滑动窗口的最大值

标签
数组、栈、双端队列
要求
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组 {2,3,4,2,6,2,5,1} 及滑动窗口的大小 3,那么一共存在 6 个滑动窗口,他们的最大值分别为 {4,4,6,6,6,5}; 针对数组 {2,3,4,2,6,2,5,1} 的滑动窗口有以下 6 个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
思路
普通解法时间复杂度 O (N*w),每次对一个窗口遍历 w 个数,选出最大值
最优解 O (N),利用双端队列 qMax {},存放数组下标
假设 arr [i],放入规则为:
1、若为空直接放
2、若不为空, 取出 qMax 队尾存放下标 j ,如果 arr [j]> arr [i] 直接将 i 放到 qmax 队尾,否则一直从 qmax 队尾弹出下标,知道某个下标在 qmax 中对应的值大于 arr [i],把 arr [i] 放入 qmax 队尾,
弹出规则
1、如果 qmax 队头下标 = i-w,弹出队头下标,res 取对应值即可
此时 qmax 成为维护长度为 w 的结构

总结:1、队列里的数大,读取的数放最后;队列里的数小等,弹出滚蛋,读取的数进来
2、定时筛选掉移出滑动窗口以外的数

备注
代码

import java.util.ArrayDeque;
import java.util.ArrayList;

public class Solution {
    public ArrayList maxInWindows(int [] num, int size)
    {
        ArrayList res = new ArrayList<>();
        ArrayDeque queue = new ArrayDeque<>();
        int len = num.length;
        
        
        if (num == null || size <= 0 || num.length < size) {
        	return res;
        }
        
        for (int i=0; isize) {
                queue.pollFirst();
            }
            // 把每次滑动的num下标加入队列
            queue.offerLast(i);
            // 当滑动窗口首地址i大于等于size时才开始写入窗口最大值
            if(i+1 >= size) {
                res.add(num[queue.peekFirst()]);
            }
        }        
        return res;
    }
}

7、其他

07 斐波那契数列

标签
递归、斐波那契
要求
大家都知道斐波那契数列,现在要求输入一个整数 n,请你输出斐波那契数列的第 n 项(从 0 开始,第 0 项为 0)。
n<=39
思路
直接看代码即可
备注
代码

public class Solution {
    public int Fibonacci(int n) {
        if(n<2)
            return n;
        else return Fibonacci(n-1)+Fibonacci(n-2);
    }
}

08 跳台阶

标签
递归、斐波那契
要求
一只青蛙一次可以跳上 1 级台阶,也可以跳上 2 级。求该青蛙跳上一个 n 级的台阶总共有多少种跳法(先后次序不同算不同的结果)。
思路
与斐波那契数列类似,从到达第n阶逆向思考,可以有n-1阶和n-2阶跳完,所以相当于跳到n-1的方法和到n-2的方法相加,一直递归
备注
代码

public class Solution {
    public int JumpFloor(int target) {
        if(target <2 )return 1;
        else if(target ==2)return 2;
        else {
        return JumpFloor(target-1) + JumpFloor(target-2);
        }
    }

09 变态跳台阶

标签
递归、数学归纳
要求
一只青蛙一次可以跳上 1 级台阶,也可以跳上 2 级…… 它也可以跳上 n 级。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。
思路
本题需要一点数学归纳,列出以下情况
n=1 时 f(1)=1;从0阶跳上来
n=2 时 f(2-1)+f(2-2);可以从1阶跳上来,也可以从0阶跳上来
n=3 时 f(3-1)+f(3-2)+f(3-3);可以从2阶、1阶、0阶跳上来

n=n 时 f(n)=f(n-1)+f(n-2)+…+f(n-(n-1))+f(n-n) => f(0)+…f(n-1)
因为 f(n-1)=f(n-1-1)+f(n-1-2)+…+f(n-1-(n-1))=> f(0)+…+f(n-2)
所以 f(n)=f(n-1)*2
备注
先列出一堆分析即可
代码

    public int JumpFloorII(int target) {
        if(target < 2)return 1;
        return 2*JumpFloorII(target-1);
    }

10 矩形覆盖

标签
递归、斐波那契
要求
我们可以用 21 的小矩形横着或者竖着去覆盖更大的矩形。请问用 n 个 21 的小矩形无重叠地覆盖一个 2*n 的大矩形,总共有多少种方法?
思路
n=1 和 n=2 时分别是1种和2种
覆盖方法有横着覆盖和竖着覆盖两种
下图可以看出,横着覆盖时(黑色),下一步必定也是横着覆盖(蓝色)
Java 剑指Offer 题目分类汇总_第1张图片
因此这个问题又可以转换为,一次可以覆盖成一格或者两格,覆盖n格有多少种方法,依然是斐波那契问题
备注
画图分析明明白白
代码

public class Solution {
    public int RectCover(int target) {
        if(target < 3)return target;
        return RectCover(target-1)+RectCover(target-2);
    }
}

12 数值的整数次方

标签
数学
要求
给定一个 double 类型的浮点数 base 和 int 类型的整数 exponent。求 base 的 exponent 次方。保证 base 和 exponent 不同时为 0
思路
细心即可
备注
变题(仅提供思路)
如何用更快的方式求整数K的N次方,如果两个整数相乘并得到结果的时间复杂度为O(1),得到整数k的N次方的过程实现复杂度O(logN)
最优解:
设10的75次方
1、次数拆解成二进制1001011(7位数)
2、用翻倍的方式求10的n次方,翻7次,10的1次,10的2次,10的4次,10的8次,10的16次,10的32次,10的64次
3、 二进制为1的位数与步骤2的数相乘,110的64次+0+10的32次+010的16次+110的8次+010的4次+110的2次+1*10的1次
代码

链接:https://www.nowcoder.com/questionTerminal/1a834e5e3e1a4b7ba251417554e07c00?answerType=1&f=discussion
来源:牛客网

// 递推写法
public class Solution {
    public static double Power(double base, int exp) {
 
        boolean flag = false;
        if (exp < 0) {
            flag = true;
            exp = -exp;
        }
        double ans = 1;
        while (exp > 0) {
            if ((exp & 1) == 1) {
                ans = ans * base;
            }
            exp >>= 1;
            base *= base;
        }
        return flag ? 1 / ans : ans;
    }
}

31 整数1出现的次数

标签
查找、数学
要求
求出 1~13 的整数中 1 出现的次数,并算出 100~1300 的整数中 1 出现的次数?为此他特别数了一下 1~13 中包含 1 的数字有 1、10、11、12、13 因此共出现 6 次,但是对于后面问题他就没辙了。ACMer 希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中 1 出现的次数(从 1 到 n 中 1 出现的次数)。
思路
首先求一个位上1的个数(以百位为例),n在百位上有3种情况
1、百位为0,如12034。此时1的个数取决于百位的高位,有100-199,1100-1199,2100-2199…11100-11199,1的个数有高位 X 位数,有12100个1。
2、百位为1,如12134。不仅受高位影响还受低位影响,有100-199,1100-1199,2100-2199…11100-11199,12100-12134,,1的个数有高位 X 位数+低位数字+1,12
100+134+1。
3、百位为2-9,如12234。仅由高位决定100-199,1100-1199,…,11100-11199”,1的个数有高位+1 X 位数,有13*100个1。
备注
细心分析
代码

public class Solution {
public int NumberOf1Between1AndN_Solution(int n) {
    if(n < 1){
        return 0;
    }
    int res = 0;
    for(int i = 1 ; i <= n ; i++){
        res += count(i);
    }
    return res;
}

public int count(int n){
    int count = 0;
    while(n != 0){
        //取个位
        count = (n % 10 == 1) ? ++count : count;
        //去掉个位
        n /= 10;
    }
    return count;
}
}

33 丑数

标签
穷举法
要求
把只包含质因子 2、3 和 5 的数称作丑数(Ugly Number)。例如 6、8 都是丑数,但 14 不是,因为它包含质因子 7。 习惯上我们把 1 当做是第一个丑数。求按从小到大的顺序的第 N 个丑数。
思路
一个丑数一定由另一个丑数乘以 2 或者乘以 3 或者乘以 5 得到,那么我们从 1 开始乘以 2,3,5,就得到 2,3,5 三个丑数,在从这三个丑数出发乘以 2,3,5 就得到 4,6,10,6,9,15,10,15,25 九个丑数

我们可以维护三个队列:
2队列 2 4 6 8…
3队列 3 6 9 12 …
5队列 5 10 15 …
每次将3个队列头最小的数加入结果队列里,每加入一次该队列对应的指针就向前挪一位,当结果队列长度为n时就停止
优化:只需要维护一个队列,2,3,5三个指针指向同一个队列,初始值指向a[0]==1(1默认为第一个丑数),当最小数为当前指针该位置的数是(如第一个加入队列的是12=2,那么该指针就会指向下一个数2,下一次添加时比较的就是4(2 * 2),3(1 * 3),5(1 * 5),此时选中3,a[2]=3,3指针下移,下次参与比较的是4(2 * 2),6(3 * 2),5(5 * 1),如此类推。
备注
其实1-6都是丑数所以n<7可以直接返回n
代码

import java.util.ArrayList;

public class Solution {
    public int GetUglyNumber_Solution(int index) {
        if(index<=0){
            return 0;
        }
        ArrayList list=new ArrayList<>();
        list.add(1);
        int t2=0,t3=0,t5=0;// 对应的下标
        while(list.size()

41 和为S的连续正数序列

标签
穷举、动态
要求
小明很喜欢数学,有一天他在做数学作业时,要求计算出 9~16 的和,他马上就写出了正确答案是 100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为 100 (至少包括两个数)。没多久,他就得到另一组连续正数和为 100 的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为 S 的连续正数序列?Good Luck!
思路
暴力破解,
由于是连续的,差为1的一个序列,那么求和公式为(a1+an)*n/2
先设定两个指针low 和high,他们之间的和为cur,如果cur小于sum,则high右移,若大于sum则low右移
直到不满足phigh>plow
备注
代码

 import java.util.ArrayList;
 public class Solution {
     public ArrayList > FindContinuousSequence(int sum) {
        //存放结果
         ArrayList> result = new ArrayList<>();
         //两个起点,相当于动态窗口的两边,根据窗口内的值的和来确定窗口的位置和大小
         int plow=1,phigh=2;
         while(phigh>plow){
             //由于是连续的,差为1的一个序列,那么求和公式为(a1+an)*n/2
             int cur=(phigh+plow)*(phigh-plow+1)/2;
             //相等,则将窗口中的值添加进结果集
             if(cur==sum){
                 ArrayList list = new ArrayList<>();
                 for(int i =plow;i<=phigh;i++){
                     list.add(i);
                 }
                 result.add(list);
                 plow++;
             }else if(cur

42 和为S的两个数

标签
穷举、数学
要求
输入一个递增排序的数组和一个数字 S,在数组中查找两个数,使得他们的和正好是 S,如果有多对数字的和等于 S,输出两个数的乘积最小的。
思路
和41同理,比41简单
数列满足递增,设两个头尾两个指针 i 和 j,
若 ai + aj == sum,就是答案(最开始出现的相差最远,相差越远乘积越小)
若 ai + aj > sum,aj 肯定不是答案之一(前面已得出 i 前面的数已是不可能),j -= 1
若 ai + aj < sum,ai 肯定不是答案之一(前面已得出 j 后面的数已是不可能),i += 1
备注
代码

import java.util.ArrayList;
public class Solution {
    public ArrayList FindNumbersWithSum(int [] array,int sum) {
        ArrayList resultList = new ArrayList<>();
        if (array.length <= 1)
            return resultList;
        int i=0;
        int j=array.length-1;
        while(i sum){
                j--;
            }else{
                i++;
            }
        }
        return resultList;
    }
}

47 求 1+2+3+…+n

标签
进制转换
要求
求 1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case 等关键字及条件判断语句(A?B:C)。
思路
1、&& 还具有短路的功能,即如果第一个表达式为 false,则不再计算第二个表达式
2、求和的公式为:(n+1)*n/2
3、
备注
代码

public class Solution {
    int result=0;
    public int Sum_Solution(int n) {
        sum(n);
        return result;
    }
    
    public int sum(int n){
        boolean a =(n-1)>=0  && (result +=n)>0 && sum(n-1)>0;//a没用,只是为了执行
        return result;
    }
}

48 不用加减乘除做加法

标签
进制转换
要求
写一个函数,求两个整数之和,要求在函数体内不得使用 +、-、*、/ 四则运算符号。
思路
首先看十进制是如何做的: 5+7=12,三步走
第一步:相加各位的值,不算进位,得到 2。
第二步:计算进位值,得到 10. 如果这一步的进位值为 0,那么第一步得到的值就是最终结果。
第三步:重复上述两步,只是相加的值变成上述两步的得到的结果 2 和 10,得到 12。

同样我们可以用三步走的方式计算二进制值相加: 5-101,7-111
第一步:相加各位的值,不算进位,得到 010,二进制每位相加就相当于各位做异或操作,101^111。
第二步:计算进位值,得到 1010,相当于各位做与操作得到 101,再向左移一位得到 1010,(101&111)<<1。
第三步重复上述两步, 各位相加 010^1010=1000,进位值为 100=(010&1010)<<1。
继续重复上述两步:1000^100 = 1100,进位值为 0,跳出循环,1100 为最终结果。
备注
不算进位相加,^,异或
求进位,&,相与,再左移一位
代码

public class Solution {
    public int Add(int num1,int num2) {
        int sum = 0;//不带进位的结果
        int carry = 0;//进位
       while(num2 != 0){
           sum = num1 ^ num2;
           carry = (num1 & num2) << 1;
           num1 = sum;
           num2 = carry;
       }
        
        return num1;
    }
}

63 数据流中的中位数

标签
堆、数学
要求
如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用 Insert () 方法读取数据流,使用 GetMedian () 方法获取当前读取数据的中位数。
思路
所谓数据流,就是不会一次性读入所有数据,只能一个一个读取,每一步都要求能计算中位数。
  将读入的数据分为两部分,一部分数字小,另一部分大。小的一部分采用大顶堆存放,大的一部分采用小顶堆存放。当总个数为偶数时,使两个堆的数目相同,则中位数 = 大顶堆的最大数字与小顶堆的最小数字的平均值;而总个数为奇数时,使小顶堆的个数比大顶堆多一,则中位数 = 小顶堆的最小数字。
  因此,插入的步骤如下:
  1. 若已读取的个数为偶数(包括 0)时,两个堆的数目已经相同,将新读取的数插入到小顶堆中,从而实现小顶堆的个数多一。但是,如果新读取的数字比大顶堆中最大的数字还小,就不能直接插入到小顶堆中了 ,此时必须将新数字插入到大顶堆中,而将大顶堆中的最大数字插入到小顶堆中,从而实现小顶堆的个数多一。
  2 若已读取的个数为奇数时,小顶堆的个数多一,所以要将新读取数字插入到大顶堆中,此时方法与上面类似。
数据流特点,数据一个个进,无法遍历
备注
这里采用PriorityQueue来代替最大堆最小堆(PriorityQueue,数字小的在前面)
最大堆则改写comparable接口,使最大的数字在队列头。
代码

import java.util.PriorityQueue;
import java.util.Comparator;
 
public class Solution {
    PriorityQueue minHeap = new PriorityQueue(); //小顶堆,默认容量为11
    PriorityQueue maxHeap = new PriorityQueue(11,new Comparator(){ //大顶堆,容量11
        public int compare(Integer i1,Integer i2){
            return i2-i1;
        }
    });
    public void Insert(Integer num) {
        if(((minHeap.size()+maxHeap.size())&1)==0){//偶数时,下个数字加入小顶堆
            if(!maxHeap.isEmpty() && maxHeap.peek()>num){
                maxHeap.offer(num);
                num=maxHeap.poll();
            }
            minHeap.offer(num);
        }else{//奇数时,下一个数字放入大顶堆
            if(!minHeap.isEmpty() && minHeap.peek()

76 剪绳子

标签
贪心算法、斐波那契
要求
给你一根长度为 n 的绳子,请把绳子剪成整数长的 m 段(m、n 都是整数,n>1 并且 m>1),每段绳子的长度记为 k [0],k [1],…,k [m]。请问 k [0] xk [1] x…xk [m] 可能的最大乘积是多少?例如,当绳子的长度是 8 时,我们把它剪成长度分别为 2、3、3 的三段,此时得到的最大乘积是 18。
思路
设置一个数组存放每个长度对应的最大值
i从4(0,1,2,3特殊处理)到n/2(i超过一半时结果与n/2之前的另一半重复)
设最后一刀为i下,则乘积为i*K[n-i],而K[n-i]在前面的时候已经计算出来了
备注
长度为0,1,2,3的时候应该特殊处理
代码

public class Solution {
    public int cutRope(int length) {
        if (length < 2) {
            return 0;
        }
        if (2 == length) {
            return 1;
        }
        if (3 == length) {
            return 2;
        }
        int[] products = new int[length + 1];  // 将最优解存储在数组中
        // 数组中第i个元素表示把长度为i的绳子剪成若干段之后的乘积的最大值
        products[0] = 0;
        products[1] = 1;
        products[2] = 2;
        products[3] = 3;
        int max = 0;
        for (int i = 4; i <= length; i++) {  //i表示长度
            max = 0;
            for (int j = 1; j <= i / 2; j++) {  //由于长度i存在(1,i-1)和(i-1,1)的重复,所以只需要考虑前一种
                int product = products[j] * products[i - j];
                if (product > max) {
                    max = product;
                }
            }
            products[i] = max;
        }
        return products[length];
    }
}

你可能感兴趣的:(算法)