编程基础题

1.二维数组中的查找

题目描述

在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。

请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

解题思路:

第一种方法:

把每一行看成有序递增的数组,
利用二分查找,
通过遍历每一行得到答案,
时间复杂度是nlogn

第二种方法:

从左下角的元素开始比较,target大的话row++,target小的话col--

 
  1. //第一种

  2. public class Solution {

  3. public boolean Find(int [][] array,int target) {

  4. //对每列二分检索(每列每行都一样)

  5. for(int i=0;i<array.length;i++){

  6. int low=0;

  7. int high=array[0].length-1;

  8. while(low<=high){//别忘了这里

  9. int mid=(low+high)/2;

  10. if(target==array[i][mid])

  11. {

  12. return true;

  13. }else{

  14. if(target>array[i][mid]){

  15. low=mid+1;

  16. }else{

  17. high=mid-1;

  18. }

  19. }

  20. }

  21. }

  22. return false;

  23. }

  24. }

 
  1. //第二种

  2. public class Solution {

  3. public boolean Find(int [][] array,int target) {

  4. int row=0;

  5. int col=array[0].length-1;

  6. while(row<array.length&&col>=0){//边界这里其实有点问题

  7. if(target==array[row][col]){

  8. return true;

  9. }else if(target>array[row][col]){

  10. row++;

  11. }else{

  12. col--;

  13. }

  14.  
  15. }

  16. return false;

  17. }

  18. }


 

2.替换空格

题目描述

请实现一个函数,将一个字符串中的空格替换成“%20”。

例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

解体思路:

这种题有很多种方法,可以巧妙地用已有的方法

第一种:

(简单粗暴)正则表达式

题中给定的参数传的是StringBuffer类的,先str.toString()转化为String类【那个括号不要忘了】

然后用String类的replaceAll("\\s","%20");

\s表示空格,前面的 \ 用来转义第二个 \

!!注意:replaceAll方法返回一个String,而不是更改原来的字符串,所以要新定义一个String a=s.replaceAll("","")

第二种:

转化为String类后,在转化成char[]数组,遍历,声明一个StingBuffer类,遇到空格,加上%20,否则加原来的字符

 
  1. //第一种

  2. public class Solution {

  3. public String replaceSpace(StringBuffer str) {

  4. return str.toString().replaceAll("\\s", "%20");

  5. }

  6. }

 
  1. //第二种

  2. public class Solution {

  3. public String replaceSpace(StringBuffer str) {

  4. String s=str.toString();

  5. char[] c=s.toCharArray();

  6. StringBuffer sb=new StringBuffer();

  7. for(int i=0;i<c.length;i++){

  8. if(c[i]==' '){

  9. sb.append("%20");

  10. }else{

  11. sb.append(c[i]);

  12. }

  13. }

  14. return sb.toString();

  15. }

  16. }


3.从尾到头打印链表

题目描述


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

输入描述:
输入为链表的表头
输出描述:
输出为需要打印的“新链表”的表头

解题思路:

第一种:

利用堆栈"先进后出"

第二种:

递归【!!!二刷的时候还不熟悉】

判断当前结点是否为空,不空的话,递归调用该函数,不停地找next,到了尾节点,其next为空,此时,将尾节点添加进list中,递归开始往回了,不停地倒着加入节点

 
  1. //第一种

  2. /**

  3. * public class ListNode {

  4. * int val;

  5. * ListNode next = null;

  6. *

  7. * ListNode(int val) {

  8. * this.val = val;

  9. * }

  10. * }

  11. *

  12. */

  13. import java.util.ArrayList;

  14. import java.util.Stack;

  15. public class Solution {

  16. public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {

  17. Stack<Integer> stack=new Stack<Integer>();

  18. while(listNode!=null){

  19. stack.push(listNode.val);

  20. listNode=listNode.next;

  21. }

  22. ArrayList<Integer> arr=new ArrayList<Integer>();

  23. while(!stack.isEmpty()){

  24. arr.add(stack.pop());

  25. }

  26. return arr;

  27. }

  28. }

 
  1. //第二种

  2. /**

  3. * public class ListNode {

  4. * int val;

  5. * ListNode next = null;

  6. *

  7. * ListNode(int val) {

  8. * this.val = val;

  9. * }

  10. * }

  11. *

  12. */

  13. import java.util.ArrayList;

  14. public class Solution {

  15. ArrayList<Integer> list=new ArrayList<Integer>();//在函数外面声明

  16. public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {

  17. if(listNode!=null){

  18. this.printListFromTailToHead(listNode.next);//用this调用

  19. list.add(listNode.val);

  20. }

  21. return list;

  22. }

  23. }


 

4.重建二叉树

题目描述

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。

假设输入的前序遍历和中序遍历的结果中都不含重复的数字。

例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

解题思路:

先判断这两种遍历数组是否为空,不要用pre==null,用pre.length==0

根据题目给出的前序遍历、后序遍历数组,
首先找出根节点,然后再根据中序遍历找到左子树和右子树的长度,
分别构造出左右子树的前序遍历和中序遍历序列,
最后分别对左右子树采取递归,递归跳出的条件是序列长度为1.

先序遍历第一个位置肯定是根节点node,
中序遍历的根节点位置在中间p,这样就可以知道左子树和右子树的长度

用Arrays.copyOfRange(int[] ,int from,int to)【取不到to】

递归递归【递归递归!!二刷的时候还是不够熟练】

 
  1. /**

  2. * Definition for binary tree

  3. * public class TreeNode {

  4. * int val;

  5. * TreeNode left;

  6. * TreeNode right;

  7. * TreeNode(int x) { val = x; }

  8. * }

  9. */

  10. import java.util.*;

  11.  
  12.  
  13. public class Solution {

  14. public TreeNode reConstructBinaryTree(int [] pre,int [] in) {

  15. if(pre.length==0||in.length==0){

  16. return null;

  17. }

  18. TreeNode node=new TreeNode(pre[0]);

  19. for(int i=0;i<in.length;i++){

  20. if(pre[0]==in[i]){

  21. node.left=reConstructBinaryTree(Arrays.copyOfRange(pre,1,i+1),Arrays.copyOfRange(in,0,i));

  22. node.right=reConstructBinaryTree(Arrays.copyOfRange(pre,i+1,pre.length),Arrays.copyOfRange(in,i+1,in.length));

  23. }

  24. }

  25. return node;

  26. }

  27. }


 

5.用两个栈实现队列

题目描述

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

解题思路:

这个题之前整理过,主要注意的是,一个栈负责压入,一个栈负责弹出

弹出时,那个栈要保证里面是空的,从压入栈中压入后,弹出

压入时,也要保证压入栈里没有东西,这两点一样,【弹出压入这两点一样,只要实现一个就行,全都放在弹出那】

注意到要将int类型转为Integer类型!!!

 
  1. import java.util.Stack;

  2.  
  3. public class Solution {

  4. Stack<Integer> stack1 = new Stack<Integer>();

  5. Stack<Integer> stack2 = new Stack<Integer>();

  6.  
  7. public void push(int node) {

  8. stack1.push(new Integer(node));//注意到要将int类型转为Integer类型//不一定用转换,直接也行

  9. }

  10.  
  11. public int pop() {

  12. if(stack2.isEmpty()){//判断栈空不空,用isEmpty()!!!

  13. while(!stack1.isEmpty()){

  14. stack2.push(stack1.pop());

  15. }

  16. }

  17.  
  18. return stack2.pop().intValue();//注意到要将Integer类型转为int类型//不一定用转换,直接也行

  19.  
  20. }

  21. }


 

6.旋转数组的最小数字【有点疑惑】

题目描述

把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。
例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。

【其实这个题就是求数组中最小元素,只是因为它自身的特性可以减小时间复杂度来求】

解题思路:

根据题意说明是一个递增数组的旋转,所以如题所示【3,4,5】,【1,2】还是局部递增的,

在这种的数组中查找,一般选择二分的方法;

基本模型有了,下面试着分析:
1.先取出中间的数值,和最后一个比较5>2 说明mid之前的某些部分旋转到了后面,

所以下次寻找 low = mid+1 开始;

2.取出的中间值要是小于high,说明mid-high之间都应为被旋转的部分,所以最小应该在mid的前面,

但是也有可能当前的mid 就是最小的值 所以下次需找的应该 从mid开始,也即high = mid 开始

3.当*mid == *high的时候,说明数组中存在着相等的数值,

可能是这样的形式 【2,2,2,2,1,2】所以应该选择的high 应该递减1 作为下次寻找的上界。

 
  1. import java.util.ArrayList;

  2.  
  3. public class Solution {

  4. public int minNumberInRotateArray(int [] array) {

  5. int low=0;

  6. int high=array.length-1;

  7.  
  8. while(low<high){

  9. int mid=low+(high-low)/2;//最好用这种,不用(high+low)/2

  10. if(array[mid]>array[high]){

  11. low=mid+1;

  12. }else if(array[mid]<array[high]){

  13. high=mid;

  14. }else {

  15. high=high-1;

  16. }

  17. }

  18. return array[low];//返回最小

  19.  
  20. }

  21. }


 

7.斐波那契数列

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

解题思路:

迭代方法,用两个变量记录fn-1和fn-2
还有P.S.  f(n) = f(n-1) + f(n-2),第一眼看就是递归啊,简直完美的递归环境
 

 
  1. if(n<=1)

  2. return n;

  3. else return Fibonacci(n-1)+Fibonacci(n-2);

但是不要用递归!!
 

 
  1. public class Solution {

  2. public int Fibonacci(int n) {

  3. if(n<2){

  4. return n;

  5. }

  6. int numfn1=0;

  7. int numfn2=1;

  8. int current=0;

  9. for(int i=2;i<=n;i++){

  10. current=numfn1+numfn2;

  11. numfn1=numfn2;

  12. numfn2=current;

  13. }

  14. return current;

  15.  
  16. }

  17. }


8.跳台阶

题目描述

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

解题思路:

f(n) = f(n-1) + f(n-2)同上同上

最后一次可能跳一阶,可能跳两阶,

 
  1. public class Solution {

  2. public int JumpFloor(int target) {

  3. if(target<=2){

  4. return target;

  5. }

  6. int f1=2;// 当前台阶后退一阶的台阶的跳法总数(初始值当前台阶是第3阶)

  7. int f2=1;// 当前台阶后退二阶的台阶的跳法总数(初始值当前台阶是第3阶)

  8. int current=0;

  9. for(int i=3;i<=target;i++){

  10. current=f1+f2;

  11. f2=f1;//后退一阶在下一次迭代变为后退两阶

  12. f1=current;// 当前台阶在下一次迭代变为后退一阶

  13. }

  14. return current;

  15.  
  16. }

  17. }


 

9.变态跳台阶

题目描述

一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。

求该青蛙跳上一个n级的台阶总共有多少种跳法。

题目解析:

重要的是分析化简,,,

关于本题,前提是n个台阶会有一次n阶的跳法。分析如下:
f(1) = 1
f(2) = f(2-1) + f(2-2)         //f(2-2) 表示2阶一次跳2阶的次数。
f(3) = f(3-1) + f(3-2) + f(3-3) 
...
f(n) = f(n-1) + f(n-2) + f(n-3) + ... + f(n-(n-1)) + f(n-n) 
 
说明: 
1)这里的f(n) 代表的是n个台阶有一次1,2,...n阶的 跳法数。
2)n = 1时,只有1种跳法,f(1) = 1
3) n = 2时,会有两个跳得方式,一次1阶或者2阶,这回归到了问题(1) ,f(2) = f(2-1) + f(2-2) 
4) n = 3时,会有三种跳得方式,1阶、2阶、3阶,
    那么就是第一次跳出1阶后面剩下:f(3-1);第一次跳出2阶,剩下f(3-2);第一次3阶,那么剩下f(3-3)
    因此结论是f(3) = f(3-1)+f(3-2)+f(3-3)
5) n = n时,会有n中跳的方式,1阶、2阶...n阶,得出结论:
    f(n) = f(n-1)+f(n-2)+...+f(n-(n-1)) + f(n-n) => f(0) + f(1) + f(2) + f(3) + ... + f(n-1)
6) 由以上已经是一种结论,但是为了简单,我们可以继续简化:
    f(n-1) = f(0) + f(1)+f(2)+f(3) + ... + f((n-1)-1) = f(0) + f(1) + f(2) + f(3) + ... + f(n-2)
    f(n) = f(0) + f(1) + f(2) + f(3) + ... + f(n-2) + f(n-1) = f(n-1) + f(n-1)
    可以得出:
    f(n) = 2*f(n-1)
    
7) 得出最终结论,在n阶台阶,一次有1、2、...n阶的跳的方式时,总得跳法为:
              | 1       ,(n=0 ) 
f(n) =     | 1       ,(n=1 )
              | 2*f(n-1),(n>=2)

【注!!】

也可以看成,最后一步走1,2,3,n阶

则f(n)=f(n-1)+f(n-2)+....+f(n-n);

而f(n-1)刚好等于f(n-2)+...f(n-n)

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

 
  1. public class Solution {

  2. public int JumpFloorII(int target) {

  3. if (target <= 0) {

  4. return -1;

  5. } else if (target == 1) {

  6. return 1;

  7. } else {

  8. return 2 * JumpFloorII(target - 1);

  9. }

  10. }

  11. }




10.矩形覆盖

我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。

请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?

解题思路

依旧是斐波那契数列
2*n的大矩形,和n个2*1的小矩形
其中target*2为大矩阵的大小
有以下几种情形:
1、target = 1大矩形为2*1,只有一种摆放方法,return1;
2、target = 2 大矩形为2*2,有两种摆放方法,return2;
3、target = n 分为两步考虑:

如果第一格竖着放,只占一个格,还剩n-1格  f(target-1)种方法

如果前两格横着放两个,占两个格,还剩n-2格  f(target-2)种方法

 
  1. public class Solution {

  2. public int RectCover(int target) {

  3. if(target==0||target==1||target==2){

  4. return target;

  5. }else if(target<0){return -1;}

  6. else{

  7. return RectCover(target-1)+RectCover(target-2);

  8. }

  9.  
  10. }

  11. }


11.二进制中1的个数
题目描述

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

解题思路:

第一种:

如果一个整数不为0,那么这个整数至少有一位是1。

如果我们把这个整数减1,那么原来处在整数最右边的1就会变为0,

原来在1后面的所有的0都会变成1(如果最右边的1后面还有0的话)。其余所有位将不会受到影响。

举个例子:一个二进制数1100,从右边数起第三位是处于最右边的一个1。

减去1后,第三位变成0,它后面的两位0变成了1,而前面的1保持不变,因此得到的结果是1011.

我们发现减1的结果是把最右边的一个1开始的所有位都取反了。

这个时候如果我们再把原来的整数和减去1之后的结果做与运算,

从原来整数最右边一个1那一位开始所有位都会变成0。

如1100&1011=1000.

也就是说,把一个整数减去1,再和原整数做与运算,会把该整数最右边一个1变成0.

那么一个整数的二进制有多少个1,就可以进行多少次这样的操作。

第二种:

Java自带的函数

Java.lang.Integer.bitCount()方法

统计参数i转成2进制后有多少个1

【要不是这道题还真不知道这个函数呢】

第三种:

把这个数逐次 右移 然后和1 与,
就得到最低位的情况,其他位都为0,
如果最低位是0和1与 之后依旧 是0,如果是1,与之后还是1。
对于32位的整数 这样移动32次 就记录了这个数二进制中1的个数了 

 
  1. public class Solution {

  2. public int NumberOf1(int n) {

  3. int count = 0;

  4. while(n!= 0){

  5. count++;

  6. n = n & (n - 1);//!!与运算

  7. }

  8. return count;

  9. }

  10. }

 
  1. public class Solution {

  2. public int NumberOf1(int n) {

  3. return Integer.bitCount(n);

  4. }

  5. }

 
  1. //这个方法也是很6的

  2. public class Solution {

  3. public int NumberOf1(int n) {

  4. return Integer.toBinaryString(n).replaceAll("0","").length(); }

  5. }


 

 
  1. public class Solution {

  2. public int NumberOf1(int n) {

  3. int count=0;

  4. for(int i=0;i<32;i++){

  5. if((n>>i&1)==1){//!!!注意这里用i标记,每次循环,就重新右移i位

  6. count++;

  7. }

  8. }

  9. return count;

  10. }

  11. }


12.数值的整数次方

题目描述

给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。

解题思路:

第一种:

咳咳,Java自带的函数~

第二种:

算法的本质就是模拟数学规律,我们可以先模拟一下幂运算就是乘法的连乘,那么用算法写出来,然后再考虑几个测试用例的极端情况,如exponent==0或者exponent<0的情况,然后按逻辑写出你的代码

 
  1. public class Solution {

  2. public double Power(double base, int exponent) {

  3. return Math.pow(base,exponent);

  4. }

  5. }

 
  1. public class Solution {

  2. public double Power(double base, int exponent) {

  3. if(exponent==0){

  4. return 1;

  5. }else if(exponent>0){

  6. double num=base;

  7. for(int i=1;i<exponent;i++){

  8. num=num*base;

  9. }

  10. return num;

  11. }else{

  12. double num2=base;

  13. int flag=-exponent;

  14. for(int i=1;i<flag;i++){

  15. num2=num2*base;

  16. }

  17. num2=1/num2;

  18. return num2;

  19. }

  20.  
  21. }

  22. }


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

题目描述

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

解题思路:

第一种:

空间换时间,创建一个数组,奇数从头放,偶数从奇数个数的末尾开始放

或者,直接两个数组

第二种:

在一个数组中,类似冒泡算法,前偶后奇数就交换

 
  1. import java.util.*;

  2. public class Solution {

  3. public void reOrderArray(int [] array) {

  4. ArrayList<Integer> odd=new ArrayList<Integer>();//奇数

  5. ArrayList<Integer> even=new ArrayList<Integer>();//偶数

  6.  
  7. for(int i=0;i<array.length;i++){

  8. if(array[i]%2==0){

  9. even.add(array[i]);

  10. }else{

  11. odd.add(array[i]);

  12. }

  13. }

  14. for(int i=0;i<odd.size();i++){

  15. array[i]=odd.get(i);

  16. }

  17. for(int i=odd.size();i<array.length;i++){

  18. array[i]=even.get(i-odd.size());

  19. }

  20. }

  21. }

 
  1. public class Solution {

  2. public void reOrderArray(int [] array) {

  3. for(int i=0;i<array.length;i++){

  4. for(int j=array.length-1;j>i;j--){

  5. if(array[j]%2==1&&array[j-1]%2==0){

  6. int temp=array[j];

  7. array[j]=array[j-1];

  8. array[j-1]=temp;

  9. }

  10. }

  11. }

  12. }

  13. }


 

14.链表中倒数第k个结点

题目描述

输入一个链表,输出该链表中倒数第k个结点。

解题思路:

两个指针,先让第一个指针和第二个指针都指向头结点,然后再让第一个指针走(k-1)步,到达第k个节点。然后两个指针同时往末尾移动,当第一个结点到达末尾的时候,第二个结点所在位置就是倒数第k个节点了

 
  1. /*

  2. public class ListNode {

  3. int val;

  4. ListNode next = null;

  5.  
  6. ListNode(int val) {

  7. this.val = val;

  8. }

  9. }*/

  10. public class Solution {

  11. public ListNode FindKthToTail(ListNode head,int k) {

  12. if(head==null||k<=0){

  13. return null;

  14. }

  15. ListNode pre=head;//先走的那个

  16. ListNode last=head;//之后走的那个人

  17. for(int i=1;i<k;i++){//先让第一个走到k

  18. if(pre.next!=null){//k大于链长就返回空

  19. pre=pre.next;

  20. }else{

  21. return null;

  22. }

  23. }

  24. while(pre.next!=null){

  25. pre=pre.next;

  26. last=last.next;

  27. }

  28. return last;

  29.  
  30. }

  31. }


15.反转链表

题目描述

输入一个链表,反转链表后,输出链表的所有元素。

解题思路:

三个指针,先记录当前结点的下一个节点

让当前结点指向前一个节点,

让前一个节点取代当前节点,因为还要继续向下走

让当前节点挪到下一个节点的位置,这是已经继续向下走了

循环,当前节点为空时,正好前一个节点为最后一个节点,而且所有节点的指向已经都反转过来了

1-->2-->3-->4-->5

1<--2<--3<--4<--5

 
  1. /*

  2. public class ListNode {

  3. int val;

  4. ListNode next = null;

  5.  
  6. ListNode(int val) {

  7. this.val = val;

  8. }

  9. }*/

  10. public class Solution {

  11. public ListNode ReverseList(ListNode head) {

  12. ListNode pre=null;

  13. ListNode next=null;

  14. ListNode cur=head;

  15. while(cur!=null){

  16. next=cur.next;

  17. cur.next=pre;

  18. pre=cur;

  19. cur=next;

  20. }

  21. return pre;

  22.  
  23. }

  24. }


 

16.合并两个排序的链表

题目描述

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

解题思路:

第一种

新建一个头节点用来存储新的链表

比较两个链表的值,哪个小就放到新链表中

第二种:

递归

 
  1. /*

  2. public class ListNode {

  3. int val;

  4. ListNode next = null;

  5.  
  6. ListNode(int val) {

  7. this.val = val;

  8. }

  9. }*/

  10. public class Solution {

  11. public ListNode Merge(ListNode list1,ListNode list2) {

  12. ListNode head=new ListNode(0);//必须new一个,构造函数必须有参数

  13. head.next=nul;//有没有这个都行

  14. ListNode root=head;//head是要跟着动的,留一个root是不动的,最后返回时要用

  15. while(list1!=null&&list2!=null){

  16. if(list1.val<list2.val){

  17. head.next=list1;//head是最前面一个无用的节点,从list1或者list2开始

  18. head=list1;//之后head还有list1节点继续往后挪,!!!!head和list1一块往后移,

  19. list1=list1.next;

  20. }else{

  21. head.next=list2;

  22. head=list2;

  23. list2=list2.next;

  24. }

  25. }

  26. //把未结束的链表连接到合并后的链表尾部

  27. if(list1!=null){

  28. head.next=list1;

  29. }

  30. if(list2!=null){

  31. head.next=list2;

  32. }

  33. return root.next;//其实没有办法确定第一个节点是谁,所以从第一个节点前面的节点声明,最后结果是root.next

  34. }

  35. }

 
  1. /*

  2. public class ListNode {

  3. int val;

  4. ListNode next = null;

  5.  
  6. ListNode(int val) {

  7. this.val = val;

  8. }

  9. }*/

  10. public class Solution {

  11. public ListNode Merge(ListNode list1,ListNode list2) {

  12. if(list1==null){return list2;}

  13. else if(list2==null){return list1;}

  14. ListNode head=null;

  15. if(list1.val<list2.val){

  16. head=list1;

  17. head.next=Merge(list1.next,list2);

  18. }else{

  19. head=list2;

  20. head.next=Merge(list2.next,list1);

  21. }

  22. return head;

  23. }

  24. }


17.树的子结构

题目描述

输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)

解题思路:

1、首先设置标志位result = false,因为一旦匹配成功result就设为true,

剩下的代码不会执行,如果匹配不成功,默认返回false

2、递归思想

如果根节点相同则递归调用DoesTree1HaveTree2(),

如果根节点不相同,则判断tree1的左子树和tree2是否相同,再判断右子树和tree2是否相同

3、注意null的条件,HasSubTree中,如果两棵树都不为空才进行判断,

DoesTree1HasTree2中,如果Tree2为空,则说明第二棵树遍历完了,即匹配成功,

tree1为空有两种情况

(1)如果tree1为空&&tree2不为空说明不匹配,

(2)如果tree1为空,tree2为空,说明匹配。

1.首先需要递归pRoot1树,找到与pRoot2根一样的节点,这需要一个遍历
2.找到相同的根节点后,要判断是否子树,仍需要一个一个遍历对比
树的遍历我们一般就用递归来做,那么根据分析需要两个递归函数如下:

!!!!!关于树的问题还要再加强!!!!

 
  1. /**

  2. public class TreeNode {

  3. int val = 0;

  4. TreeNode left = null;

  5. TreeNode right = null;

  6.  
  7. public TreeNode(int val) {

  8. this.val = val;

  9.  
  10. }

  11.  
  12. }

  13. */

  14. public class Solution {

  15. public boolean HasSubtree(TreeNode root1,TreeNode root2) {

  16. boolean result=false;

  17. //当tree1和tree2都不为空是,才进行比较,否则直接返回false

  18. if(root1!=null&&root2!=null){

  19. //如果找到了对应tree2的根节点

  20. if(root1.val==root2.val){

  21. //以这个根节点为起点判断是否包含tree2

  22. result=DoesTree1HaveTree2(root1,root2);

  23. }

  24. //如果找不到,那么就再去root1的左儿子当作起点

  25. if(!result){

  26. result=HasSubtree(root1.left,root2);

  27. }

  28. //如果还找不到,那么就再去root1的有儿子当作起点

  29. if(!result){

  30. result=HasSubtree(root1.right,root2);

  31. }

  32. }

  33. return result;

  34. }

  35. //判断tree1是否包含tree2

  36. public static boolean DoesTree1HaveTree2(TreeNode node1,TreeNode node2){

  37. //如果tree1已经遍历完了,都能对应的上,返回true

  38. if(node2==null){

  39. return true;

  40. }

  41. //如果tree2还没有遍历完,tree1却遍历完了,返回false

  42. if(node1==null){

  43. return false;

  44. }

  45. //如果其中有一个点没有对应上,返回false

  46. if(node1.val!=node2.val){

  47. return false;

  48. }

  49. //如果根节点对应的上,那么久分别去自子节点里面匹配

  50. return DoesTree1HaveTree2(node1.right,node2.right)&&DoesTree1HaveTree2(node1.left,node2.left);

  51. }

  52. }


18.二叉树的镜像

题目描述

操作给定的二叉树,将其变换为源二叉树的镜像。

解题思路:

第一种:

递归,关于树的很多都可以用递归来解

第二种:

非递归

层次遍历

用一个栈,压入根节点,弹出后交换其左右子树,再将左右子树压入,直到遍历完所有节点

 
  1. /**

  2. public class TreeNode {

  3. int val = 0;

  4. TreeNode left = null;

  5. TreeNode right = null;

  6.  
  7. public TreeNode(int val) {

  8. this.val = val;

  9.  
  10. }

  11.  
  12. }

  13. */

  14. import java.util.*;

  15. public class Solution {

  16. public void Mirror(TreeNode root) {

  17. if(root == null){

  18. return;

  19. }

  20. //用堆栈

  21. Stack<TreeNode> stack = new Stack<TreeNode>();

  22. stack.push(root);//压入根节点

  23. while(!stack.isEmpty()){

  24. TreeNode node = stack.pop();

  25. //至少有一边子树不为空时,交换左右子树

  26. if(node.left != null||node.right != null){

  27. TreeNode temp = node.left;

  28. node.left = node.right;

  29. node.right = temp;

  30. }

  31. //左子树不为空时,把左子数压入栈中

  32. if(node.left!=null){

  33. stack.push(node.left);

  34. }

  35. //右子树不为空时,把右子树压入栈中

  36. if(node.right!=null){

  37. stack.push(node.right);

  38. }

  39. }

  40. }

  41. }

 
  1. /**

  2. public class TreeNode {

  3. int val = 0;

  4. TreeNode left = null;

  5. TreeNode right = null;

  6.  
  7. public TreeNode(int val) {

  8. this.val = val;

  9.  
  10. }

  11.  
  12. }

  13. */

  14. public class Solution {

  15. public void Mirror(TreeNode root) {

  16. if(root!=null){//!要记得判断要不然出不去了

  17. TreeNode temp=null;

  18. temp=root.right;

  19. root.right=root.left;

  20. root.left=temp;

  21. Mirror(root.right);

  22. Mirror(root.left);

  23. }

  24. }

  25. }


 

19.顺时针打印矩阵【等下再看,,】

题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,

例如,如果输入如下矩阵: 

   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. import java.util.ArrayList;

  2. public class Solution {

  3. static ArrayList<Integer> list=new ArrayList<Integer>();

  4. public static ArrayList<Integer> printMatrix(int [][] matrix) {

  5. int r1=0;

  6. int c1=0;

  7. int r2=matrix.length-1;

  8. int c2=matrix[0].length-1;

  9. while(r1<=r2&&c1<=c2){

  10. printEdge(matrix,r1++,c1++,r2--,c2--);

  11. }

  12. return list;

  13. }

  14. public static void printEdge(int[][] matrix,int r1,int c1,int r2,int c2){

  15. if(r1==r2){//只有一行

  16. for(int i=c1;i<=c2;i++){

  17. list.add(matrix[r1][i]);

  18. }

  19. }else if(c1==c2){//只有一列

  20. for(int i=r1;i<=r2;i++){

  21. list.add(matrix[i][c1]);

  22. }

  23. }else{

  24. int curr=r1;

  25. int curc=c1;

  26. while(curc!=c2){

  27. list.add(matrix[r1][curc]);

  28. curc++;

  29. }

  30. while(curr!=r2){

  31. list.add(matrix[curr][c2]);

  32. curr++;

  33. }

  34. while(curc!=c1){

  35. list.add(matrix[r2][curc]);

  36. curc--;

  37. }

  38. while(curr!=r1){

  39. list.add(matrix[curr][c1]);

  40. curr--;

  41. }

  42. }

  43. }

  44. }


 

 
  1. import java.util.ArrayList;

  2. public class Solution {

  3. public ArrayList<Integer> printMatrix(int [][] matrix) {

  4. ArrayList<Integer> ls = new ArrayList<Integer>();

  5. int colStart = 0;

  6. int colEnd = matrix[0].length;

  7.  
  8. int lineStart = 0;

  9. int lineEnd = matrix.length;

  10. int count = lineEnd * colEnd;

  11. if (matrix == null)

  12. return ls;

  13. while (count != 0) {

  14. for(int i = colStart;i<colEnd;i++){

  15. ls.add(matrix[lineStart][i]);

  16. count--;

  17. }

  18. lineStart++;

  19. if(count==0)

  20. break;

  21. for(int i = lineStart;i<lineEnd;i++){

  22. ls.add(matrix[i][colEnd-1]);

  23. count--;

  24. }

  25. colEnd--;

  26. if(count==0)

  27. break;

  28. for(int i = colEnd-1;i>=colStart;i--){

  29. ls.add(matrix[lineEnd-1][i]);

  30. count--;

  31. }

  32. lineEnd--;

  33. if(count==0)

  34. break;

  35. for(int i = lineEnd-1;i>=lineStart;i--){

  36. ls.add(matrix[i][colStart]);

  37. count--;

  38. }

  39. colStart++;

  40. if(count==0)

  41. break;

  42. }

  43. return ls;

  44. }

  45. }


 

 
  1. import java.util.ArrayList;

  2. public class Solution {

  3. public ArrayList<Integer> printMatrix(int [][] matrix){

  4. ArrayList<Integer> list=new ArrayList<Integer>();

  5. if(matrix.length==0)

  6. return list;

  7. int n=matrix.length;

  8. int m=matrix[0].length;

  9. if(m==0)

  10. return list;

  11. int layer=(Math.min(m,n)-1)/2+1;

  12. //循环几圈

  13. for(int i=0;i<layer;i++){

  14. //从左上到右上

  15. for(int j=i;j<m-i;j++){

  16. list.add(matrix[i][j]);

  17. }

  18. //从右上到右下

  19. for(int k=i+1;k<n-i;k++){

  20. list.add(matrix[k][m-1-i]);

  21. }

  22. //从右下到左下

  23. //考虑奇数圈的情况,最后一圈只走了上面一行,要对最后两步进行限制

  24. for(int j=m-i-2;(j>=i)&&(n-i-1!=i);j--){

  25. list.add(matrix[n-i-1][j]);

  26. }

  27. //从左下到左上

  28. for(int k=n-i-2;k>i&&(m-i-1!=1);k--){

  29. list.add(matrix[k][i]);

  30. }

  31. }

  32. return list;

  33. }

  34. }


 

20.包含min函数的栈

题目描述

定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。

 
  1. import java.util.Stack;

  2.  
  3. public class Solution {

  4. Stack<Integer> data=new Stack<Integer>();

  5. Stack<Integer> min=new Stack<Integer>();

  6.  
  7. public void push(int node) {

  8. data.push(node);

  9. if(min.isEmpty()){//这里要注意!栈要用isEmpty(),不要用null

  10. min.push(node);

  11. }else{

  12. int temp=min.pop();//这里需要知道现在的最小值,pop出来之后记得放回去

  13. min.push(temp);

  14. if(node<temp){

  15. min.push(node);

  16. }

  17. }

  18. }

  19.  
  20. public void pop() {//弹出这里,只用考虑弹出的那个值是不是最小值就行,不用想弹出他后,还在最小值的栈里

  21. int num=data.pop();

  22. int num1=min.pop();

  23. if(num!=num1){

  24. min.push(num1);

  25. }

  26. }

  27.  
  28. public int top() {

  29. int num=data.pop();

  30. data.push(num);

  31. return num;

  32.  
  33. }

  34.  
  35. public int min() {

  36. int num=min.pop();

  37. min.push(num);

  38. return num;

  39. }

  40. }


21.栈的压入、弹出序列【还要看!!】

题目描述

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。

假设压入栈的所有数字均不相等。

例如序列1,2,3,4,5是某栈的压入顺序,

序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。

(注意:这两个序列的长度是相等的)

解题思路:

借用一个辅助的栈,遍历压栈顺序,先将第一个放入栈中,这里是1,

然后判断栈顶元素是不是出栈顺序的第一个元素,这里是4,很显然1≠4,所以我们继续压栈,

直到相等以后开始出栈,出栈一个元素,则将出栈顺序向后移动一位,

直到不相等,这样循环等压栈顺序遍历完成,如果辅助栈还不为空,说明弹出序列不是该栈的弹出顺序。

举例:
入栈1,2,3,4,5
出栈4,5,3,2,1
首先1入辅助栈,此时栈顶1≠4,继续入栈2
此时栈顶2≠4,继续入栈3
此时栈顶3≠4,继续入栈4
此时栈顶4=4,出栈4,弹出序列向后一位,此时为5,,辅助栈里面是1,2,3
此时栈顶3≠5,继续入栈5
此时栈顶5=5,出栈5,弹出序列向后一位,此时为3,,辅助栈里面是1,2,3
….
依次执行,最后辅助栈为空。如果不为空说明弹出序列不是该栈的弹出顺序。

 
  1. import java.util.ArrayList;

  2. import java.util.Stack;

  3. public class Solution {

  4. public boolean IsPopOrder(int [] pushA,int [] popA) {

  5. while(pushA.length==0||popA.length==0){

  6. return false;

  7. }

  8. Stack<Integer> stack=new Stack<Integer>();

  9. int index=0;

  10. for(int i=0;i<pushA.length;i++){

  11. stack.push(pushA[i]);

  12. while(!stack.empty()&&stack.peek()==popA[index]){

  13. stack.pop();

  14. index++;

  15. }

  16. }

  17. return stack.empty();

  18. }

  19. }


22.从上往下打印二叉树

题目描述:

从上往下打印出二叉树的每个节点,同层节点从左至右打印。

解题思路:

二叉树层次遍历

 
  1. import java.util.ArrayList;

  2. import java.util.*;

  3. /**

  4. public class TreeNode {

  5. int val = 0;

  6. TreeNode left = null;

  7. TreeNode right = null;

  8.  
  9. public TreeNode(int val) {

  10. this.val = val;

  11.  
  12. }

  13.  
  14. }

  15. */

  16. public class Solution {

  17. public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {

  18. Queue<TreeNode> queue=new LinkedList<TreeNode>();//队列里存的是TreeNode类型的节点!

  19. ArrayList<Integer> list=new ArrayList<Integer>();

  20. if(root==null){//为空的条件一定要考虑到!!!

  21. return list;

  22. }

  23. queue.offer(root);//队列中添加最好用offer,将根节点压入队列

  24. while(!queue.isEmpty()){//每次都会压入当前结点的左右子树,所以直到最后全都压完队列才会变空

  25. TreeNode temp=queue.poll();//每次取出最后一个节点

  26. //放入左右子树

  27. if(temp.left!=null){

  28. queue.offer(temp.left);

  29. }

  30. if(temp.right!=null){

  31. queue.offer(temp.right);

  32. }

  33. list.add(temp.val);

  34. }

  35. return list;

  36. }

  37. }


 

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

题目描述

输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。

如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。

解题思路:

后序遍历,最后一个数是根节点

 
  1. public class Solution {

  2. public boolean VerifySquenceOfBST(int [] sequence) {

  3. //数组为空时返回

  4. if(sequence.length==0){

  5. return false;

  6. }

  7. return subtree(sequence,0,sequence.length-1);

  8. }

  9. public static boolean subtree(int[] a,int st,int root){

  10. //不停地分割数组,最后st>=root时说明分完了,所有的都满足要求,返回true

  11. if(st>=root)

  12. return true;

  13. //最后一个数是根节点,从它前面那个数开始看

  14. int i=root-1;

  15. //根节点前面那个的节点开始找,找到第一个比根节点小的数

  16. while(i>st&&a[i]>a[root]){////!!!!这里要判断i>st

  17. i--;

  18. }

  19. //判断从头到刚刚找到的那个节点之间没有比根结点大的

  20. for(int j=st;j<i;j++){///!!!!这里判断的时候j<i不能有等号!!!!!

  21. if(a[j]>a[root]){//有的话说明不符合二叉搜索树,返回false

  22. return false;

  23. }

  24. }

  25. //判断完后分别看左右子树是否满足二叉搜索树

  26. return subtree(a,st,i)&&subtree(a,i+1,root-1);

  27. }

  28. }

  29.  


24.二叉树中和为某一值的路径【!!!】

题目描述

输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。

路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

解析:原来的那个不是特别好理解~再来一种

在原方法中定义好ArrayList<ArrayList<Integer>> paths,之后就一直用这个,

要用一个方法find来递归,find主要是确定当前是不是叶节点而且当前的target是不是已经等于root.val了,如果是的话把这个path放进paths结果集中

如果还没满足条件,则再递归从左右子树开始找,这里要注意,新建一个path2,复制已经放进root的path,然后左右子树用不同的path开始分头找

 
  1. import java.util.ArrayList;

  2. /**

  3. public class TreeNode {

  4. int val = 0;

  5. TreeNode left = null;

  6. TreeNode right = null;

  7.  
  8. public TreeNode(int val) {

  9. this.val = val;

  10.  
  11. }

  12.  
  13. }

  14. */

  15. public class Solution {

  16. public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {

  17. ArrayList<ArrayList<Integer>> paths=new ArrayList<ArrayList<Integer>>();

  18. if(root==null)

  19. return paths;

  20. find(paths,new ArrayList<Integer>(),root,target);

  21. return paths;

  22. }

  23. public void find(ArrayList<ArrayList<Integer>> paths,ArrayList<Integer> path,TreeNode root,int target){

  24. if(root==null)

  25. return;

  26. path.add(root.val);

  27. if(root.left==null&&root.right==null&&target==root.val){

  28. paths.add(path);

  29. return;

  30. }

  31. ArrayList<Integer> path2=new ArrayList<Integer>();

  32. path2.addAll(path);

  33. find(paths,path,root.left,target-root.val);

  34. find(paths,path2,root.right,target-root.val);

  35.  
  36. }

  37. }


 

 
  1. import java.util.ArrayList;

  2. /**

  3. public class TreeNode {

  4. int val = 0;

  5. TreeNode left = null;

  6. TreeNode right = null;

  7.  
  8. public TreeNode(int val) {

  9. this.val = val;

  10.  
  11. }

  12.  
  13. }

  14. */

  15.  
  16. public class Solution {

  17. private ArrayList<ArrayList<Integer>> listAll=new ArrayList<ArrayList<Integer>>();

  18. private ArrayList<Integer> list=new ArrayList<Integer>();//声明在外面,因为一直要用

  19. public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {

  20. //递推到最后的叶节点时要用到

  21. if(root==null){

  22. return listAll;

  23. }

  24. //遍历到这个节点,啥都不管先加到list里面

  25. list.add(root.val);

  26. target-=root.val;//更新target

  27. //这是说明到达符合要求的叶节点了

  28. if(target==0&&root.left==null&&root.right==null){

  29. listAll.add(new ArrayList<Integer>(list));//新new一个list,原来的list还要一直用

  30. }

  31. //向下找左子树右子树

  32. FindPath(root.right,target);

  33. FindPath(root.left,target);

  34. //遍历到叶节点不符合要求,把它在list里面删掉,回退,然后再继续递归遍历

  35. list.remove(list.size()-1);

  36. return listAll;

  37. }

  38. }


 

25.复杂链表的复制

题目描述

输入一个复杂链表

(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点)

返回结果为复制后复杂链表的head。

(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

解题思路:

map关联

首先遍历一遍原链表,创建新链表(赋值label和next),用map关联对应结点;

再遍历一遍,更新新链表的random指针。(注意map中应有NULL ----> NULL的映射)

 
  1. /*

  2. public class RandomListNode {

  3. int label;

  4. RandomListNode next = null;

  5. RandomListNode random = null;

  6.  
  7. RandomListNode(int label) {

  8. this.label = label;

  9. }

  10. }

  11. */

  12. import java.util.HashMap;

  13. import java.util.Iterator;

  14. import java.util.Map.Entry;

  15. import java.util.Set;

  16. public class Solution {

  17. public RandomListNode Clone(RandomListNode pHead)

  18. {

  19. //声明一个map用来关联原来的节点和新的链表里的节点

  20. HashMap<RandomListNode,RandomListNode> map = new HashMap<RandomListNode,RandomListNode>();

  21. //原来的链表

  22. RandomListNode p = pHead;

  23. //新的链表

  24. RandomListNode q = new RandomListNode(-1);//这里一定要这么定义,不能用null

  25. while(p!=null){

  26. //根据原来的链表节点的值,创建节点

  27. RandomListNode t = new RandomListNode(p.label);

  28. q.next = t;//把新的链表里的节点连起来

  29. q = t;

  30. map.put(p, q);//把原来的链表的节点和新链表里的节点关联起来

  31. p = p.next;//向后移动

  32.  
  33. }

  34. //取得map中的键值对

  35. Set<Entry<RandomListNode,RandomListNode>> set = map.entrySet();

  36. //变成set后用迭代器遍历

  37. Iterator<Entry<RandomListNode,RandomListNode>> it = set.iterator();

  38. while(it.hasNext()){

  39. Entry<RandomListNode, RandomListNode> next = it.next();

  40. //把新链表中的节点的random连上,用了get(),所以连的是新链表的节点

  41. next.getValue().random = map.get(next.getKey().random);

  42. }

  43. //map中键值对里的值,是新的链表

  44. return map.get(pHead);

  45. }

  46. }

26.二叉搜索树与双向链表

输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。

要求不能创建任何新的结点,只能调整树中结点指针的指向。

解题思路:

中序遍历,左中右

最终形成了一个串,左指针指向左边的数,右指针指向右边的数,变成横着的了

跟着程序走一遍

又看了一遍,这道题再换一种方法更好理解

解析:

核心是中序遍历的非递归算法

修改当前遍历节点的指针指向

中序遍历非递归算法是:用一个栈,从根节点开始,一直找左节点,压入栈中,没有左节点后,弹出当前结点,找它的右节点,右节点存在的话,压入栈中,再找右节点的左节点压入栈中,每次都是找不到时弹出当前栈顶节点

 
  1. /**

  2. public class TreeNode {

  3. int val = 0;

  4. TreeNode left = null;

  5. TreeNode right = null;

  6.  
  7. public TreeNode(int val) {

  8. this.val = val;

  9.  
  10. }

  11.  
  12. }

  13. */

  14. import java.util.*;

  15. public class Solution {

  16. public TreeNode Convert(TreeNode pRootOfTree) {

  17. if(pRootOfTree==null)

  18. return null;

  19. Stack<TreeNode> stack=new Stack<TreeNode>();

  20. TreeNode p=pRootOfTree;

  21. TreeNode pre=null;//用于保存中序遍历的上一个节点

  22. boolean isFirst=true;//用这个判断是不是第一次弹出节点,第一次弹出的节点是链表的首节点

  23. TreeNode root=null;//这个是最后链表的头节点,结果返回这个就行

  24. while(!stack.isEmpty()||p!=null){

  25. while(p!=null){

  26. stack.push(p);

  27. p=p.left;//只要还有左节点,就一直压入栈中

  28. }

  29. p=stack.pop();//找不到左节点时,弹出栈顶元素

  30. if(isFirst){//如果是第一次弹出

  31. root=p;//把这个节点给root,这个就是链表的首节点了

  32. pre=root;

  33. isFirst=false;

  34. }else{

  35. pre.right=p;//和前一个节点绑定关系

  36. p.left=pre;

  37. pre=p;//移动

  38. }

  39. p=p.right;//找不到左节点后,弹出栈顶元素要进行一些操作,之后去找右节点

  40. }

  41. return root;

  42. }

  43. }


 

 
  1. /**

  2. public class TreeNode {

  3. int val = 0;

  4. TreeNode left = null;

  5. TreeNode right = null;

  6.  
  7. public TreeNode(int val) {

  8. this.val = val;

  9.  
  10. }

  11.  
  12. }

  13. */

  14. public class Solution {

  15. //!!这两个要声明在外面

  16. TreeNode head=null;

  17. TreeNode realhead=null;//最终形成排序链表的头

  18. public TreeNode Convert(TreeNode pRootOfTree) {

  19.  
  20. ConvertSub(pRootOfTree);

  21. return realhead;

  22. }

  23. //不返回东西,只是把每个节点的左右指针调整成平的,一个挨着一个

  24. public void ConvertSub(TreeNode pRootOfTree){

  25. if(pRootOfTree==null){

  26. return;

  27. }

  28. //先调整左子树

  29. ConvertSub(pRootOfTree.left);

  30. //这一步就是确定最左边的那个realhead

  31. if(head==null){

  32. head=pRootOfTree;

  33. realhead=pRootOfTree;

  34. }else{

  35. //以后的每一步走的都是这里

  36. head.right=pRootOfTree;//让原来的head的右指针指向现在的根

  37. pRootOfTree.left=head;//让现在的根的左指针指向原来的head

  38. head=pRootOfTree;//把原来的head更新一下

  39. }

  40. ConvertSub(pRootOfTree.right);

  41. }

  42. }


 

27.字符串的排列

输入一个字符串,按字典序打印出该字符串中字符的所有排列。

例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。 

结果请按字母顺序输出。 

输入描述:

输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。

解题思路:

有重复元素的全排列

 
  1. import java.util.ArrayList;

  2. import java.util.*;

  3. public class Solution {

  4. public ArrayList<String> Permutation(String str) {

  5.  
  6. ArrayList<String> list=new ArrayList<String>();

  7. if(str!=null&&str.length()>0){//哎呀呀记住一定要判断是否为空

  8. PermutationHelper(str.toCharArray(),0,list);

  9. Collections.sort(list);//用Collection自带的sort,这次就不用考虑顺序的问题了

  10. }

  11.  
  12. return list;

  13. }

  14. public void PermutationHelper(char[] a,int start,ArrayList<String> list){

  15. //交换到最后一个数时,将这个序列输出,添加进list中

  16. if(start==a.length){

  17. list.add(String.valueOf(a));//有char数组转化为String

  18. }

  19. for(int i=start;i<a.length;i++){

  20. //比原来的全排列多了一个判断条件,因为可能有重复的数

  21. if(a[i]!=a[start]||i==start){//要有i==start的判断,否则当所有元素相等时就直接都lue'guo'le

  22. swap(a,i,start);

  23. PermutationHelper(a,start+1,list);

  24. swap(a,i,start);

  25. }

  26. }

  27. }

  28. public static void swap(char[] list, int start, int i) {

  29. char temp;

  30. temp = list[start];

  31. list[start] = list[i];

  32. list[i] = temp;

  33. }

  34. }

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

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。

例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半

因此输出2。如果不存在则输出0。

解题思路:

用hashmap

 
  1. import java.util.*;

  2. public class Solution {

  3. public int MoreThanHalfNum_Solution(int [] array) {

  4. HashMap<Integer,Integer> hash=new HashMap<Integer,Integer>();

  5. for(int i=0;i<array.length;i++){

  6. Integer temp=hash.get(array[i]);

  7. if(temp==null){

  8. hash.put(array[i],1);

  9. temp=1;

  10. }else{

  11. hash.put(array[i],temp+1);

  12. temp++;

  13. }

  14. if(temp>array.length/2){

  15. return array[i];

  16. }

  17. }

  18. return 0;

  19. }

  20. }


29.最小的K个数【还有更好的方法,记得看一下】

输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。

 
  1. import java.util.*;

  2. public class Solution {

  3. public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {

  4. bubble(input,input.length);

  5. ArrayList<Integer> list=new ArrayList<Integer>();

  6. if(input==null || input.length<=0 || input.length<k){//为空的时候一定要注意!每种情况都考虑一下

  7. return list;

  8. }

  9. for(int i=0;i<k;i++){

  10. list.add(input[i]);

  11. }

  12. return list;

  13. }

  14. public static void bubble(int[] a,int n){

  15. for(int i=0;i<n-1;i++){

  16. for(int j=1;j<n-i;j++){

  17. if(a[j-1]>a[j]){

  18. int temp=a[j-1];

  19. a[j-1]=a[j];

  20. a[j]=temp;

  21. }

  22. }

  23. }

  24. }

  25. }


 

30.整数中1出现的次数(从1到n整数中1出现的次数)

题目描述:

求出1~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数?

为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。

可以很快的求出任意非负整数区间中1出现的次数。

 
  1. public class Solution {

  2. public int NumberOf1Between1AndN_Solution(int n) {

  3. int count=0;//记录1出现的次数

  4. for(int i=0;i<=n;i++){

  5. String str=String.valueOf(i);

  6. int len=str.length();

  7. for(int j=0;j<len;j++){

  8. if(str.charAt(j)=='1'){

  9. count++;

  10. }

  11. }

  12. }

  13. return count;

  14. }

  15. }


 

31.把数组排成最小的数

输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。

例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。

解题思路:

先把整型数组换成字符串型数组,元素都变成String类型,然后给它们排序,重写Collections或者Arrays的sort方法,重新定义一下排序规则,然后直接用sort排序,排好序之后,连接起来输出

 
  1. import java.util.ArrayList;

  2. import java.util.*;

  3. public class Solution {

  4. public String PrintMinNumber(int [] numbers) {

  5. int len=numbers.length;

  6. StringBuilder sb=new StringBuilder();

  7. String str[]=new String[len];

  8. for(int i=0;i<len;i++){

  9. str[i]=String.valueOf(numbers[i]);

  10. }

  11. Arrays.sort(str,new Comparator<String>(){

  12. public int compare(String s1,String s2){

  13. String c1=s1+s2;

  14. String c2=s2+s1;

  15. return c1.compareTo(c2);

  16. }

  17. });

  18. for(int i=0;i<len;i++){

  19. sb.append(str[i]);

  20. }

  21. return sb.toString();

  22.  
  23. }

  24. }


32.丑数

把只包含因子2、3和5的数称作丑数(Ugly Number)。

例如6、8都是丑数,但14不是,因为它包含因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。

解题思路:

后面的一个丑数是由前面某一个丑数乘以2,3,4得来的,可以用动态规划去解

 
  1. public class Solution {

  2. public int GetUglyNumber_Solution(int index) {

  3. if(index<=0)

  4. return 0;

  5. if(index==1)

  6. return 1;

  7. //创建一个数组保存所有的丑数

  8. int[] a=new int[index];

  9. a[0]=1;

  10. int t2=0,t3=0,t5=0;最开始的时候是,这三个数哪一个也没用到

  11. for(int i=1;i<index;i++){

  12. a[i]=Math.min(a[t2]*2,Math.min(a[t3]*3,a[t5]*5));

  13. if(a[i]==a[t2]*2)//确定这个数乘以2得到的,t2++记录上,

  14. t2++;

  15. if(a[i]==a[t3]*3)

  16. t3++;

  17. if(a[i]==a[t5]*5)

  18. t5++;

  19. }

  20. return a[index-1];

  21. }

  22. }


 

33.找出字符串中第一个只出现一次的字符
找出字符串中第一个只出现一次的字符
详细描述:
接口说明
原型:
bool FindChar(char* pInputString, char* pChar);
输入参数:
char* pInputString:字符串
输出参数(指针指向的内存区域保证有效):
char* pChar:第一个只出现一次的字符
如果无此字符 请输出'.'
 

输入描述:

输入一串字符,由小写字母组成

输出描述:

输出一个字符

输入例子:

asdfasdfo

输出例子:
o

解题思路:

这道题最后写成了整个程序,没有单独写接口或者函数

用hashMap,而且是LinkedHashMap!!!这个可以保持元素有序!!

 
  1. import java.util.*;

  2. public class Main{

  3. public static char FindChar(String str){

  4. LinkedHashMap<Character,Integer> map=new LinkedHashMap<Character,Integer>();

  5. int n=str.length();

  6. for(int i=0;i<n;i++){

  7. if(map.containsKey(str.charAt(i))){//containsKey这个方法记一下

  8. int time=map.get(str.charAt(i));//

  9. map.put(str.charAt(i),++time);

  10. }else{

  11. map.put(str.charAt(i),1);

  12. }

  13. }

  14. char pos='.';

  15. int i=0;

  16. for(;i<n;i++){

  17. char c=str.charAt(i);

  18. if(map.get(c)==1){

  19. return c;//找到了就在这里返回就行

  20. }

  21. }

  22. return pos;//如果没有找到,最后返回空

  23. }

  24. public static void main(String[] args){

  25. Scanner sc=new Scanner(System.in);

  26. while(sc.hasNext()){

  27. String str=sc.next();

  28. System.out.println(FindChar(str));

  29. }

  30. }

  31. }


 

34.数组中的逆序对

在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007 

输入描述:

 

题目保证输入的数组中没有的相同的数字

数据范围:

对于%50的数据,size<=10^4

对于%75的数据,size<=10^5

对于%100的数据,size<=2*10^5

输入例子:

1,2,3,4,5,6,7,0

输出例子:

7

解析:

归并排序的改进,把数据分成前后两个数组(递归分到每个数组仅有一个数据项),
合并数组,合并时,出现前面的数组值array[i]大于后面数组值array[j]时;则前面
数组array[i]~array[mid]都是大于array[j]的,count += mid+1 - i
参考剑指Offer,但是感觉剑指Offer归并过程少了一步拷贝过程。
还有就是测试用例输出结果比较大,对每次返回的count mod(1000000007)求余

跟着归并排序走一遍就能明白,主要的一步是merge合并的时候要比较一下,那时候如果前面的数大于后面的数就要记录count

之前不知道要怎么把count放进里面,涉及到返回什么样的数据,后来发现,变成全局变量就行,自始至终都在,最后返回count就行

有count的地方记得取mod

 
  1. public class Solution {

  2. int count;//比普通的归并排序多了一个count来记录

  3. public int InversePairs(int[] array){

  4. count=0;

  5. if(array!=null){

  6. sort(array,0,array.length-1);

  7. }

  8. return count;

  9. }

  10. //归并排序

  11. public void sort(int[] a,int low,int high){

  12. int mid=(low+high)/2;

  13. if(low<high){

  14. sort(a,low,mid);

  15. sort(a,mid+1,high);

  16. merge(a,low,mid,high);

  17. }

  18. }

  19. public void merge(int[] a,int low,int mid,int high){

  20. int i=low;

  21. int j=mid+1;

  22. int k=0;

  23. int temp[]=new int[high-low+1];

  24. while(i<=mid&&j<=high){

  25. if(a[i]>a[j]){

  26. temp[k++]=a[j++];

  27. count+=mid-i+1;

  28. count%=1000000007;

  29. }else{

  30. temp[k++]=a[i++];

  31. }

  32. }

  33.  
  34. while(i<=mid){

  35. temp[k++]=a[i++];

  36. }

  37. while(j<=high){

  38. temp[k++]=a[j++];

  39. }

  40. for(int k2=0;k2<temp.length;k2++){

  41. a[k2+low]=temp[k2];

  42. }

  43. }

  44.  
  45.  
  46. }


35.数字在排序数组中出现的次数

统计一个数字在排序数组中出现的次数。

解析:

其实依旧是二分法,改进了一下,找到第一个k和最后一个k

 
  1. public class Solution {

  2. public int GetNumberOfK(int [] array , int k) {

  3. if(array.length==0||array==null)//这里的判断不要忘

  4. return 0;

  5. int first=getFirstK(array,k);

  6. int last=getLastK(array,k);

  7. if(first==-1||last==-1)//这个很重要,如果有一个里面返回-1就说明数组中不存在k,要在这里返回0

  8. return 0;

  9. return last-first+1;//否则一切正常,就用最后一个的索引-第一个索引+1

  10. }

  11. public int getFirstK(int[] a,int k){

  12. int low=0;

  13. int high=a.length-1;

  14. while(low<=high){

  15. int mid=(low+high)/2;

  16. if(a[mid]>k)//这里和二分检索一样

  17. high=mid-1;

  18. else if(a[mid]<k){//这里和二分检索也一样

  19. low=mid+1;

  20. }else{//只有相等时要多判断一下,是不是第一个k

  21. if(mid==0||(mid>0&&a[mid-1]!=k))

  22. return mid;

  23. else

  24. high=mid-1;

  25. }

  26.  
  27. }

  28. return -1;

  29. }

  30. public int getLastK(int[] a,int k){

  31. int low=0;

  32. int high=a.length-1;

  33. while(low<=high){

  34. int mid=(low+high)/2;

  35. if(a[mid]>k)

  36. high=mid-1;

  37. else if(a[mid]<k){

  38. low=mid+1;

  39. }else{

  40. if(mid==a.length-1||(mid<a.length-1&&a[mid+1]!=k))

  41. return mid;

  42. else

  43. low=mid+1;

  44. }

  45.  
  46. }

  47. return -1;

  48. }

  49. }


 

36.二叉树的深度

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度

解析:

递归求解:
假如是空节点,则返回0;
否则,原树的深度由左右子树中深度较的深度加1,为原树的深度。

 
  1. /*

  2. public class TreeNode {

  3. int val = 0;

  4. TreeNode left = null;

  5. TreeNode right = null;

  6. public TreeNode(int val) {

  7. this.val = val;

  8. }

  9. };*/

  10. public class Solution {

  11. public int TreeDepth(TreeNode pRoot)

  12. {

  13. if(pRoot==null)

  14. return 0;

  15. return Math.max(1+TreeDepth(pRoot.left),1+TreeDepth(pRoot.right));

  16. }

  17. }


37.平衡二叉树

输入一棵二叉树,判断该二叉树是否是平衡二叉树。

 
  1. /*

  2. * 输入一棵二叉树,判断该二叉树是否是平衡二叉树

  3. */

  4. public class BalanceTree {

  5. class TreeNode{

  6. TreeNode left;

  7. TreeNode right;

  8. }

  9. //声明了一个全局变量来判断是否是平衡树

  10. private boolean isBalanced=true;

  11. public boolean IsBalanced_Solution(TreeNode root) {

  12. getDepth(root);

  13. return isBalanced;

  14. }

  15. //这个函数其实是在求树的高度

  16. public int getDepth(TreeNode root){

  17. if(root==null)//递归到底部的时候

  18. return 0;

  19. int left=getDepth(root.left);//递归来求树的高度,递归就相当于自底向上了

  20. int right=getDepth(root.right);

  21. //每次求完子树的高度,就判断一下

  22. if(Math.abs(left-right)>1)

  23. isBalanced=false;//不是记为false,但无论如何都要遍历一遍,最后把isBalanced输出来

  24. return right>left?right+1:left+1;

  25. }

  26. }


 

 
  1. /*

  2. * 输入一棵二叉树,判断该二叉树是否是平衡二叉树

  3. */

  4.  
  5. public class BalanceTree2 {

  6. class TreeNode{

  7. TreeNode left;

  8. TreeNode right;

  9. }

  10. //这里用了一个class来传值,声明对象后就可以根据对象来保存这个值n

  11. //这里n其实相当于树的深度

  12. private class Holder{

  13. int n;

  14. }

  15. public boolean IsBalanced_Solution(TreeNode root){

  16. return judge(root,new Holder());

  17. }

  18. public boolean judge(TreeNode root,Holder h){

  19. if(root==null)

  20. return true;

  21. Holder l=new Holder();

  22. Holder r=new Holder();

  23. //这边的两个judge是在递归,先跑到树的最下面

  24. //如果最下面的两个子数都是平衡树,那就判断一下他俩的高度差

  25. if(judge(root.left,l)&&judge(root.right,r)){

  26. if(Math.abs(l.n-r.n)>1)

  27. return false;

  28. h.n+=(l.n>r.n?l.n:r.n)+1;

  29. return true;

  30. }

  31. return false;

  32. }

  33. }


38.数组中只出现一次的数字

一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。

解析:

自己的方法有点笨,就是都存在hashmap里,然后再遍历找到value为1,想想都感觉好笨,,

还看到一种方法是,用map.containsKey()判断key有没有,没有的话,先放进去,在发现有的话,remove出来,这样,最后就剩两个数了

最正规的做法:

异或运算的性质:任何一个数字异或它自己都等于0 。

也就是说,如果我们从头到尾依次异或数组中的每一个数字,那么最终的结果刚好是那个只出现一次的数字,

因为那些出现两次的数字全部在异或中抵消掉了。

如果能够把原数组分为两个子数组。

在每个子数组中,包含一个只出现一次的数字,而其它数字都出现两次。

如果能够这样拆分原数组,按照前面的办法就是分别求出这两个只出现一次的数字了。

我们还是从头到尾依次异或数组中的每一个数字,那么最终得到的结果就是两个只出现一次的数字的异或结果。

因为其它数字都出现了两次,在异或中全部抵消掉了。

由于这两个数字肯定不一样,那么这个异或结果肯定不为0 ,也就是说在这个结果数字的二进制表示中至少就有一位为1 。

我们在结果数字中找到第一个为1 的位的位置,记为第N 位。

现在我们以第N 位是不是1 为标准把原数组中的数字分成两个子数组,

第一个子数组中每个数字的第N 位都为1 ,而第二个子数组的每个数字的第N 位都为0 。

现在我们已经把原数组分成了两个子数组,每个子数组都包含一个只出现一次的数字,而其它数字都出现了两次。

[2*8比2<<3快]

2<<3是左移,是2进制的运算
2*8,还要做很多的运算。
一般,我们都说2进制运算最快。

["<<"这个是左移位运算符],"2<<3"表示2左移3位

2的二进制是00000000 00000000 00000000 00000010
2左移3位,高位的移出,低位的用0填充。
结果:00000000 00000000 00000000 00010000
这个数是16
[m<<n]: 等于m*(2的n次方)
 

5可以表示为:00000101(最高位表示符号,0位正,1为负)
[>>右移]后为00000010

^  按位异或。[相同为0不同为1]

比如二进制     1001 ^ 1100 = 0101
0^0=0,1^1=0 ,1^0 = 1,0^1=1。

& 按位与
int a = 10;
int b =2;
a&b=2 ,按位与,算术运算..1010&0010 = 0010
a&&b = true 并且,逻辑运算.

 
  1. /*

  2. * 一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。

  3. */

  4. public class xorProblem {

  5. public void FindNumsAppearOnce(int[] array,int num1[],int num2[]){

  6. if(array==null||array.length==0)

  7. return;

  8. int temp=0;

  9. for(int i=0;i<array.length;i++){

  10. temp^=array[i];//异或数组中所有的数字

  11. }

  12. //index1是指那两个数异或时第一个出现1的位置

  13. int index1=findFirstBitOne(temp);

  14. //遍历数组,按那一位是1还是0把数组分成两个数组

  15. for(int i=0;i<array.length;i++){

  16. if(isBit(array[i],index1))

  17. num1[0]^=array[i];

  18. else

  19. num2[0]^=array[i];

  20. }

  21. }

  22. //寻找一个数的二进制表示中,第一个1出现的位置,从右到左开始找

  23. public int findFirstBitOne(int num){

  24. int index=0;

  25. //num中的二进制位不停地和1按位与,index标记位数

  26. //不要超过int的bit数就好,int四个字节,每个字节8bit,所以8*4,最好直接写成32

  27. while(((num&1)==0)&&(index)<8*4){

  28. num=num>>1;//对num进行右移,把最右边比较完的数挤出去

  29. ++index;

  30. }

  31. return index;

  32. }

  33. //给出之前找到的index,判断其他数,这一位是不是1

  34. public boolean isBit(int num,int index){

  35. num=num>>index;

  36. return (num&1)==1;

  37. }

  38. }


 

 
  1. import java.util.ArrayList;

  2. public class Solution {

  3. public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {

  4. ArrayList<Integer>list=new ArrayList<Integer>();

  5. for(int i=0;i<array.length;i++)

  6. {

  7. if(!list.contains(array[i]))

  8. list.add(array[i]);

  9. else

  10. list.remove(new Integer(array[i]));

  11. }

  12. if(list.size()>1)

  13. {

  14. num1[0]=list.get(0);

  15. num2[0]=list.get(1);

  16. }

  17. }

  18. }


 

 
  1. //num1,num2分别为长度为1的数组。传出参数

  2. //将num1[0],num2[0]设置为返回结果

  3. import java.util.*;

  4. public class Solution {

  5. public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {

  6. HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();

  7. for(int i=0;i<array.length;i++){

  8. if(map.containsKey(array[i])){

  9. int val=map.get(array[i]);

  10. map.put(array[i],++val);

  11. }else{

  12. map.put(array[i],1);

  13. }

  14. }

  15. int a=0;

  16. for(int i=0;i<array.length;i++){

  17. if(map.get(array[i])==1&&a==0){

  18. num1[0]=array[i];

  19. a++;

  20. }else if(map.get(array[i])==1&&a==1){

  21. num2[0]=array[i];

  22. }

  23. }

  24. }

  25. }


 

39.和为S的连续正数序列

小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck! 

输出描述:

输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序

解析:

根据数学公式计算:(a1+an)*n/2=s  n=an-a1+1
(an+a1)*(an-a1+1)=2*s=k*l(k>l)
an=(k+l-1)/2  a1=(k-l+1)/2

还要求排列是从大到小的排列,给2*s开平方,以内k和L不等,一定是一个在平方根的左边一个在平方根的右边

随便找个例子可以发现L越大,a1越小,

所以从平方根开始找L,不停--,直到2

 
  1. import java.util.ArrayList;

  2. public class Solution {

  3. public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {

  4. ArrayList<ArrayList<Integer>> list=new ArrayList<ArrayList<Integer>>();

  5. if(sum<3)

  6. return list;

  7. int s=(int)Math.sqrt(2*sum);

  8. //这里i相当于L,等于1的时候序列里面只有一个数

  9. for(int i=s;i>=2;i--){

  10. if(2*sum%i==0){

  11. int k=(2*sum)/i;

  12. if(k%2==0&&i%2==1||k%2==1&&i%2==0){//想保证下面式子成立,k和L一定一奇一偶

  13. int a1=(k-i+1)/2;

  14. int an=(k+i-1)/2;

  15. ArrayList<Integer> arr=new ArrayList<Integer>();

  16. for(int j=a1;j<=an;j++){

  17. arr.add(j);

  18. }

  19. list.add(arr);

  20. }

  21. }

  22. }

  23. return list;

  24. }

  25.  
  26. }


40.和为S的两个数字

输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。 

输出描述:

对应每个测试案例,输出两个数,小的先输出。

解析:

原来用了二分查找,比较笨的方法,在输出时还出现了错误,总是大的在前面,其实有比较简单的方法

因为是排好序的数组,所以从两边开始找,比sum大的话,high--,比sum小的话,low++

从两边一夹很容易就找得到

 
  1. import java.util.ArrayList;

  2. public class Solution {

  3. public ArrayList<Integer> FindNumbersWithSum(int [] array,int sum) {

  4. ArrayList<Integer> list=new ArrayList<Integer>();

  5. while(array==null||array.length<2)

  6. return list;

  7. int i=0;

  8. int j=array.length-1;

  9. while(i<j){

  10. if(array[i]+array[j]==sum){

  11. list.add(array[i]);

  12. list.add(array[j]);

  13. return list;

  14. }else if(array[i]+array[j]>sum){

  15. j--;

  16. }else

  17. i++;

  18. }

  19. return list;

  20. }

  21. }


41.左旋转字符串

汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!

解析:

用subString的话还是很简单的

 
  1. public class Solution {

  2. public String LeftRotateString(String str,int n) {

  3. if(str==null||str.length()==0)

  4. return "";//因为要返回string类型,这里不能写成null

  5. int t=n;

  6. if(n>str.length()){

  7. t=n%str.length();

  8. }

  9. String s=str.substring(n,str.length())+str.substring(0,t);//记住substring是这么写,没有大写字母

  10. return s;

  11.  
  12. }

  13. }


42.翻转单词顺序列

例如,“student. a am I”->“I am a student.”

 
  1. public class Solution {

  2. public String ReverseSentence(String str){

  3. StringBuffer sb=new StringBuffer();//字符串拼接时用StringBuffer吧

  4. if(str.length()==0||str.length()==1||str.trim().equals("")){//这里很重要,trim()去掉两边的空格

  5. return str;

  6. }

  7. String[] s=str.split(" ");

  8. int len=s.length;

  9. for(int i=len-1;i>0;i--){

  10. sb.append(s[i]+" ");//先不加上最后一个数,否则还要考虑空格的问题

  11. }

  12. sb.append(s[0]);

  13. return sb.toString();

  14. }

  15. }


43.[编程题]求1+2+3+...+n

求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。

  •  

解析:

1.需利用逻辑与的短路特性实现递归终止。 

2.当n==0时,(n>0)&&((sum+=Sum_Solution(n-1))>0)只执行前面的判断,为false,然后直接返回0;

3.当n>0时,执行sum+=Sum_Solution(n-1),实现递归计算Sum_Solution(n)。

 
  1. public class Solution {

  2. public int Sum_Solution(int n) {

  3. int sum=n;//要等于n不是等于0,想不明白的时候举个例子

  4. boolean t=(n>0)&&((sum+=Sum_Solution(n-1))>0);//这里必须写成一个语句,所以声明了t,

  5. return sum;

  6. }

  7. }


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

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

解析:

约瑟夫环,可以找规律,但感觉通过数组或链表来模拟环还是很方便的

 
  1. public class Solution {

  2. public int LastRemaining_Solution(int n, int m) {

  3. if(n<1||m<1)//先判断这个

  4. return -1;

  5. int count=n;//现在还剩下的人数

  6. int step=0;//每轮走的步数!

  7. int i=-1;//指针,跟着绕,保证环的特征

  8. int[] a=new int[n];

  9. //因为要求出最后剩下的那个的编号,所以不能在删除倒数第二个点的时候就退出,

  10. //要接着去删最后一个点,就可以得到位置了

  11. while(count>0){

  12. i++;//指向数组中的数

  13. if(i>=n)//记住这是一个环,通过i来保持环的特征,编号为0~n-1,所以i变为n时就要清回0了

  14. i=0;

  15. if(a[i]==-1)

  16. continue;//删除点的时候将值变为-1.看到-1,就结束本次循环,直接下次循环

  17. step++;

  18. if(step==m){

  19. a[i]=-1;

  20. step=0;

  21. count--;

  22. }

  23. }

  24. return i;

  25. }

  26. }


 

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的运气如何。为了方便起见,你可以认为大小王是0。

解析:

如果Set集合中不包含要添加的对象,则add添加对象并返回true;否则返回false。


set是接口,不能实例化,所以不能有Set s = new Set();set是接口, 是不能创建对象的. 所以不能有 new Set()这样的写法...

只能实例化接口的实现类,比如HashSet

List list = new ArrayList();

用接口去引用去实现类,是针对接口编程可以很容易的改为其他实现类,比如 LinkedList

只是 List list = new ArrayList() 这么写.. 对于代码的重构有点好处而已... 

而且仅仅适用于, 你只是用了List的接口, 而没有用ArrayList自己单独有的属性和方法... 

 
  1. import java.util.*;

  2. public class Solution {

  3. //判断除0外没有相同元素,而且max-min<5

  4. public boolean isContinuous(int [] numbers) {

  5. if(numbers==null||numbers.length<5)

  6. return false;

  7. Set<Integer> set=new HashSet<Integer>();//set要注意一下

  8. int max=-1;

  9. int min=14;

  10. for(int t:numbers){

  11. if(!set.add(t)&&t!=0)//这个数不为0,而且已经存在,用set很方便

  12. return false;

  13. if(t!=0){

  14. max=Math.max(max,t);

  15. min=Math.min(min,t);

  16. }

  17. }

  18. if(max-min<5)

  19. return true;

  20. return false;

  21. }

  22. }

46.

不用加减乘除做加法

写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。

解析:

一看到这种题就知道要用位运算来解决

let's have a good look

首先看十进制是如何做的:5+7=12

第一步:相加各位的值,不算进位,得到2

第二步:计算进位值,得到10,如果这一步的进位值为0,那么在这一步终止,得到最终结果

第三步:重复上两步,相加的值变成了2+10,得到12,没有进位,进位值为0,循环终止,否则一直相加,直到进位值为0

同样,用这三步来计算二进制相加:5->101,7->111,

第一步:相加各位的值,不算进位,二进制每位相加就相当于做异或操作,101^111=010[相同为0不同为1]

第二步:计算进位值,相当于二进制各位数与,再向左移一位,(101&111)<<1  =  101<<1=1010

第三步:重复上两步:010^1010=1100,(010&1010)<<1=  0,进位值为0,跳出循环,1100为最终结果

 
  1. <span style="font-family:Microsoft YaHei;font-size:14px;">public class Solution {

  2. public int Add(int num1,int num2) {

  3. while(num2!=0){

  4. int temp=num1^num2;

  5. num2=(num1&num2)<<1;

  6. num1=temp;

  7. }

  8. return num1;

  9. }

  10. }</span>

47.把字符串转换成整数

将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0 

输入描述:

输入一个字符串,包括数字字母符号,可以为空

输出描述:

如果是合法的数值表达则返回该数字,否则返回0

输入例子:

+2147483647
    1a33

输出例子:

2147483647
    0

解析:

一、按题意的解法:

把String字符串换成char[] c数组

判断c[0]是否为'-',是的话用记录sign下来,之后算完数的时候要和它相乘,否则默认为正的

然后循环判断里面的每一个字符

先判断c[0]是否为'-'或'+',如果是的话,从c[1]开始循环

判断c[i]在'0'-'9'之间,否则直接return 0

然后想一下怎么按照每位的数字算出最终的数字

每位数字:c[i]-'0'

比如1234

初始化sum=0,开始循环:sum=0*10+1=1,sum=1*10+2=12,sum=12*10+3=123,sum=123*10+4=1234

所以:sum=sum*10+c[i]-'0'

最后循环结束,返回sum*sign

 
  1. public class Solution {

  2. public int StrToInt(String str) {

  3. if(str==""||str.length()==0){

  4. return 0;

  5. }

  6. char[] c=str.toCharArray();

  7. int sign=1;

  8. if(c[0]=='-')

  9. sign=-1;

  10. int sum=0;

  11. for(int i=(c[0]=='-'||c[0]=='+')?1:0;i<c.length;i++){

  12. if(!(c[i]>='0'&&c[i]<='9'))

  13. return 0;

  14. sum=sum*10+c[i]-'0';

  15. }

  16. return sum*sign;

  17. }

  18. }


二、用Java自带的函数~

String s="";

int num=Integer.parseInt(s);

int num=Integer.valueOf(s);

 
  1. public class stringConvertInt {

  2. public static void main(String[] args){

  3. String s="1234";

  4. int num1=Integer.parseInt(s);

  5. int num2=Integer.valueOf(s);

  6. System.out.println(num1);

  7. System.out.println(num2);

  8. }

  9. }


 

48.数组中重复的数字

在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是重复的数字2或者3。

解析:

因为所有数字都在0到n-1的范围内,所以可以新建一个大小为n的boolean数组b[]

遍历原数组,比如,遇到1,就去看b[1]是否为true,如果已经是true说明之前访问过1,原数组中有1,直接把这个1赋给结果数组

否则,b[1]=true,继续遍历,如果遍历完也没有,就返回false,表示没有重复的数字

 
  1. public class Solution {

  2. // Parameters:

  3. // numbers: an array of integers

  4. // length: the length of array numbers

  5. // duplication: (Output) the duplicated number in the array number,length of duplication array is 1,so using duplication[0] = ? in implementation;

  6. // Here duplication like pointor in C/C++, duplication[0] equal *duplication in C/C++

  7. // 这里要特别注意~返回任意重复的一个,赋值duplication[0]

  8. // Return value: true if the input is valid, and there are some duplications in the array number

  9. // otherwise false

  10. public boolean duplicate(int numbers[],int length,int [] duplication) {

  11. boolean[] b=new boolean[length];

  12. for(int i=0;i<length;i++){

  13. if(b[numbers[i]]==true){

  14. duplication[0]=numbers[i];

  15. return true;

  16. }

  17. b[numbers[i]]=true;

  18. }

  19. return false;

  20. }

  21. }


49.构建乘积数组

给定一个数组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]。不能使用除法。

  •  

解析:

第一种方法:

从左到右计算A[0]*A[1]*...*A[i-1]

从右到左计算A[i+1]*...*A[n-1]

比如n=3

b[0]=1  *  A[1]*A[2]

b[1]=A[0]  *  A[2]

b[2]=A[0]*A[1]  *  1

用一个数res来记录不停相乘的A[i],初始化res=1,

循环的时候先令b[i]=res,然后再res=res*A[i],这样现在每个b[i]的值都是A[0]*A[1]*...*A[i-1],【如果是b[0]就先等于1】

然后res再变为1,开始从右到左循环,先令b[i]=b[i]*res,然后再res=res*A[i],现在的res是A[i+1]*...*A[n-1]

 
  1. import java.util.ArrayList;

  2. public class Solution {

  3. public int[] multiply(int[] A) {

  4. int b[]=new int[A.length];

  5. int res=1;

  6. for(int i=0;i<A.length;i++){

  7. b[i]=res;

  8. res=res*A[i];

  9. }

  10. res=1;

  11. for(int i=A.length-1;i>=0;i--){

  12. b[i]=b[i]*res;

  13. res=res*A[i];

  14. }

  15. return b;

  16. }

  17. }


50.正则表达式匹配

请实现一个函数用来匹配包括'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配

解析:

这道题主要是分析好有哪些情况

然后用递归实现!!

一、当模式中第二个字符不是 ' * ' 时

先匹配第一个字符,如果两个字符相等或者,pattern中第一个字符为 ' . ' ,继续向下匹配

如果第一个字符匹配不成功,直接return false

二、当模式中第二个字符是 ' * ' 时【注意,这里要向后看两位有没有*,所以要注意看看有没有超出pattern长度】

[因为,a*可以匹配0~n个字符]

如果第一个字符匹配,则字符串后移1位,pattern后移两位,继续匹配[*匹配1个字符];

或者字符串后移一位,pattern不动,继续匹配[*匹配多个字符];

或者字符串不移动,pattern后移两位,字符串不移动[*匹配0个字符]

如果第一个字符不匹配,[*匹配了0个字符]那么pattern后移两位,字符串不移动,继续匹配

三、得到结果:

当字符串和pattern都匹配结束,返回true

pattern先用完,字符串还剩下没有匹配的,直接返回false

这里没有关于字符串长度的限制,所以在中间匹配时要注意str有没有超过长度

 
  1. public class Solution {

  2. public boolean match(char[] str, char[] pattern)

  3. {

  4. if(str==null||pattern==null)

  5. return false;

  6. int strindex=0;

  7. int patindex=0;

  8. return regex(str,strindex,pattern,patindex);

  9. }

  10. public boolean regex(char[] str,int strindex,char[] pattern,int patindex){

  11. if(strindex==str.length&&patindex==pattern.length)

  12. return true;

  13. if(patindex==pattern.length&&strindex!=str.length)

  14. return false;

  15. if(patindex+1<pattern.length&&pattern[patindex+1]=='*'){

  16. if(strindex!=str.length&&pattern[patindex]==str[strindex]||(pattern[patindex]=='.'&&strindex!=str.length)){

  17. return regex(str,strindex,pattern,patindex+2)||regex(str,strindex+1,pattern,patindex+2)||regex(str,strindex+1,pattern,patindex);

  18. }else{

  19. return regex(str,strindex,pattern,patindex+2);

  20. }

  21. }

  22. if(strindex!=str.length&&(pattern[patindex]==str[strindex]||pattern[patindex]=='.')){

  23. return regex(str,strindex+1,pattern,patindex+1);

  24. }else

  25. return false;

  26. }

  27. }


 

51.

表示数值的字符串

请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。

解析:

一开始在分析各种各样的情况,最后发现用正则表达式最方便

正则表达式:

(1)+、-这两个中只能出现1次或0次:[\\+-]?

(2)无论是在e前面还是在+-后面,还是在小数点前面,都要有数字:[0-9]+

(3)小数点和后面的数字,可能出现一次,或者不出现:(\\.[0-9]+)?

(4)带e的部分是一个整体,可能出现一次,或者不出现:([eE][\\+-]?[0-9]+)?

最后:[\\+-]?[0-9]+(\\.[0-9]+)?([eE][\\+-]?[0-9]+)?

 
  1. public class Solution {

  2. public boolean isNumeric(char[] str) {

  3. String s=String.valueOf(str);

  4. return s.matches("[\\+-]?[0-9]+(\\.[0-9]+)?([eE][\\+-]?[0-9]+)?");

  5. }

  6. }

52.字符流中第一个不重复的字符

请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。 

输出描述:

如果当前字符流没有存在出现一次的字符,返回#字符。

解析:

类似这种判断出现一次两次的问题都可以用hashmap来解决,这里可以用int数组来模拟一下

每个字符占8位,所有字符一共有2^8=256个,所以一个256大的int数组hashtable就够了

Insert的时候,因为插入的是char类型字符

在全局最外面声明一个StringBuffer的对象,每次插入字符,都s.append(ch)【好神奇可以append一个char类型的!!】

然后hashtable[ch]++

只要按原来字符的顺序寻找,看hashtable的值,第一个hashtable[i]=1的字符就是!!

 
  1. public class Solution {

  2. int[] hashtable=new int[256];

  3. StringBuffer sb=new StringBuffer();

  4. //Insert one char from stringstream

  5. public void Insert(char ch)

  6. {

  7. sb.append(ch);

  8. hashtable[ch]++;

  9. }

  10. //return the first appearence once char in current stringstream

  11. public char FirstAppearingOnce()

  12. {

  13. char[] c=sb.toString().toCharArray();//要记得先转换成String类型,在变成char数组

  14. for(char t:c){

  15. if(hashtable[t]==1)

  16. return t;

  17. }

  18. return '#';

  19.  
  20. }

  21. }


53.链表中环的入口结点

一个链表中包含环,请找出该链表的环的入口结点。

解析:

第一种方法:【链表问题常用的方法】

一、两个指针p1和p2,p1每次走1步,p2每次走2步,它们俩一定会在环内的某一处相遇,

假设p1走了x步,那么p2就走了2x步

p2刚好比p1多走了一个环的距离才又赶上p1

环的长度n=2x-x=x

p1其实在环外走了x1步,又在环内走了x-x1步,[还差n-(x-x1)=x1步就走到了入口]

二、现在把p2放回表头,让它们俩同时一起一步一步走,p2走x1步走到入口,p1走x1步也走到入口

不用单独求x1是什么,只需要把p2放在表头,然后让他们移动,相遇的地方就是入口!!

时间复杂度O(N),额外空间复杂度O(1)

【不明白的时候画一个图】

 
  1. /*

  2.  public class ListNode {

  3.     int val;

  4.     ListNode next = null;

  5.  
  6.  
  7.     ListNode(int val) {

  8.         this.val = val;

  9.     }

  10. }

  11. */

  12. public class Solution {

  13.  
  14.  
  15.        public ListNode EntryNodeOfLoop(ListNode pHead)  

  16.    {  

  17.        if(pHead==null||pHead.next==null)

  18.     <span style="white-space:pre"> </span>   return null;

  19.        ListNode p1=pHead;

  20.        ListNode p2=pHead;

  21.        while(p2.next!=null&&p2.next.next!=null){

  22.     <span style="white-space:pre"> </span>   p1=p1.next;

  23.     <span style="white-space:pre"> </span>   p2=p2.next.next;

  24.     <span style="white-space:pre"> </span>   if(p1==p2)

  25.     <span style="white-space:pre"> </span>   break;

  26.        }

  27.        if(p2.next==null||p2.next.next==null)

  28.     <span style="white-space:pre"> </span>   return null;

  29.        p2=pHead;

  30.        while(p2!=p1){

  31.     <span style="white-space:pre"> </span>   p1=p1.next;

  32.     <span style="white-space:pre"> </span>   p2=p2.next;

  33.        }

  34.        return p1;

  35.    }  

  36. }


 

第二种方法:

用hashmap记录节点,ListNode-boolean类型的,如果没有这个节点就放进去,并放一个true,当发现这个节点已经有过了,containsKey()

就说明这个节点是入口

 
  1. /*

  2. public class ListNode {

  3. int val;

  4. ListNode next = null;

  5.  
  6. ListNode(int val) {

  7. this.val = val;

  8. }

  9. }

  10. */

  11. import java.util.*;

  12. public class Solution {

  13.  
  14. public ListNode EntryNodeOfLoop(ListNode pHead)

  15. {

  16. HashMap<ListNode,Boolean> map=new HashMap<ListNode,Boolean>();

  17. while(pHead!=null){

  18. if(map.containsKey(pHead))

  19. return pHead;

  20. map.put(pHead,true);

  21. pHead=pHead.next;

  22. }

  23. return null;

  24. }

  25. }


 

54.删除链表中重复的结点

在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5

解析:

这里是用递归解决的

 
  1. /*

  2. public class ListNode {

  3. int val;

  4. ListNode next = null;

  5.  
  6. ListNode(int val) {

  7. this.val = val;

  8. }

  9. }

  10. */

  11. public class Solution {

  12. public ListNode deleteDuplication(ListNode pHead)

  13. {

  14. if(pHead==null)

  15. return null;

  16. if(pHead.next==null&&pHead!=null)

  17. return pHead;//前面两部分也可以直接换成if(pHead==null||pHead.next==null)return pHead;

  18. ListNode cur=pHead;

  19. if(pHead.val==pHead.next.val){

  20. cur=pHead.next.next;

  21. while(cur!=null&&cur.val==pHead.val){//!!注意!!cur!=null一定要写在前面!!&&这个东西很艮的,只看前面,如果前面的条件不成立,直接不看后面的

  22. cur=cur.next;

  23. }

  24. return deleteDuplication(cur);

  25. }else{

  26. cur=pHead.next;

  27. pHead.next=deleteDuplication(cur);

  28. return pHead;

  29. }

  30.  
  31. }

  32. }

55.二叉树的下一个结点

给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。

解析:

画一个二叉树,求出该二叉树的中序遍历

(1)如果树为空,return null

(2)如果树有右子树,找到右子树最左节点

(3)如果没有右节点,它的下一个节点应该是,以自己为左孩子的父节点,如果自己不是自己父节点的左孩子,就继续向上找

 
  1. /*

  2. public class TreeLinkNode {

  3. int val;

  4. TreeLinkNode left = null;

  5. TreeLinkNode right = null;

  6. TreeLinkNode next = null;

  7.  
  8. TreeLinkNode(int val) {

  9. this.val = val;

  10. }

  11. }

  12. */

  13. public class Solution {

  14. public TreeLinkNode GetNext(TreeLinkNode pNode)

  15. {

  16. if(pNode==null)

  17. return null;

  18. if(pNode.right!=null){//如果右子树不为空

  19. pNode=pNode.right;

  20. if(pNode.left!=null)

  21. pNode=pNode.left;

  22. return pNode;

  23. }

  24. while(pNode.next!=null){//因为要一直往上找

  25. if(pNode.next.left==pNode)

  26. return pNode.next;

  27. pNode=pNode.next;

  28. }

  29. return null;

  30. }

  31. }


56.对称的二叉树

请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

解析:

一看到这种题,就有感觉要用递归来做

判断两个子树是否对称

左子树的左子树应该等于右子树的右子树

左子树的右子树应该等于右子树的左子树

 
  1. <span style="font-family:Microsoft YaHei;">/*

  2. public class TreeNode {

  3. int val = 0;

  4. TreeNode left = null;

  5. TreeNode right = null;

  6.  
  7. public TreeNode(int val) {

  8. this.val = val;

  9.  
  10. }

  11.  
  12. }

  13. */

  14. public class Solution {

  15. boolean isSymmetrical(TreeNode pRoot)

  16. {

  17. if(pRoot==null)//记得判断为空的情况,这个在递归里面判断不了

  18. return true;

  19. return same(pRoot.left,pRoot.right);

  20. }

  21. boolean same(TreeNode leftNode,TreeNode rightNode){

  22. if(leftNode==null&&rightNode!=null)return false;

  23. if(leftNode!=null&&rightNode==null)return false;

  24. if(leftNode==null&&rightNode==null)return true;

  25. if(leftNode.val==rightNode.val)

  26. return same(leftNode.left,rightNode.right)&&same(leftNode.right,rightNode.left);

  27. return false;

  28. }

  29. }</span>

57.按之字形顺序打印二叉树

请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。

解析:

层次遍历+每一层单行输出,这个是之前做过的题,改编一下

定义两个变量,curNum和nextNum来分别保存当前层的节点数和下一层的节点数

初始化时curNum=1,nextNum=0

层次遍历用队列,先把根节点压入,开始循环

弹出队列头节点,输出,curNum--,判断弹出的节点有没有左右孩子,有的话压入队列,每压入一个,nextNum++

判断if(curNum==0),等于0的话说明,这一行已经遍历完了,curNum=nextNum,nextNum=0;

这里每输出一层,按顺序存放在arrayList中,可以用一个标志位flag,true的时候从左到右,false的时候从右到左,每当curNum==0时转换,

转换之前判断是true还是false,true的话正常把这一次的arraylist加到总的结果中,否则,反转这个arraylist后再添加进去

 
  1. import java.util.*;

  2.  
  3. /*

  4. public class TreeNode {

  5. int val = 0;

  6. TreeNode left = null;

  7. TreeNode right = null;

  8.  
  9. public TreeNode(int val) {

  10. this.val = val;

  11.  
  12. }

  13.  
  14. }

  15. */

  16. public class Solution {

  17. public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {

  18. ArrayList<ArrayList<Integer> > res=new ArrayList<ArrayList<Integer> >();

  19. if(pRoot==null)//不要忘记判断

  20. return res;

  21. int curNum=1;

  22. int nextNum=0;

  23. boolean flag=true;

  24. ArrayList<Integer> list=new ArrayList<Integer>();

  25. Queue<TreeNode> queue=new LinkedList<TreeNode>();//记得这里是链表,才能生成的队列

  26. queue.add(pRoot);

  27. while(!queue.isEmpty()){

  28. TreeNode node=queue.poll();

  29. list.add(node.val);

  30. curNum--;

  31. if(node.left!=null){

  32. queue.add(node.left);

  33. nextNum++;

  34. }

  35. if(node.right!=null){

  36. queue.add(node.right);

  37. nextNum++;

  38. }

  39. if(curNum==0){

  40. if(flag)

  41. res.add(list);

  42. else{

  43. res.add(reverse(list));

  44. }

  45.  
  46. flag=!flag;

  47. curNum=nextNum;

  48. nextNum=0;

  49. list=new ArrayList<Integer>();//只有打印完一行才再重新声明

  50. }

  51.  
  52. }

  53. return res;

  54. }

  55. public ArrayList<Integer> reverse(ArrayList<Integer> list){

  56. int len=list.size();

  57. ArrayList<Integer> list2=new ArrayList<Integer>();

  58. for(int i=len-1;i>=0;i--){

  59. list2.add(list.get(i));

  60. }

  61. return list2;

  62. }

  63.  
  64. }

58.

把二叉树打印成多行

从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

解析:这个就是层次遍历按层输出的那个

 
  1. <span style="font-family:Microsoft YaHei;">import java.util.ArrayList;

  2. import java.util.*;

  3.  
  4. /*

  5. public class TreeNode {

  6. int val = 0;

  7. TreeNode left = null;

  8. TreeNode right = null;

  9.  
  10. public TreeNode(int val) {

  11. this.val = val;

  12.  
  13. }

  14.  
  15. }

  16. */

  17. public class Solution {

  18. ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {

  19. ArrayList<ArrayList<Integer> > res=new ArrayList<ArrayList<Integer> >();

  20. if(pRoot==null)

  21. return res;

  22. ArrayList<Integer> list=new ArrayList<Integer>();

  23. Queue<TreeNode> queue=new LinkedList<TreeNode>();

  24. int curNum=1;

  25. int nextNum=0;

  26. queue.add(pRoot);

  27. while(!queue.isEmpty()){

  28. TreeNode node=queue.poll();

  29. list.add(node.val);

  30. curNum--;

  31. if(node.left!=null){

  32. queue.add(node.left);

  33. nextNum++;

  34. }

  35. if(node.right!=null){

  36. queue.add(node.right);

  37. nextNum++;

  38. }

  39. if(curNum==0){

  40. res.add(list);

  41. curNum=nextNum;

  42. nextNum=0;

  43. list=new ArrayList<Integer>();

  44. }

  45. }

  46. return res;

  47. }

  48.  
  49. }</span>

59..序列化二叉树

请实现两个函数,分别用来序列化和反序列化二叉树

解析:

第一种方法:

序列化二叉树,就是把二叉树变成一串字符串,先序遍历,最开始str="",不停往上面加,最后返回str

每遍历一个节点后面加上!,遇到空节点输出#!

遇到空节点返回#!,先加上根节点!,再对根节点的左孩子调用这个方法,然后对根节点的右孩子调用这个方法,最后返回str,递归

反序列化:对用先序遍历序列化的字符串进行反序列化

用到队列,先把字符串用split("!")变成字符串数组,遍历把每个元素添加到队列中,空的时候返回null,这个在后面的递归中要用到

弹出的第一个节点是根节点,然后根节点的左孩子是队列中剩下的元素调用这个函数得到的节点,遍历到#后,说明当前结点的左孩子后面没有东西了,返回当前结点,看他的右孩子,再遍历到#后,再回到当前结点,找到当前结点的父节点,也使用递归实现

!!注意,因为是递归,所以每轮只算自己的!!不用哪一步都str+=

 
  1. /*

  2. public class TreeNode {

  3. int val = 0;

  4. TreeNode left = null;

  5. TreeNode right = null;

  6.  
  7. public TreeNode(int val) {

  8. this.val = val;

  9.  
  10. }

  11.  
  12. }

  13. */

  14. import java.util.*;

  15. public class Solution {

  16. //序列化

  17. String Serialize(TreeNode root) {

  18. if(root==null){

  19. return "#!";//这里return#!就行,不用加上str

  20. }

  21. String str=root.val+"!";//每次只算自己的!!

  22. str+=Serialize(root.left);

  23. str+=Serialize(root.right);

  24. return str;

  25. }

  26. //反序列化!

  27. TreeNode Deserialize(String str) {

  28. Queue<String> queue=new LinkedList<String>();//这里存放的是String类型

  29. String[] s=str.split("!");

  30. for(int i=0;i<s.length;i++){

  31. queue.add(s[i]);

  32. }

  33. return reconPre(queue);

  34. }

  35. public TreeNode reconPre(Queue<String> queue){

  36. String value=queue.poll();

  37. if(value.equals("#"))

  38. return null;

  39. TreeNode head=new TreeNode(Integer.valueOf(value));

  40. head.left=reconPre(queue);

  41. head.right=reconPre(queue);

  42. return head;

  43. }

  44. }


 

第二种方法:

层次遍历来序列化:序列化的时候要用到队列,序列化的字符串是str,初始时为空

最开始判断是否为空,为空的话return #!

先将节点压入队列,队列是TreeNode类型的,然后层次遍历

先压入头节点,当队列不为空的时候,循环,弹出队首的元素,将val!加入到str中,

看看这个节点有没有左孩子右孩子,有的话分别压入队列,没有的话str+"#!" , 循环,

反序列化:先把字符串split("!")拆成String数组

其实反序列化就相当于再来一遍层次遍历,之前用先序遍历时就相当于再来一遍先序遍历。遇到#,表示是null,其他的就是正常节点

声明一个队列,TreeNode类型的,把String数组中第一个数放进去,然后index++,队列不为空的时候循环

取出队首元素,通过一个函数把它变成节点,然后按理来说后面两个是它的左右孩子,判断一下是不是空节点,是的话不要管了,

是正常节点的话以左孩子或者右孩子的身份添加到队列中

思路一定要清晰!!

 
  1. /*

  2. public class TreeNode {

  3. int val = 0;

  4. TreeNode left = null;

  5. TreeNode right = null;

  6.  
  7. public TreeNode(int val) {

  8. this.val = val;

  9.  
  10. }

  11.  
  12. }

  13. */

  14. import java.util.*;

  15. public class Solution {

  16. String Serialize(TreeNode root) {

  17. Queue<TreeNode> queue=new LinkedList<TreeNode>();

  18. if(root==null)

  19. return "#!";

  20. String str=root.val+"!";

  21. queue.add(root);

  22. while(!queue.isEmpty()){

  23. root=queue.poll();

  24. if(root.left!=null){

  25. str+=root.left.val+"!";

  26. queue.add(root.left);

  27. }else{

  28. str+="#!";

  29. }

  30. if(root.right!=null){

  31. str+=root.right.val+"!";

  32. queue.add(root.right);

  33. }else{

  34. str+="#!";

  35. }

  36. }

  37. return str;

  38. }

  39. TreeNode Deserialize(String str) {

  40. String[] s=str.split("!");

  41. Queue<TreeNode> queue=new LinkedList<TreeNode>();

  42. int index=0;//指针在数组中移动

  43. TreeNode head=createNode(s[index++]);

  44. if(head!=null){

  45. queue.add(head);

  46. }

  47. TreeNode node=null;//这个node要放在外面,因为里面一直用一个

  48. while(!queue.isEmpty()){

  49. node=queue.poll();

  50. node.left=createNode(s[index++]);

  51. node.right=createNode(s[index++]);

  52. if(node.left!=null){

  53. queue.add(node.left);

  54. }

  55. if(node.right!=null){

  56. queue.add(node.right);

  57. }

  58.  
  59. }

  60. return head;

  61. }

  62. public TreeNode createNode(String a){

  63. if(a.equals("#"))

  64. return null;

  65. return new TreeNode(Integer.valueOf(a));

  66. }

  67. }

60.数据流中的中位数

如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。

解析:一个最大堆,一个最小堆,最小堆直接就是优先级队列,最大堆要重新定义comparator

想要得到中位数,也就是一个有序数列中的中间那个数,或者中间两个数的平均数

分成两边,平均分放在两个堆里,左边是最大堆,右边是最小堆,保证最小堆里的数一定大于最大堆里的数,

那最后中位数就是,总数为奇数时为最大堆的堆顶(也可以是最小堆的堆顶,看怎么分了),总数为偶数时为最大堆堆顶和最小堆堆顶的平均数

初始时count=0

判断count是奇数还是偶数,【假设最后取中位数,总数为奇数是,中位数为堆顶】,

所以,当前为偶数时,先放进最小堆筛选一下,选出最小的放入最大堆!,然后count++

count为奇数时,先放进最大堆筛选一下,选出最大的放入最小堆,然后count++

求中位数的时候根据count判断,然后取值就好,记得double

 
  1. import java.util.*;

  2. public class Solution {

  3. private PriorityQueue<Integer> minHeap = new PriorityQueue<>();

  4. private PriorityQueue<Integer> maxHeap=new PriorityQueue<Integer>(15,new Comparator<Integer>(){

  5. public int compare(Integer o1,Integer o2){//这个方法要public!!!

  6. return o2-o1;

  7. }

  8. });

  9. private int count=0;

  10. public void Insert(Integer num) {

  11. if(count%2==0){

  12. minHeap.offer(num);

  13. int min=minHeap.poll();

  14. maxHeap.offer(min);

  15. count++;

  16. }else{

  17. maxHeap.offer(num);

  18. int max=maxHeap.poll();

  19. minHeap.offer(max);

  20. count++;

  21. }

  22. }

  23.  
  24. public Double GetMedian() {

  25. if(count%2==0){

  26. return new Double((minHeap.peek()+maxHeap.peek()))/2;

  27. }else

  28. return new Double(maxHeap.peek());

  29. }

  30.  
  31.  
  32. }


 

61.滑动窗口的最大值

给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{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]}。

解析:

用一个双端队列,队列的第一个位置保留窗口最大值,当窗口滑动一次

1.判断当前最大值是否过期

2.新增加值从队尾开始比较,把所有比它小的值丢掉

比如:[2,3,4]中,4放在队列第一个

双端队列中存放的是下标

关于begin 比如序列2 3 4 2 6 2 5 1 ,首先窗口移动3次都还是原来那三个值,不存在过期的问题,当到了第四个数也就是i到了3的时候,双端队列中的头得和begin=0进行比较,如果头头等于0或者小于0,说明最大值过期了,这个begin其实就是i-size+1,

确定

 
  1. import java.util.*;

  2. public class Solution {

  3. public ArrayList<Integer> maxInWindows(int [] num, int size)

  4. {

  5. ArrayList<Integer> res=new ArrayList<Integer>();

  6. if(size==0)

  7. return res;

  8. ArrayDeque<Integer> q=new ArrayDeque<Integer>();

  9. int begin;

  10. for(int i=0;i<num.length;i++){

  11. begin=i-size+1;//这是一个记录,方便后面的边界判断,当前为i的时候,begin是多少会让它失效

  12. if(q.isEmpty()){

  13. q.add(i);

  14. }else if(begin>q.peekFirst()){//判断当前最大值是否过期

  15. q.pollFirst();//最大值已经失效,就拿出来

  16. }

  17. while(!q.isEmpty()&&num[q.peekLast()]<=num[i])//看队列末尾的数是否小于新加入的数,记住是peek不是poll

  18. q.pollLast();

  19. q.add(i);

  20. if(begin>=0){//begin=0后每移动一次,就是一个新的窗口

  21. res.add(num[q.peekFirst()]);

  22. }

  23. }

  24. return res;

  25. }

  26. }


 

62.矩阵中的路径

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。

解析:

回溯的本质就是标记后再去标记,以返回最初的状态。!!

因为任意一个点都可能是起点,所以遍历矩阵中的每一个元素,对每个点进行判断递归,每个点走过之后要标记上,所以用一个int数组flag,1走过,0没走过

每个递归里面用index表示当前走到矩阵中的哪个元素,用k表示匹配到字符串的哪个元素

每次递归里面先求index,

然后判断,i,j,又没有超过边界,还有当前矩阵元素的值与字符串当前的值是否相等,还有flag[index]如果等于1,说明已经走过了,这些都直接返回false

如果已经匹配到字符串的最后一个元素,说明匹配成功,所以return true

出去上面那些情况,只是匹配了当前结点,让flag[index]=1,然后去判断上下左右走能不能正常匹配,这里是递归,如果有一个能走,就返回true

否则,当前结点就算匹配上了也不好使,让flag[index]=0;然后return false

 
  1. public class Solution {

  2. public boolean hasPath(char[] matrix, int rows, int cols, char[] str)

  3. {

  4. int[] flag=new int[matrix.length];//用flag标记这个点有没有走到过

  5. for(int i=0;i<rows;i++){

  6. for(int j=0;j<cols;j++){

  7. if(helper(matrix,rows,cols,i,j,0,str,flag))

  8. return true;

  9. }

  10. }

  11. return false;

  12. }

  13. public boolean helper(char[] matrix,int rows,int cols,int i,int j,int k,char[] str,int[] flag){

  14. int index=i*cols+j;//当前走到哪个点

  15. if(i<0||i>=rows||j<0||j>=cols||matrix[index]!=str[k]||flag[index]==1)

  16. return false;

  17. if(k==str.length-1)//字符串中的最后一个数也匹配上了

  18. return true;

  19. flag[index]=1;//匹配上说明这个点已经走过了

  20. //继续分别看他的上下左右

  21. if(helper(matrix,rows,cols,i-1,j,k+1,str,flag)||helper(matrix,rows,cols,i+1,j,k+1,str,flag)||

  22. helper(matrix,rows,cols,i,j-1,k+1,str,flag)||helper(matrix,rows,cols,i,j+1,k+1,str,flag))

  23. return true;

  24. flag[index]=0;//它的上下左右的不行,所以回退,把之前的标记取消,这一步是最典型的回溯

  25. return false;

  26. }

  27.  
  28.  
  29. }


63.机器人的运动范围

地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?

解析:

其实return那边我有点不太懂,为什么都要加上,,,,

这道题和上面不一样的地方是,这里不用回退,如果标记了1就是走过了,不会让他再变回来

 
  1. public class Solution {

  2. public int movingCount(int threshold, int rows, int cols)

  3. {

  4. int[] flag=new int[(rows+1)*(cols+1)];

  5. return helper(threshold,rows,cols,0,0,flag);

  6. }

  7. public int helper(int threshold,int rows,int cols,int i,int j,int[] flag){

  8. int index=i*cols+j;

  9. if(i<0||i>=rows||j<0||j>=cols||add(i,j)>threshold||flag[index]==1)

  10. return 0;

  11. flag[index]=1;

  12. return 1+helper(threshold,rows,cols,i+1,j,flag)+

  13. helper(threshold,rows,cols,i-1,j,flag)+

  14. helper(threshold,rows,cols,i,j+1,flag)+

  15. helper(threshold,rows,cols,i,j-1,flag);

  16. }

  17. public int add(int i,int j){

  18. int a=i%10+i/10;

  19. int b=j%10+j/10;

  20. return a+b;

  21. }

  22. }

猜你喜欢

转载自blog.csdn.net/fanleiym/article/details/81661257