文章目录
- 1.用两个栈来实现一个队列
- 2.旋转数组的最小数字
- 3.变态跳台阶
- 4.不用加减乘除做加法
- 5.二叉树的镜像
- 6.二叉树的深度
- 7.重建二叉树
- 8.斐波那契数列
- 9.约瑟夫环问题
- 9.1孩子们的游戏(圆圈中最后剩下的数)即约瑟夫环问题
- 10.跳台阶
- 11.矩形覆盖
- 12.二进制中1的个数
- 13.数值的整数次方
- 14.整数中1出现的次数(从1到n的整数中,1出现的次数)
- 15.反转链表
- 16.连续子数组的最大和
- 17.合并两个排序的链表
- 18.两个链表的第一个公共节点
- 19.数组中出现次数超过一半的数字
- 20.数字在升序数组中出现的次数
- 21.数组中只出现一次的数字
- 22.平衡二叉树
- 23.和为S的连续正数序列
- 24.和为S的两个数
- 25.数组中重复的数字
- 26.链表中环的入口结点
- 27.求1+2+3+4+……+n
- 28.栈的压入、弹出序列
- 29.二叉搜索树与双向链表
- 30.二叉树的下一个节点
- 31.左旋转字符串
- 32.链表中倒数第k个结点
- 33.二维数组的查找
- 34. 字符流中第一个不重复的字符
- 35.替换空格
- 36.最小K个数
- 37.包含min函数的栈
- 38.翻转单词顺序
- 39.调整数组顺序使奇数位于偶数前面
- 40.树的子结构
- 41.从上往下打印二叉树
- 42.顺时针打印二维矩阵
- 43.第一个只出现一次的字符
- 44.扑克牌顺子
- 47.全排列2
1.用两个栈来实现一个队列
题目:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路:栈是先进后出;队列是先进先出;创建两个栈,存数据push时放入栈1;取数据时判断栈2是否为空,不为空直接栈2.pop(),如果为空的话,将栈1数据pop然后push入栈2,然后再pop栈2数据(必须确定栈2是否为空)
public class solution{
Stack stack1 = new Stack();
Stack stack2 = new Stack();
public void push(int node){
stack1.push(node);
}
public int pop(){
if(stack2.length==0){
while(stack1.length!=0){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
2.旋转数组的最小数字
题目:把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。
例如数组[3,4,5,1,2]为[1,2,3,4,5]的一个旋转,该数组的最小值为1。
NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
思路一:利用冒泡排序,相当于暴力解法,直接遍历数组找出最小值,当数组很大时,就不太适用;
import java.util.ArrayList;
public class Solution {
public int minNumberInRotateArray(int [] array) {
if(array.length == 0){
return 0;
}
//冒泡排序
int num=array[0];
for(int i=0; i<array.length; i++){
if(array[i]<=num){
num=array[i];
}
}
return num;
}
}
思路二:利用二分法,判断中间值与最左边和最右边的值的大小
import java.util.ArrayList;
public class Solution {
public int minNumberInRotateArray(int [] array) {
int first = 0;
int end = array.length-1;
int mid = (first + end)/2;
while(first < end){
if(end-first==1){
break;
}
mid = (first + end)/2;
if(array[mid] >= array[first]){
first = mid;
}else{
end = mid;
}
}
return array[end];
}
}
思路三:因为是非递减排序(递增数列或者{1,2,3,4,4,4,5,5,6}这样的数组)的数组旋转之后找到第一个小于前一位数的数就是最小值;
import java.util.ArrayList;
public class Solution {
public int minNumberInRotateArray(int [] array) {
if(array.length==0){
return 0;
}
int num=array[0];
for(int i=0; i<array.length; i++){
if(array[i]>array[i+1]){
num = array[i+1];
break;
}
}
return num;
}
}
3.变态跳台阶
一只青蛙一次可以跳上一级台阶,也可以跳上两级台阶……也可以跳上n级,现在有n级台阶,青蛙有多少种方法跳上去。
推导:从第一级台阶直接跳上第n阶,跳上第一阶有f(1)种方法,f(1)=1;
从第二阶直接跳上第n阶,跳上第二阶有f(2)种方法;
……
从第n-1阶直接跳上第n阶,跳上第n-1阶有f(n-1)种方法;
所以:f(n) = f(n-1) + f(n-2) +…+ f(1);
f(n-1) = f(n-2) +f(n-3) +…+ f(1);
f(n) - f(n-1) = f(n-1);
f(n) = 2f(n-1);
因为:f(1) = 1;
f(n) = 2^(n-1);
思路一:运用递归的方法
public class Solution {
public int JumpFloorII(int target) {
if(target == 0){
return 0;
}
if(target == 1){
return 1;
}
else{
return 2*JumpFloorII(target-1);
}
}
}
思路二:推导出公式再写代码就很简单了,直接用公式
public class Solution {
public int JumpFloorII(int target) {
if(target==0){
return 0;
}
int num = 1;
for(int i=1; i<target; i++){
num = num * 2;
}
return num;
}
}
4.不用加减乘除做加法
题目:写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。
思路:整数加法:例如5+7
1.计算各位相加的值,不算进位,得到2
2.计算进位值,得到10,如果这一步的结果是0,那么最终结果就是2
3.重复上面操作,将上面两个结果相加,10+2得到12,进位值为0;
同理,可以计算二进制相加5–101,7–111;
1.将二进制各位相加得到010,二进制每位相加相当于各位做异或操作101^111->010;
2.进位值相加得到1010,二进制进位值计算相当于各位做与操作得到101,然后向左移一位得到1010=(101&111)<<1;
3.重复上面的两步,各位相加010^1010得到1000,进位值010&1010=010,左移一位100;继续重复上述两步,各位相加1000 ^ 100得到1100,进位值计算1000&100=0,跳出循环,结果就是1100;
(1)十进制加法分三步:(以5+17=22为例)
-
只做各位相加不进位,此时相加结果为12(个位数5和7相加不进位是2,十位数0和1相加结果是1);
-
做进位,5+7中有进位,进位的值是10;
-
将前面两个结果相加,12+10=22
public class Solution {
public int Add(int num1,int num2) {
while(num2!=0){
int num = num1^num2;
num2 = (num1&num2)<<1;
num1=num;
}
return num1;
}
}
5.二叉树的镜像
题目:操作给定的二叉树,将其改变为源二叉树的镜像
输入描述:
二叉树的镜像定义:
源二叉树
8 / \ 6 10 / \ / \ 5 7 9 11 镜像二叉树 8 / \ 10 6 / \ / \ 11 9 7 5
思路:运用递归的思路,将二叉树的左子树和右子树调换,然后运用递归将全部的左右子树调换
递归条件:
1.结束条件:当根root为null时,return;
2.不断减小规模:将根root 的左子树和右子树调换;将调换后的左子树和右子树作为新的二叉树
3.调用自身:将调换后的左子树和右子树作为新的二叉树,调用自身的方法;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public void Mirror(TreeNode root) {
if(root == null){
return;
}
if(root.left!=null || root.right!=null){
TreeNode value = root.left;
root.left = root.right;
root.right = value;
Mirror(root.left);
Mirror(root.right);
}
}
}
6.二叉树的深度
题目:输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
思路:运用递归的思路
1.结束条件:当root ==null时,return 0;
2.调用自身:调用自身TreeDepth(),
3.减小规模:调用自身时往下取值,root.left/root.right;返回较大的值加一(加一是加上根节点那一层)
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public int TreeDepth(TreeNode root) {
if(root == null){
return 0;
}
int left = TreeDepth(root.left);
int right = TreeDepth(root.right);
if(right >= left){
return right+1;
}else{
return left+1;
}
}
}
7.重建二叉树
题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
思路:前序遍历:根—左子树—右子树; 中序遍历:左子树—根—右子树; 后序遍历:左子树—右子树—根;
前序遍历的第一个数一定是树的根root,在中序遍历中找到root的位置,然后root左边的是左子树,右边的是右子树;后面使用递归,在划分出来的左子树和右子树中找根,左子树,右子树;
结束条件:当不断切割的pre和in树等于null时,return null;
调用自身&减小规模:将前序遍历和中序遍历的树切割成根,左子树,右子树三个部分,然后把左子树,右子树分别作为pre和in,调用自身;
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.Arrays;
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if(pre.length == 0 || in.length == 0){
return null;
}
TreeNode root = new TreeNode(pre[0]);
for(int i=0; i<in.length; i++){
if(pre[0] == in[i]){
root.left = reConstructBinaryTree(Arrays.copyOfRange(pre,1,i+1),
Arrays.copyOfRange(in,0,i));
root.right = reConstructBinaryTree(
Arrays.copyOfRange(pre,i+1,pre.length),
Arrays.copyOfRange(in,i+1,in.length));
}
}
return root;
}
}
8.斐波那契数列
题目:大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0,第1项是1,n<=39)
递归解法:f(n)=f(n-1)+f(n-2);
public class Solution {
public int Fibonacci(int n) {
if(n == 0){
return 0;
}
if(n == 1){
return 1;
}
return Fibonacci(n-1)+Fibonacci(n-2);
}
}
用for循环实现
public class Solution {
public int Fibonacci(int n) {
if(n==0){
return 0;
}
if(n==1){
return 1;
}
int a=0;
int b=1;
int c=0;
for(int i=2; i<=n; i++){
c=a+b;
a=b;
b=c;
}
return c;
}
}
用数组做:
public class Solution {
public int Fibonacci(int n) {
int[] arr= new int[n+1];
if(n==0){
return 0;
}
if(n==1){
return 1;
}
if(n>1){
arr[0]=0;
arr[1]=1;
for(int i=2; i<=n; i++){
arr[i]=arr[i-1]+arr[i-2];
}
}
return arr[n];
}
}
9.约瑟夫环问题
已知 n 个人(以编号1,2,3 … n 分别表示)围成一圈。从编号为 1 的人开始报数,数到 m 的那个人出列;他的下一个人又从 1 开始报数,数到 m 的那个人又出列;依此规律重复下去,直到最后剩下一个人。要求找出最后出列的人的编号或者按顺序依次输出被淘汰的人的编号。
思路一:用一个数组输入1~n编号,然后每m个输出该编号并从数组中删除该数,(或者将该编号改为-1);
思路二:用循环链表
9.1孩子们的游戏(圆圈中最后剩下的数)即约瑟夫环问题
题目:每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为牛客的资深元老,自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m,让编号为0的小朋友开始报数。每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续0…m-1报数…这样下去…直到剩下最后一个小朋友,可以不用表演,并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!_)。请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从0到n-1)
如果没有小朋友,请返回-1
思路:先创建一个链表节点childNode,然后创建循环单链表;
public class Solution {
public int LastRemaining_Solution(int n, int m) {
childNode first=new childNode(0);
if(n==0){
return -1;
}
if(n==1){
return 0;
}
//将n个小朋友添加进链表,最后节点未指向first
childNode curchild=first;
for(int i=1; i<n; i++){
childNode child=new childNode(i);
curchild.next=child;
curchild=child;
}
//构建循环单链表,,将最后一个节点指向first,并将辅助指针pointer指向最后一个节点
childNode pointer=curchild;
pointer.next=first;
/**
childNode pointer=first;
while(true){
if(pointer.next==null){
pointer.next=first;
break;
}
pointer=pointer.next;
}
*/
//从第0个小朋友开始报数,第m-1个出列,直到最后剩一个
while(true){
if(pointer==first){
break;
}
for(int j=0; j<m-1; j++){
first=first.next;
pointer=pointer.next;
}
first=first.next;
pointer.next=first;
}
return first.no;
}
//链表的长度length
// public static int nodeLength(childNode point){
// if(point.next==null){
// return 1;
// }
// childNode a=point.next;
// int count=0;
// while(a!=point){
// count++;
// a=a.next;
// }
// return count+1;
// }
//创建单链表节点
class childNode{
int no;
childNode next;
public childNode(int no){
this.no=no;
}
}
}
10.跳台阶
题目:一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。
思路:青蛙第一次跳上一级台阶,剩下(n-1)级台阶有f(n-1)种方法;
青蛙第二次跳上两级台阶,剩下(n-2)级台阶有f(n-2)种方法;
所以,青蛙跳上n级台阶共有f(n)=f(n-1)+f(n-2);
f(1)=1;f(2)=2;
相当于斐波那契数列;
直接递归:
public class Solution {
public int JumpFloor(int target) {
if(target == 1){
return 1;
}
if(target == 2){
return 2;
}
return JumpFloor(target-1)+JumpFloor(target-2);
}
}
11.矩形覆盖
题目:我们可以用21的小矩形横着或者竖着去覆盖更大的矩形。请问用n个21的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
比如n=3时,2*3的矩形块有3种覆盖方法:
思路:仍然是斐波那契数列;
public class Solution {
public int RectCover(int target) {
if(target == 1){
return 1;
}
if(target == 2){
return 2;
}
return RectCover(target-1)+RectCover(target-2);
}
}
12.二进制中1的个数
思路一:将n&1得到1或者0,得到1就num++,然后n右移一位(Java的右移代码n>>>1)继续上述操作,直到n=0结束;
public class Solution{
public int NumberOf1(){
int num=0;
while(n!=0){
if((n&1)==1){
num++;
}
n=n>>>1;
}
return num;
}
}
思路二:将n&(n-1),每次会将n最右边的1消掉,循环看n&(n-1)执行了多少次即可;
public class Solution{
public int NumberOf1(){
int count=0;
while(n!=0){
n=n&(n-1);
count++;
}
return count;
}
}
13.数值的整数次方
题目:给定一个double类型的浮点数base和int类型的整数exponent,求base的exponent整数次方。保证base和exponent不同时为0。
思路:一个for循环,需要判断base是否为零,exponent是否为负数;
public class Solution {
public double Power(double base, int exponent) {
double result=1;
if(base==0){
return 0;
}
if(exponent==0){
return 1;
}
if(exponent<0){
base=1/base;
exponent=-exponent;
}
for(int i=0; i<exponent; i++){
result *= base;
}
return result;
}
}
14.整数中1出现的次数(从1到n的整数中,1出现的次数)
题目:求出1-13的整数中1出现的次数,并算出100~1300的整数中1出现的次数?为此他特别数了一下1-13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数)。
思路:遍历从1到n的整数,然后依次对j取余判断与1是否相等,若相等count就加1,然后对j/10;直到j等于0退出循环;返回count值;
public class Solution {
public int NumberOf1Between1AndN_Solution(int n) {
int count=0;
for(int i=1; i<=n; i++){
int j=i;
while(j!=0){
if(j%10==1){
count++;
}
j=j/10;
}
}
return count;
}
}
15.反转链表
题目:输入一个链表,反转此链表,输出反转后的链表头;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null){
return head;
}
ListNode pre=null;
ListNode next=null;
while(head != null){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}
/*
//反转链表
public ListNode ReverseList1(ListNode head) {
if (head == null)
return null; // head为当前节点,如果当前节点为空的话,那就什么也不做,直接返回null;
ListNode pre = null;
ListNode next = null;
// 当前节点是head,pre为当前节点的前一节点,next为当前节点的下一节点
// 需要pre和next的目的是让当前节点从pre->head->next1->next2变成pre<-head next1->next2
// 即pre让节点可以反转所指方向,但反转之后如果不用next节点保存next1节点的话,此单链表就此断开了
// 所以需要用到pre和next两个节点
// 1->2->3->4->5
// 1<-2<-3->4->5
while(head != null){ //注意这个地方的写法,如果写head.next将会丢失最后一个节点
// 做循环,如果当前节点不为空的话,始终执行此循环,此循环的目的就是让当前节点从指向next到指向pre
// 如此就可以做到反转链表的效果
// 先用next保存head的下一个节点的信息,保证单链表不会因为失去head节点的原next节点而就此断裂
next = head.next; //先让head.next指向的节点,即第二个节点叫next
head.next = pre; //将head.next指向pre,也就是说断开head节点与后面的连接
pre = head;//pre,head依次向后移动一个节点,进行下一次反转
head = next;
}
// 如果head为null的时候,pre就为最后一个节点了,但是链表已经反转完毕,pre就是反转后链表的第一个节点
return pre;
}
//合并两个递增的链表并且保证最终的链表也是单调不减的。
*/
16.连续子数组的最大和
题目:HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢?例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。给一个数组,返回它的最大连续子序列的和,你会不会被他忽悠住?(子向量的长度至少是1)
思路:遍历数组,从第一个数开始累加,用total表示,每次累加前判断total值是否大于0,若大于0则继续累加,小于0则将从现在的值重新开始累加,需要设置一个变量max来保存最大值,每次累加完需要判断max和total的大小,保留最大值;
/* 算法时间复杂度O(n) 用total记录累计值,maxSum记录和最大
基于思想:对于一个数A,若是A的左边累计数非负,那么加上A能使得值不小于A,认为累计值对
整体和是有贡献的。如果前几项累计值负数,则认为有害于总和,total记录当前值。
此时 若和大于maxSum 则用maxSum记录下来 */
public class Solution {
public int FindGreatestSumOfSubArray(int[] array) {
if(array == null){
return 0;
}
int total=array[0];
int max=array[0];
for(int i=1; i<array.length; i++){
if(total>=0){
total=total+array[i];
}else{
total=array[i];
}
if(total>max){
max=total;
}
}
return max;
}
}
17.合并两个排序的链表
题目:输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
思路:因为是单调递增的链表,首先新建链表的表头,表头从list1和list2的第一个中的较小值选取;然后接着判断list1和list2后续的值,逐一增加到表头后;最后再判断一下是否list1和list2还有剩余;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1==null){
return list2;
}
if(list2==null){
return list1;
}
//判断头结点
ListNode newhead = null;
if(list1.val <= list2.val){
newhead = list1;
list1 = list1.next;
}else{
newhead = list2;
list2 = list2.next;
}
//合并剩余的元素
ListNode temp = newhead;
while(list1!=null && list2!=null){
if(list1.val<=list2.val){
temp.next=list1;
list1=list1.next;
temp=temp.next;
}else{
temp.next=list2;
list2=list2.next;
temp=temp.next;
}
}
if(list1!=null){
temp.next=list1;
}else{
temp.next=list2;
}
return newhead;
}
}
//递归
/*
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1==null){
return list2;
}
if(list2==null){
return list1;
}
//ListNode newhead = null;
ListNode head = null;
if(list1.val<=list2.val){
head = list1;
head.next = Merge(list1.next, list2);
}
else{
head = list2;
head.next = Merge(list1, list2.next);
}
return head;
}
}
*/
18.两个链表的第一个公共节点
题目:输入两个链表,找出它们的第一个公共结点。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)
思路:两个链表只要有一个公共节点,那么节点后面的节点都相同;
1.首先遍历链表,找到list1和list2两个链表的最后一个节点,判断两个节点是否相同,若不相同说明两个链表没有公共节点;
2.若相同,则有,需让两个链表同时遍历到公共节点;若list1.length>list2.length,则让list1先走(list1-list2)步,再和list2同时往后遍历,等到list1=list2时就是第一个公共节点;同理list2>list1也是相同;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if(pHead1==null || pHead2==null){
return null;
}
//头指针不能动,取两个变量指向头指针
ListNode temp1 = pHead1;
ListNode temp2 = pHead2;
int num1=0;//取两个变量记录链表的长度
int num2=0;
while(temp1.next != null){
num1++;
temp1=temp1.next;
}
while(temp2.next != null){
num2++;
temp2=temp2.next;
}
//判断两个链表最后的节点是否相等
if(temp1 != temp2){
return null;
}
int n=0;
temp1=pHead1;//重新初始化temp1,2
temp2=pHead2;
//让长度长的链表先走都出来的部分
if(num1 >= num2){
n=num1-num2;
while(n != 0){
temp1=temp1.next;
n--;
}
}else{
n=num2-num1;
while(n != 0){
temp2=temp2.next;
n--;
}
}
//同时往后遍历找到相等的节点
while(temp1!=temp2){
temp1=temp1.next;
temp2=temp2.next;
}
return temp1;
}
}
19.数组中出现次数超过一半的数字
题目:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
思路:for循环里包含for循环遍历直接找到次数超过一半的数字
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
//int count=0;
int lg=array.length/2;
for(int i=0; i<array.length; i++){
int count=1;//注意这里count要记为1
for(int j=i+1; j<array.length; j++){
if(array[i]==array[j]){
count++;
}
}
if(count>lg){
return array[i];
}
}
return 0;
}
}
20.数字在升序数组中出现的次数
题目:
思路一:暴力解法;直接遍历数组,累加出数字出现的次数;
public class Solution {
public int GetNumberOfK(int [] array , int k) {
int count=0;
for(int i=0; i<array.length; i++){
if(array[i]==k){
count++;
}
}
return count;
}
}
思路二:利用二分查找(代码可以运行,但超时)
public class Solution {
public int GetNumberOfK(int [] array , int k) {
int first=0;
int end=array.length-1;
int mid=(first+end)/2;
boolean flag=false;
if(array==null){
return 0;
}
//找到k的位置
while(true){
if((end-first)==1){
break;
}
if(array[mid]==k){
flag=true;
break;
}
if(array[mid]>k){
end=mid;
}
if(array[mid]<k){
first=mid;
}
mid=(first+end)/2;
}
//System.out.println(mid);
int count=0;
if(flag){
for(int i=mid; i<array.length; i++){
if(array[i]==k){
count++;
}else{
break;
}
}
for(int i=mid-1; i>=0; i--){
if(array[i]==k){
count++;
}else{
break;
}
}
}
return count;
/*
int i=mid-1;
while(array[i]==k){
if(i==0){
i--;
break;
}
i--;
System.out.println(i);
}
int j=mid+1;
while(array[j]==k){
if(j==array.length-1){
j++;
break;
}
j++;
System.out.println(j);
}
count=j-i-1;
}
return count;
*/
}
}
21.数组中只出现一次的数字
题目:一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
思路:1.遍历数组找到出现两次的数字,将他们都变为-1;(注:要先判断数组array里有没有-1,如果有将-1赋给num1[0]或者num2[0];
2.然后再遍历数组,将不为-1的值取出交给num1[0]和num2[0];
//num1,num2分别为长度为1的数组。传出参数
//将num1[0],num2[0]设置为返回结果
public class Solution {
public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
int count=0;
for(int x : array){
if(x==-1){
count++;
}
}
if(count==1){
num2[0]=-1;
}
for(int i=0; i<array.length; i++){
for(int j=i+1; j<array.length; j++){
if(array[i]==array[j]){
array[i]=-1;
array[j]=-1;
}
}
}
for(int k=0; k<array.length; k++){
if(array[k]!=-1 && num1[0]==0){
num1[0]=array[k];
}
if(array[k]!=-1 && array[k]!=num1[0] && num1[0]!=0 && num2[0]==0){
num2[0]=array[k];
}
}
}
}
22.平衡二叉树
题目:输入一棵二叉树,判断该二叉树是否是平衡二叉树。
在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树
思路:判断任意节点的左子树与右子树的深度相差不超过1,就为平衡二叉树;
'public class Solution {
boolean flag=true;
public boolean IsBalanced_Solution(TreeNode root) {
getLengthTree(root);
return flag;
}
public int getLengthTree(TreeNode root){
if(root == null){
return 0;
}
int left=getLengthTree(root.left);
int right=getLengthTree(root.right);
if(left-right<-1 || left-right>1){
flag=false;
}
return Math.max(left,right)+1;
}
}
23.和为S的连续正数序列
题目:小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!
输出描述:
输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序。
思路:暴力解法
import java.util.ArrayList;
public class Solution {
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer>> n = new ArrayList<ArrayList<Integer>>();
//ArrayList<Integer> a = new ArrayList<Integer>();
for(int i=1; i<sum; i++){
int count=0;
for(int j=i; j<sum; j++){
count = count+j;
ArrayList<Integer> a = new ArrayList<Integer>();
if(count==sum){
for(int k=i; k<=j; k++){
a.add(k);
}
n.add(a);
}
if(count>sum){
break;
}
}
}
return n;
}
}
24.和为S的两个数
题目:输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。
输出描述:
对应每个测试案例,输出两个数,小的先输出。
思路:暴力解法,遍历数组查找;
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> FindNumbersWithSum(int [] array,int sum) {
ArrayList<Integer> a = new ArrayList<Integer>();
int mul=0;
int min=0;//保存最小值
for(int i=0; i<array.length; i++){
for(int j=i+1; j<array.length; j++){
if(array[i]+array[j]==sum){
mul=array[i]*array[j];
if(a.size()==0){
a.add(array[i]);
a.add(array[j]);
min=array[i]*array[j];
break;
}
if(a.size()!=0 && mul<min){
a.clear();
a.add(array[i]);
a.add(array[j]);
min=mul;
break;
}
}
}
}
return a;
}
}
25.数组中重复的数字
题目:在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
思路:简单,遍历数组即可;
public class Solution {
// Parameters:
// numbers: an array of integers
// length: the length of array numbers
// duplication: (Output) the duplicated number in the array number,
// length of duplication array is 1,so using duplication[0] = ? in implementation;
// Here duplication like pointor in C/C++, duplication[0] equal *duplication in C/C++
// 这里要特别注意~返回任意重复的一个,赋值duplication[0]
// Return value: true if the input is valid, and there are some duplications in the array number
// otherwise false
public boolean duplicate(int numbers[],int length,int [] duplication) {
boolean flag=false;
for(int i=0; i<length; i++){
for(int j=i+1; j<length; j++){
if(numbers[i]==numbers[j]){
duplication[0]=numbers[i];
flag=true;
break;
}
}
if(duplication[0]==numbers[i]){
break;
}
}
return flag;
}
}
26.链表中环的入口结点
题目:给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
思路:用双指针不同的速度遍历找出环的节点;
- 第一步,找环中相汇点。分别用p1,p2指向链表头部,
- p1每次走一步,p2每次走二步,直到p1==p2找到在环中的相汇点。
通过141题,我们知道可以通过快慢指针来判断是否有环,现在我们假设两个指针相遇在z点,如图
那么我们可以知道fast指针走过a+b+c+b
slow指针走过a+b
那么2*(a+b) = a+b+c+b
所以a = c
那么此时让slow回到起点,fast依然停在z,两个同时开始走,一次走一步
那么它们最终会相遇在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 || pHead.next==null){
return null;
}
ListNode fast=pHead;
ListNode slow=pHead;
//判断链表中是否有环
while(fast!=null && fast.next!=null){
fast=fast.next.next;
slow=slow.next;
//第一次相等之后使慢指针slow回到起点pHead,然后第二次相等就是环的入口
if(fast==slow){
slow=pHead;
while(fast!=slow){
fast=fast.next;
slow=slow.next;
}
return fast;
}
}
return null;
}
}
27.求1+2+3+4+……+n
题目:求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
思路:利用递归调用的计算求个次数,但是计算终止条件,用&&或运算,代替。注意&&有个重要的性质:A&&B,如果A为false则不会计算B,即到0就会返回。
public class Solution {
public int Sum_Solution(int n) {
int result=n;
boolean b=(n>0) && (result=n+Sum_Solution(n-1))>0;
return result;
}
}
28.栈的压入、弹出序列
题目:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
思路:借助Stack实现,将第一个入栈序列依次压入新建的栈stack,在压入的过程中判断栈顶元素是否与第二个出栈序列中最前面的数相同,若相同,则让其出栈,若不同,则继续入栈,最后判断stack是否为空,若为空,则相等,若不为空,则不相等;
import java.util.ArrayList;
import java.util.Stack;
/**借用一个辅助的栈,遍历压栈顺序,先讲第一个放入栈中,这里是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
….
依次执行,最后辅助栈为空。如果不为空说明弹出序列不是该栈的弹出顺序。
**/
public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
if(pushA==null || popA==null || pushA.length==0 || popA.length==0){
return false;
}
Stack<Integer> stack = new Stack<Integer>();
int index=0;
for(int i=0; i<pushA.length; i++){
stack.push(pushA[i]);
//当栈不为空且栈顶元素等于弹出序列元素时候,就弹出一个,同时让弹出序列后移一个
while(!stack.isEmpty() && stack.peek()==popA[index]){
stack.pop();
index++;
}
}
return stack.isEmpty();
}
}
29.二叉搜索树与双向链表
题目:输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
思路:使用中序遍历,之前做重建二叉树的时候使用过中序遍历但是我总感觉和这个题目说的中序遍历不一样,我看了别人的代码很久才弄懂,主要是那个递归不好想,有点抽象;反正都说是利用中序遍历,可能我还是没有完全理解中序遍历;
1.第一次遍历到最左边的节点时,将pre和first指向这个节点;
2.然后当root为pre的根时,执行pre.right=root; root.left=pre; pre=root; 在pre与root之间构建双向链表然后pre后移;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
TreeNode first=null;
TreeNode pre=null;
public TreeNode Convert(TreeNode pRootOfTree) {
ReConvert(pRootOfTree);
return first;
}
public void ReConvert(TreeNode root){
if(root==null){
return;
}
ReConvert(root.left);
if(pre==null){
pre=root;
first=root;
}else{
pre.right=root;
root.left=pre;
pre=root;
}
ReConvert(root.right);
}
}
30.二叉树的下一个节点
题目:给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
思路:分两种情况,一种为该节点有右子节点,一种为没有右子节点;
1.该节点有右子节点,那么下一个节点就是右子树的最左边的节点;
2.该节点没有右子节点:
*若该节点也没有父节点,则该节点没有下一个节点返回null;
*若该节点为其父节点的左子节点,那么其下一个节点就是该节点的父节点;
*若该节点为其父节点的右子节点,那么如果该节点的父节点是该节点的父节点的父节点的左子节点,那么该节点的父节点的父节点就是下一个节点;如果不是就继续往上找。直到找到是父节点的左子节点就返回改父节点;注意:如果没有的话该节点为最后一个节点,没有下一个节点,返回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 late=null;
//该节点有右子节点
if(pNode.right!=null){
late=pNode.right;
while(late.left!=null){
late=late.left;
}
}else{//该节点没有右子节点
if(pNode.next==null){
return null;
}
else if(pNode==pNode.next.left){
late=pNode.next;
}else{
while(true){
if(pNode.next.next==null || pNode.next==pNode.next.next.left){
break;
}
pNode.next=pNode.next.next;
}
late=pNode.next.next;
}
}
return late;
}
}
/*
下面是简洁的代码
public class Solution {
public TreeLinkNode GetNext(TreeLinkNode pNode){
if(pNode==null){
return null;
}
//该节点有右子节点
if(pNode.right!=null){
pNode=pNode.right;
while(pNode.left!=null){
pNode=pNode.left;
}
return pNode;
}
//该节点没有右子节点
while(pNode.next!=null){
if(pNode.next.left==pNode){
return pNode;
}
pNode=pNode.next;
}
return null;
}
}
31.左旋转字符串
题目:汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
思路:先将要左移的n个字符的后面的字符全部交给一个新的String变量,然后再将要左移的字符添加到变量后,结束;
public class Solution {
public String LeftRotateString(String str,int n) {
if(str==null || str.length()==0){
return str;
}
String reStr="";
n=n%str.length();//防止n大于str的长度,所以对n取余
reStr=str.substring(n,str.length());
reStr +=str.substring(0,n);
return reStr;
}
}
32.链表中倒数第k个结点
题目:输入一个链表,输出该链表中倒数第k个结点。
思路:思路很简单,就是先遍历一遍链表得到链表长度length,然后倒数第k个结点就是(length-k),再遍历到那个结点输出;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(head==null){
return null;
}
int length=0;
ListNode point1=head;
ListNode point2=head;
while(true){
length++;
if(point1.next==null){
break;
}
point1=point1.next;
}
if(k>length){
return null;
}
int num=length-k;
for(int i=0; i<num; i++){
point2=point2.next;
}
return point2;
}
}
33.二维数组的查找
题目:在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
思路一:暴力解法:遍历整个数组找到是否有该整数
public class Solution {
public boolean Find(int target, int [][] array) {
if(array.length==0 || array==null || array[0].length==0){
return false;
}
for(int i=0; i<array.length; i++){
for(int j=0; j<array.length; j++){
if(array[i][j]==target){
return true;
}
}
}
return false;
}
}
思路二:定位到二维数组左下角元素num,将其与要查找的数target比较,target大于num,右移;target小于num,左移;target等于num,return true;
public class Solution {
public boolean Find(int target, int [][] array) {
int row=array.length-1;
int line=0;
while(row>=0 && line<=array[0].length-1){
if(target==array[row][line]){
return true;
}
else if(target > array[row][line]){
line++;
//continue;
}
else{
row--;
}
}
return false;
}
}
34. 字符流中第一个不重复的字符
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
输出描述:
如果当前字符流没有存在出现一次的字符,返回#字符。
思路一:创建一个char数组(char类型和int类型数值在 0-255之内的可以通用,默认初始值是ASCII的0(int);char类型会自动转换成(int型)ASCII进行算术运算)然后存入一个字符,就在char数组中该字符所在位置加1,再将该字符存入StringBuffer类中,遍历是只要判断StringBuffer中字符对应的char数组中该元素的值是否为1即可;
public class Solution {
char[] chars = new char[256];
StringBuffer sb = new StringBuffer();
//Insert one char from stringstream
public void Insert(char ch)
{
sb.append(ch);
chars[ch]++;
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
char[] str = sb.toString().toCharArray();
for(char c : str){
if(chars[c]==1){
return c;
}
}
return '#';
}
}
思路二:HashMap + ArrayList方法
import java.util.HashMap;
import java.util.ArrayList;
public class Solution {
HashMap<Character,Integer> map = new HashMap<>();
ArrayList<Character> array = new ArrayList<>();
//Insert one char from stringstream
public void Insert(char ch)
{
if(map.containsKey(ch)){
int value=map.get(ch)+1;
map.put(ch,value);
}else{
map.put(ch,1);
}
array.add(ch);
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
for(char cr : array){
if(map.get(cr)==1){
return cr;
}
}
return '#';
}
}
35.替换空格
题目:请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
思路一:牺牲空间节省时间,创建一个新的String,遍历StringBuffer,遇到空格就将“%20”加入String,否则就直接加入String;
public class Solution {
public String replaceSpace(StringBuffer str) {
String res="";
for(int i=0; i<str.length(); i++){
if(str.charAt(i)==' '){
res=res+"%20";
}else{
res=res+str.charAt(i);
}
}
return res;
}
}
思路二:牺牲时间节省空间,先遍历StringBuffer,找到空格的数量number,然后将StringBuffer的长度+number*2,在从后往前遍历,遇到空格就将“02%”依次传入,否则直接后移(从后往前排);
public class Solution {
public String replaceSpace(StringBuffer str) {
int count=0;
for(int i=0; i<str.length(); i++){
if(str.charAt(i)==' '){
count++;
}
}
int num=str.length();//保存str的长度
int len=str.length()+count*2;
int k=len-1;
str.setLength(len);//改变str的长度
for(int j=num-1; j>=0; j--){
if(str.charAt(j)==' '){
str.setCharAt(k--,'0');
str.setCharAt(k--,'2');
str.setCharAt(k--,'%');
}else{
str.setCharAt(k--,str.charAt(j));
}
}
return str.toString();
}
}
36.最小K个数
题目:输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4。
思路:将输入的数按从小到大的顺序排列,然后依次输出前K个数;
//冒泡排序,暴力解法
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> array = new ArrayList<>();
if(input.length<k){
return array;
}
int a=0;
for(int i=0; i<input.length; i++){
for(int j=i+1; j<input.length; j++){
if(input[i]>input[j]){
a=input[i];
input[i]=input[j];
input[j]=a;
}
}
}
for(int x=0; x<k; x++){
array.add(input[x]);
}
return array;
}
}
37.包含min函数的栈
题目:定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
思路:构建两个栈,一个用来存数据,另一个辅助栈用来存最小值,
import java.util.Stack;
public class Solution {
Stack<Integer> stack1=new Stack<>();//数值栈
Stack<Integer> stack2=new Stack<>();//辅助栈
public void push(int node) {
stack1.push(node);
if(stack2.size()==0){//如果辅助栈为空,直接入栈
stack2.push(node);
}else{
if(node<=stack2.peek()){//小于等于辅助栈栈顶元素,直接入栈
stack2.push(node);
}else{//否则将栈顶元素再次入栈
stack2.push(stack2.peek());
}
}
}
public void pop() {
stack1.pop();
stack2.pop();
}
public int top() {
return stack1.peek();
}
public int min() {
return stack2.peek();
}
}
38.翻转单词顺序
题目:牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
思路:利用split方法将句子切割为单词数组,然后从后向前遍历数组,将单词在组成String句子,要注意句子全为空格的情况
public class Solution {
public String ReverseSentence(String str) {
String rs="";
String[] newstr=str.split(" ");
//如果str全为空格
if(newstr.length==0){
for(int i=0; i<str.length(); i++){
rs=rs+" ";
}
return rs;
}
for(int j=newstr.length-1; j>=0; j--){
if(j==0){
rs=rs+newstr[j];
}else{
rs=rs+newstr[j]+" ";
}
}
return rs;
}
}
39.调整数组顺序使奇数位于偶数前面
题目:输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
思路:建立两个栈,一个存放奇数,一个存放偶数,遍历数组,将奇数存入栈1,将偶数存入栈2;再将栈2,栈1中的数倒序存入数组;
import java.util.Stack;
public class Solution {
public void reOrderArray(int [] array) {
Stack<Integer> stack1=new Stack<>();//存放奇数
Stack<Integer> stack2=new Stack<>();//存放偶数
int remainder=0;
for(int i=0; i<array.length; i++){
remainder=array[i]%2;
if(remainder==1){
stack1.push(array[i]);
}else{
stack2.push(array[i]);
}
}
for(int j=array.length-1; j>=0; j--){
if(!stack2.isEmpty()){
array[j]=stack2.pop();
}else if(!stack1.isEmpty()){
array[j]=stack1.pop();
}
}
}
}
40.树的子结构
题目:输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
示例1:
思路:第一步:找到与root2根节点相同的节点;
第二步:判断该节点后面的节点是否与root2后的节点都相同;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
//找到root1中和root2的根节点相等的点,然后使用CompareTree方法
//判断root2是不是root1的子结构,如果是的话,返回true,如果不是,继续往下找
public boolean HasSubtree(TreeNode root1,TreeNode root2) {
boolean flag=false;
//因为约定空树不是任意一个树的子结构,所以root1和root2都不能为null
if(root1!=null && root2!=null){
//如果root1的某节点与root2的根节点相同,则继续判断后续节点是否相同
//如果root1的该节点与root2的根节点不相同,则继续往后找与根节点相同的节点
if(root1.val==root2.val){
flag=CompareTree(root1,root2);
}
if(!flag){
flag=HasSubtree(root1.left,root2);
}
if(!flag){
flag=HasSubtree(root1.right,root2);
}
}
return flag;
}
//写一个方法CompareTree,判断root2是不是root1的子结构
public boolean CompareTree(TreeNode root1, TreeNode root2){
//如果root2先遍历完,则root1包含root2,返回true
if(root2==null){
return true;
}
//如果root2没有遍历完,root1遍历完,则返回false
if(root1==null){
return false;
}
//如果root1和root2不匹配,返回false
if(root1.val!=root2.val){
return false;
}
//如果根节点匹配,就去比较左右子节点是否一样
return CompareTree(root1.left,root2.left)&& CompareTree(root1.right,root2.right);
}
}
41.从上往下打印二叉树
题目:从上往下打印出二叉树的每个节点,同层节点从左至右打印。
思路:树的深度遍历用栈或递归,树的层次遍历用队列,每次打印一个节点时,如果该节点有子节点,将子节点加入队列末尾,接下来取出队列的头重复前面的打印动作,直到队列中的所有节点都打印完。
import java.util.ArrayList;
import java.util.*;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
//利用队列,每遍历到一个将其子节点加入队列
ArrayList<Integer> res = new ArrayList<>();
if(root==null){
return res;
}
Queue<TreeNode> queue=new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
TreeNode temp=queue.poll();//取出队列头部元素
res.add(temp.val);
if(temp.left!=null){
queue.add(temp.left);
}
if(temp.right!=null){
queue.add(temp.right);
}
}
return res;
}
}
42.顺时针打印二维矩阵
题目:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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.
思路:
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printMatrix(int [][] matrix) {
ArrayList<Integer> array = new ArrayList<Integer>();
if(matrix==null || matrix.length==0 || matrix[0].length==0){
return array;
}
int row = matrix.length;
int column = matrix[0].length;
int start=0;
while(row>start*2 && column>start*2){
printClockwise(array, matrix, row, column, start);
start=start+1;
}
return array;
}
public static void printClockwise(ArrayList<Integer> array,
int[][] matrix, int row, int column, int start){
int endx=column-1-start;
int endy=row-1-start;
//从左到右打印一行
for(int i=start; i<=endx; i++){
int result=matrix[start][i];
array.add(result);
}
//从上到下打印一列
if(start<endy){
for(int i=start+1; i<=endy; i++){
int result=matrix[i][endx];
array.add(result);
}
}
//从右到左打印一行
if(start<endx && start<endy){
for(int i=endx-1; i>=start; i--){
int result=matrix[endy][i];
array.add(result);
}
}
//从下到上打印一列
if(start<endx && endy-start>1){
for(int i=endy-1; i>start; i--){
int result=matrix[i][start];
array.add(result);
}
}
}
}
43.第一个只出现一次的字符
题目:在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).(从0开始计数)
思路一:暴力解法
public class Solution {
public int FirstNotRepeatingChar(String str) {
int position=0;
while(position<str.length()){
for(int i=0; i<str.length(); i++){
if(i==position){
continue;
}
if(str.charAt(i)==str.charAt(position)){
break;
}
if(i==str.length()-1){
return position;
}
}
position++;
}
return -1;
}
}
思路二:用hash表
利用每个字母的ASCII码作hash来作为数组的index。首先用一个58长度的数组来存储每个字母出现的次数,为什么是58呢,主要是由于A-Z对应的ASCII码为65-90,a-z对应的ASCII码值为97-122,而每个字母的index=int(word)-65,比如g=103-65=38,而数组中具体记录的内容是该字母出现的次数,最终遍历一遍字符串,找出第一个数组内容为1的字母就可以了,时间复杂度为O(n)
public class Solution {
public int FirstNotRepeatingChar(String str) {
int[] word = new int[58];
for(int i=0; i<str.length(); i++){
word[str.charAt(i)-65] += 1;
}
for(int i=0; i<str.length(); i++){
if(word[str.charAt(i)-65]==1){
return i;
}
}
return -1;
}
}
44.扑克牌顺子
题目:描述
现在有2副扑克牌,从扑克牌中随机五张扑克牌,我们需要来判断一下是不是顺子。
有如下规则:
- A为1,J为11,Q为12,K为13,A不能视为14
- 大、小王为 0,0可以看作任意牌
- 如果给出的五张牌能组成顺子(即这五张牌是连续的)就输出true,否则就输出false。
例如:给出数据[6,0,2,0,4]
中间的两个0一个看作3,一个看作5 。即:[6,3,2,5,4]
这样这五张牌在[2,6]区间连续,输出true
数据保证每组5个数字,每组最多含有4个零,数组的数取值为 [0, 13]
思路:就是先将五个数排序,有几个要点
1.找出0的个数zero,再找出数字之间缺失的个数diff,如果zero>=diff,则是顺子,输出true
2.如果五个数中有不为0的相同的数,就直接输出false
import java.util.Arrays;
public class Solution {
public boolean IsContinuous(int [] numbers) {
if(numbers==null || numbers.length==0){
return false;
}
Arrays.sort(numbers);
int zero=0;
int diff=0;
for(int i=0; i<numbers.length-1; i++){
if(numbers[i]==0){
zero++;
}else if(numbers[i]!=numbers[i+1]){
diff += numbers[i+1]-numbers[i]-1;
}else{
return false;
}
}
if(zero>=diff){
return true;
}
return false;
}
}
47.全排列2
class Solution {
//存放结果
List<List<Integer>> result = new ArrayList<>();
//暂存结果
List<Integer> path = new ArrayList<>();
public List<List<Integer>> permuteUnique(int[] nums) {
boolean[] used = new boolean[nums.length];
Arrays.fill(used, false);
Arrays.sort(nums);
backTrack(nums, used);
return result;
}
private void backTrack(int[] nums, boolean[] used) {
if (path.size() == nums.length) {
result.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; i++) {
// used[i - 1] == true,说明同⼀树⽀nums[i - 1]使⽤过
// used[i - 1] == false,说明同⼀树层nums[i - 1]使⽤过
// 如果同⼀树层nums[i - 1]使⽤过则直接跳过
if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false) {
continue;
}
//如果同⼀树⽀nums[i]没使⽤过开始处理
if (used[i] == false) {
used[i] = true;//标记同⼀树⽀nums[i]使⽤过,防止同一树支重复使用
path.add(nums[i]);
backTrack(nums, used);
path.remove(path.size() - 1);//回溯,说明同⼀树层nums[i]使⽤过,防止下一树层重复
used[i] = false;//回溯
}
}
}
}