一、栈的压入、弹出
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
思路:借用一个辅助的栈,遍历压栈顺序,先将第一个放入栈中,这里是1,然后判断栈顶元素是不是出栈顺序的第一个元素,这里是4,很显然1≠4,所以我们继续压栈,直到相等以后开始出栈,出栈一个元素,则将出栈顺序向后移动一位,直到不相等,这样循环等压栈顺序遍历完成,如果辅助栈还不为空,说明弹出序列不是该栈的弹出顺序。
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
Stack<Integer> s=new Stack<Integer>();
if(pushA.length==0||popA.length==0)
return false;
//用于标识弹出序列的位置
int popIndex=0;
for(int i=0;i<pushA.length;i++){
s.push(pushA[i]);
while(!s.empty() &&s.peek()==popA[popIndex]){ //如果栈不为空,且栈顶元素==弹出元素,则弹出
s.pop();
popIndex++; //弹出序列向后移动一位
}
}
return s.empty();
}
}
二、从上往下打印二叉树
从上往下打印出二叉树的每个节点,同层节点从左至右打印
思路:每次打印一个节点,如果该节点有子节点,则把该节点的子节点放到一个队列的末尾。接下来到队列的头部取出最早进入队列的节点,重复前面的打印操作,直至队列中的所有节点都被打印出来为止。
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> a=new ArrayList<Integer>();
ArrayList<TreeNode> queue=new ArrayList<TreeNode>();
if(root==null)
return a;
queue.add(root);
while(queue.size()!=0){
TreeNode temp=queue.remove(0);
if(temp.left!=null)
queue.add(temp.left);
if(temp.right!=null)
queue.add(temp.right);
a.add(temp.val);
}
return a;
}
}
三、后序遍历二叉树
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同
二叉搜索树定义:它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。
思路:判断左子树是否小于根节点,右子树大于根节点。递归
public class Solution {
public boolean VerifySquenceOfBST(int [] sequence) {
if(sequence.length==0){
return false;
}
return isBST(sequence,0,sequence.length-1);
}
public boolean isBST(int [] sequence,int start,int end){
if (end<=start) return true;
int i=start;
for(;i<end;i++){
if(sequence[i]>sequence[end])
break;
}
for(int j=i;j<end;j++){
if(sequence[j]<sequence[end])
return false;
}
return isBST(sequence,0,i-1)&&isBST(sequence,i,end-1);
}
}
四、二叉树中和为某一值的路径
输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
五、复杂链表的复制
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点(next),另一个特殊指针指向任意一个节点)(random),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
思路:1、复制每个节点,如:复制节点A得到A1,将A1插入节点A后面
2、遍历链表,A1->random = A->random->next;
3、将链表拆分成原链表和复制后的链表
public class Solution {
public RandomListNode Clone(RandomListNode pHead)
{
if(pHead==null)return null;
RandomListNode curr=pHead;
//1.复制每个节点,如:复制节点A得到A1,将A1插入节点A后面
while(curr!=null){
RandomListNode pclone=new RandomListNode(curr.label);
pclone.next=curr.next;
pclone.random=null;
curr.next=pclone;
curr=pclone.next;
}
//2.遍历链表,A1->random = A->random->next;
curr=pHead;
while(curr!=null){
RandomListNode pclone=curr.next;
if(curr.random!=null){
pclone.random=curr.random.next;
}
curr=pclone.next;
}
//3.拆分链表
RandomListNode pphead=pHead.next;
curr=pHead;
RandomListNode pclone=pphead;
curr.next=pclone.next;
curr = pclone.next;
while(curr!=null){
pclone.next=curr.next;
pclone=curr.next;
curr.next=pclone.next;
curr=pclone.next;
}
return pphead;
}
}
六、二叉搜索树转换成双向链
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
思路:原先指向左子结点的指针调整为链表中指向前一个结点的指针,指向右子结点的指针,调整为链表中指向后一个结点指针
七、字符串排列
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
八、数组中出现次数超过一半的数字
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
思路:先排序数组,数组中出现次数大于一半的数一定是中间的数,统计中间的数字出现的次数。如果长度超过数组长度的一半,就输出该数字。
import java.util.*;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
int len=array.length;
if(len<1)return 0;
int count=0;
Arrays.sort(array);
int num=array[len/2];
for(int i=0;i<len;i++){
if(array[i]==num){
count++;
}
}
if(count>len/2){
return num;
}
return 0;
}
}
九、最小的K个数
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4
思路:先排序数组,将最小的k个数add到arr中
import java.util.*;
public class Solution {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> arr=new ArrayList<Integer>();
if(input==null||k<=0||k>input.length){
return arr;
}
Arrays.sort(input);
for(int i=0;i<k;i++){
arr.add(input[i]);
}
return arr;
}
}
十、连续子数组的最大和
HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢?例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。给一个数组,返回它的最大连续子序列的和,你会不会被他忽悠住?(子向量的长度至少是1)
思路:定义sum、max为array[0],依次求数组的和,如果sum为负数,则将sum=0;比较sum与max的值,返回max
public class Solution {
public int FindGreatestSumOfSubArray(int[] array) {
if (array.length==0 || array==null) {
return 0;
}
int len=array.length;
int max=array[0];
int sum=array[0];
for(int i=1;i<len;i++){
if(sum<0)sum=0;
sum+=array[i];
if(sum>max){
max=sum;
}
}
return max;
}
}
十一、整数中1出现的次数
求出1~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数)。
十二、把数组排成最小的数
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
import java.util.ArrayList;
import java.util.*;
public class Solution {
public String PrintMinNumber(int [] numbers) {
String s="";
int len=numbers.length;
ArrayList<Integer> a=new ArrayList<Integer>();
for(int i=0;i<len;i++){
a.add(numbers[i]);
}
Collections.sort(a,new Comparator<Integer>(){
public int compare(Integer str1,Integer str2){
String s1=str1+""+str2;
String s2=str2+""+str1;
return s1.compareTo(s2);
}
});
for(int j:a){
s+=j;
}
return s;
}
}
十三、丑数
把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
思路:丑数应该是另一个丑数乘以2、3或者5的结果。建立一个大小为index的数组,比较丑数*2、*3、*5后的最小数,将其按大小放进数组中
public class Solution {
public int GetUglyNumber_Solution(int index) {
if(index<=0)return 0;
int[] a=new int[index];
int count=0;
int i2=0;
int i3=0;
int i5=0;
a[0]=1;
int tmp=0;
while(count<index-1){
tmp=min(a[i2]*2,min(a[i3]*3,a[i5]*5));
if(tmp==a[i2]*2)i2++;
if(tmp==a[i3]*3)i3++;
if(tmp==a[i5]*5)i5++;
a[++count]=tmp;
}
return a[index-1];
}
public int min(int x1,int x2){
return (x1<x2)?x1:x2;}
}
十四、第一个只出现一次的字符
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
思路:定义一个hashmap,扫描两次字符串,第一次扫描的时候统计每个字符出现的次数。第二次扫描时在遇到第一个字符出现的次数为1时,返回i;否则返回-1
import java.util.HashMap;
public class Solution {
public int FirstNotRepeatingChar(String str) {
if(str.length()==0||str==null)
return -1;
HashMap<Character,Integer> map=new HashMap<Character,Integer>();
for (int i=0;i<str.length();i++){
char c=str.charAt(i);
int time=1;
if(map.containsKey(c)){
time++;
map.put(c,time);
}
else{
map.put(c,1);
}
}
for(int i=0;i<str.length();i++){
char c=str.charAt(i);
if(map.get(c)==1)
return i;
}
return -1;
}
}
15.数组中的逆序对
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
16.两个链表的第一个公共结点
两个链表的第一个公共结点
思路:第一步:遍历链表,得到2个链表的长度n1,n2
第二步:计算链表长度差,长的链表先走n1-n2步
第三步:同时遍历链表,返回第一个相同的结点
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode p1=pHead1;
ListNode p2=pHead2;
int n1=len(pHead1);
int n2=len(pHead2);
int n3=0;
if(n1>n2){
n3=n1-n2;
for(int i=0;i<n3;i++){
p1=p1.next;
}
}
else {
n3=n2-n1;
for(int i=0;i<n3;i++){
p2=p2.next;
}
}
while(p1!=null&&p2!=null&&p1!=p2){
p1=p1.next;
p2=p2.next;
}
return p1;
}
public int len(ListNode pHead){
int len=0;
ListNode p1=pHead;
while(p1!=null){
p1=p1.next;
len++;
}
return len;
}
}
17.数字在排序数组中出现的次数
统计一个数字在排序数组中出现的次数。
public class Solution {
public int GetNumberOfK(int [] array , int k) {
int len=array.length;
int count=0;
for(int i=0;i<len;i++){
if(array[i]==k)
count++;
}
return count;
}
}
方法二:二分查找
思路:先查找第一个k的位置,查找该最后一个k的位置,n=last-first+1
public class Solution {
public int GetNumberOfK(int [] array , int k) {
int len=array.length;
if(len<0)return -1;
if(len==0)return 0;
int first=first(array,0,len-1,k);
int last=last(array,0,len-1,k,len);
if(first!=-10&&last!=-1){
int num=last-first+1;
return num;}
return 0;
}
public int first(int[] array,int start,int end,int k){
if(start>end)return -2;
//查找第一个k
int middle=(start+end)/2;
if(array[middle]==k){
if((middle>0&&array[middle-1]!=k)||middle==0)return middle;
else end=middle-1;
}
else if(array[middle]>k)
end=middle-1;
else start=middle+1;
return first(array,start,end,k);
}
public int last(int[] array,int start,int end,int k,int len){
//查找最后一个k
if(start>end)return -1;
int middle=(start+end)/2;
if(array[middle]==k){
if((middle<len-1&&array[middle+1]!=k)||middle==len-1)return middle;
else start=middle+1;
}
else if(array[middle]>k)
end=middle-1;
else start=middle+1;
return last(array,start,end,k,len);
}
}
18.二叉树的深度
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
public class Solution {
public int TreeDepth(TreeNode root) {
int len=0;
if(root==null)return 0;
int left=TreeDepth(root.left);
int right=TreeDepth(root.right);
return (left>right)?(left+1):(right+1);
}
}
19.平衡二叉树
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
平衡二叉树定义:每个结点的左右子树的深度相差不超过1
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root==null)return true;
int left=num(root.left);
int right=num(root.right);
int sub=left-right;
if(sub<-1||sub>1)
return false;
else return true;
}
public int num(TreeNode root){
if(root==null)return 0;
return Math.max(num(root.left),num(root.right))+1;
}
}
20.数组中只出现一次的数字
一个整型数组里除了两个数字之外,其他的数字都出现了偶数次。请写程序找出这两个只出现一次的数字。f
import java.util.HashMap;
import java.util.ArrayList;
public class Solution {
public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
int len=array.length;
int arr[]=new int[2];
HashMap a=new HashMap();
for(int i=0;i<len;i++){
int time=1;
if(!a.containsKey(array[i])){
a.put(array[i],1);
}
else{
time++;
a.put(array[i],time);
}
}
for(int i=0;i<len;i++){
if(a.containsValue(1)){
for(int j=0;j<=1;j++){
arr[j]=array[i];
}
}
}
num1[0]=arr[0];
num2[0]=arr[1];
}
}
思路:
对数组每个数字异或,得到为1的数字位置index;根据数字该位置是否为1,将数组划分为2组;
对两数组异或可得到最终的数字
//num1,num2分别为长度为1的数组。传出参数
//将num1[0],num2[0]设置为返回结果
public class Solution {
public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
if(array.length < 2) return ;
if(array.length==2){
num1[0]=array[0];
num2[0]=array[1];
}
int br=0;
for(int i=0;i<array.length;i++){
br^=array[i];//对数组每一个数字异或,得到为1的数组位置
}
int index=findindex(br);
for(int i=0;i<array.length;i++){
if(isone(array[i],index))
num1[0]^=array[i];
else
num2[0]^=array[i];
}
}
public int findindex(int num){//找到1的位置
int index=0;
if((num&1)==0&&index<32){
num<<=1;
index++;
}
return index;
}
public boolean isone(int num,int index){//根据index位置的数字是否为1将数组分成两半
return ((num>>index)&1)==1;
}
}
21.和为s的连续正数序列
小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!
输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序
思路:设定small=1,big=2;如果从small到big的和curSum==sum,则将这个序列添加到lists;如果curSum小于sum,则增大big,如果curSum大于sum则增大small;
import java.util.ArrayList;
public class Solution {
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer>> lists=new ArrayList<ArrayList<Integer>>();
if(sum<3)return lists;
int small=1;
int big=2;
int middle=(1+sum)/2;
while(small<middle){
int curSum=sum(small,big);
if(curSum==sum){
ArrayList<Integer> list=new ArrayList<Integer>();
for(int i=small;i<=big;i++){
list.add(i);
}
lists.add(list);
small++;big++;
}
else if(curSum<sum)
big++;
else
small++;
}
return lists;
}
public int sum(int start,int end){
int sum=start;
for(int i=start+1;i<=end;i++){
sum+=i;
}
return sum;
}
}
22.和为S的两个数字
输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> FindNumbersWithSum(int [] array,int sum) {
int len=array.length;
ArrayList list=new ArrayList();
if(len<2)return list;
int small=array[0];
int big=array[len-1];
int i=0;
int j=len-1;
while(small<big){
if(small+big==sum){
list.add(small);
list.add(big);
small=array[i++];
big=array[j--];
return list;
}
else if(small+big<sum)
small=array[i++];
else
big=array[j--];
}
return list;
}
}
23.左旋转字符串
汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
思路:首先将字符串转化成字符数组。先翻转前n个数,在翻转后n个数。翻转整个字符数组,最后在转换成字符串
public class Solution {
public String LeftRotateString(String str,int n) {
int len=str.length();
if(len<=0||n<0)return "";
char[] c=str.toCharArray();
reverse(c,0,n-1);
reverse(c,n,len-1);
reverse(c,0,len-1);
StringBuffer b=new StringBuffer();
for(char t:c)b.append(t);
return b.toString();
}
public void reverse(char[] c,int low,int high){
while(low<high){
char temp=c[low];
c[low]=c[high];
c[high]=temp;
low++;
high--;
}
}
}
24.翻转单词顺序列
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
思路:先翻转整个字符串,再分别翻转每个单词
public class Solution {
public String ReverseSentence(String str) {
int len=str.length();
if (str == null || str.equals("") || str.length() == 0)
return "";
char[] c=str.toCharArray();
reverse(c,0,len-1);
int begin=0;int end=0;
while(end<len){
while(begin<len&&c[begin]==' ')
begin++;
while(end<len&&c[end]!=' ')
end++;
reverse(c,begin,end-1);
begin=end;
end++;
}
return new String(c);
}
public void reverse(char[] c,int low,int high){
while(low<high){
char temp=c[low];
c[low]=c[high];
c[high]=temp;
low++;
high--;
}
}
}
25.扑克牌顺子
LL今天心情特别好,因为他去买了一副扑克牌,发现里面居然有2个大王,2个小王(一副牌原本是54张^_^)...他随机从中抽出了5张牌,想测测自己的手气,看看能不能抽到顺子,如果抽到的话,他决定去买体育彩票,嘿嘿!!“红心A,黑桃3,小王,大王,方片5”,“Oh My God!”不是顺子.....LL不高兴了,他想了想,决定大\小 王可以看成任何数字,并且A看作1,J为11,Q为12,K为13。上面的5张牌就可以变成“1,2,3,4,5”(大小王分别看作2和4),“So Lucky!”。LL决定去买体育彩票啦。 现在,要求你使用这幅牌模拟上面的过程,然后告诉我们LL的运气如何, 如果牌能组成顺子就输出true,否则就输出false。为了方便起见,你可以认为大小王是0
思路:1.排序数组,并统计数组中有几个0
2.统计相邻数字之间差几个数,不要统计与0差几个数,如果相邻的数相等,则false
3.如果相邻数差的数小于等于0的个数,返回TRUE 否则false
import java.util.Arrays;
public class Solution {
public boolean isContinuous(int [] numbers) {
//1.排序数组,并统计数组中有几个0
//2.统计相邻数字之间相差的个数
int len=numbers.length;
if(len == 0){
return false;
}
Arrays.sort(numbers);
int num0=0;
int count=0;
for(int i=0;i<len-1;i++){
if (numbers[i]==0){
num0++;
continue;
}
if(numbers[i]==numbers[i+1])return false;
count+=numbers[i+1]-numbers[i]-1;
}
if(num0>=count)return true;
return false;
}
}
26.圆圈中最后剩下的数
每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为牛客的资深元老,自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m,让编号为0的小朋友开始报数。每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续0...m-1报数....这样下去....直到剩下最后一个小朋友,可以不用表演,并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!^_^)。请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从0到n-1)
public class Solution {
public int LastRemaining_Solution(int n, int m) {
if(n<=0||m<=0)return -1;
int[] array=new int[n];
int i=-1;int count=n;int step=0;
while(count>0){
i++;
if(i>=n)i=0;//模拟环
if(array[i] == -1) continue;//跳过被删除的对象
step++;
if(step==m){
//找到待删除的对象。
array[i]=-1;
step=0;
count--;
}
}
return i;
}
}
27.求1+2+......+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)。
public class Solution {
public int Sum_Solution(int n) {
int sum=n;
boolean a=(n>0)&&((sum+=Sum_Solution(n-1))>0);
return sum;
}
}
28.不用加减乘除做加法
写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。
思路:我们可以用三步走的方式计算二进制值相加: 5-101,7-111 第一步:相加各位的值,不算进位,得到010,二进制每位相加就相当于各位做异或操作,101^111。
第二步:计算进位值,得到1010,相当于各位做与操作得到101,再向左移一位得到1010,(101&111)<<1。
第三步重复上述两步, 各位相加 010^1010=1000,进位值为100=(010&1010)<<1。
继续重复上述两步:1000^100 = 1100,进位值为0,跳出循环,1100为最终结果。
public class Solution {
public int Add(int num1,int num2) {
do{
int temp=num1^num2;//1.两个数异或
num2=(num1&num2)<<1;//2.计算进位制,左移一位
num1=temp;
}while(num2!=0);
return num1;
}
}
29.把字符串转换成整数
将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。
输入一个字符串,包括数字字母符号,可以为空,如果是合法的数值表达则返回该数字,否则返回0
思路:1.考虑空字符串
2.数据上下溢出的问题
3.判断正负号
public class Solution {
public int StrToInt(String str) {
int len=str.length();
if(len==0||str==null)return 0;
int start=0;
int flag=0;
//1.判断正负号
if(str.charAt(0)=='-'){
start=1;
flag=1;
}
else if(str.charAt(0)=='+'){
start=1;
flag=0;
}
else{
start=0;
flag=0;
}
long result=0;
for(int i=start;i<len;i++){
char tmp = str.charAt(i);
if((tmp>='0')&&(tmp<='9')){
result=result*10+(tmp-'0');
if(flag==0&&result>Integer.MAX_VALUE)
throw new RuntimeException("向上溢出");
if(flag==1&&result<Integer.MIN_VALUE)
throw new RuntimeException("向下溢出");
}
else return 0;
}
if(flag==0)
return (int)result;
else
return (int)(result*-1);
}
}
30.数组中重复的数字
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
方法一:排序一个数组,如果存在相同的数就返回true
import java.util.Arrays;
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) {
if(length==0||numbers==null)return false;
Arrays.sort(numbers);
for(int i=0;i<length-1;i++){
if(numbers[i]==numbers[i+1]){
duplication[0]=numbers[i];
return true;
}
}
return false;
}
}
方法二:
思路:1.如果没有重复数字,那么数组排序之后第i位=i;
2.从头开始遍历数组,如果第i位不等于i,就交换位置,使第i位等于i。比如2,3,1,0,2,5,3;第0位是2,与下标位不相等,则把它和下标位置为2的1交换,此时第0为1,不等于下标位置,则交换3,1;此时第0位为3,交换0,3;此时第0位为0,接着扫描下一个数字。。第一位为1,第二位为2,第三位为3得到数组0,1,2,3,2,5,3;接下来扫描下标位置为4的数,该数为2,则比较它和下标为2的数字。两数字相等,则出现重复数字。返回true
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) {
if(length==0||numbers==null)return false;
for(int i=0;i<length;i++){
while(numbers[i]!=i){
if(numbers[i]==numbers[numbers[i]]){
duplication[0]=numbers[i];
return true;
}
if(numbers[i]!=i){
int temp=numbers[i];
numbers[i]=numbers[temp];
numbers[temp]=temp;
}
}
}
return false;
}
}
31.构建乘积数组
给定一个数组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]。不能使用除法
思路:分为上三角的乘积b1[i]和下三角的乘积b2[i] 在计算b[i]=b1[i]*b2[i];
import java.util.ArrayList;
public class Solution {
public int[] multiply(int[] A) {
int len=A.length;
if(len<=0)return null;
//构建上三角、下三角
int[] b1=new int[len];//下三角的乘积
int[] b2=new int[len];//上三角的乘积
int[] b=new int[len];
b1[0]=1;
b2[len-1]=1;
for(int i=1;i<len;i++){
b1[i]=b1[i-1]*A[i-1];
}
for(int i=len-2;i>=0;i--){
b2[i]=b2[i+1]*A[i+1];
}
for(int i=0;i<len;i++){
b[i]=b1[i]*b2[i];
}
return b;
}
}
32.正则表达式的匹配
请实现一个函数用来匹配包括'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配
public class Solution {
public boolean match(char[] str, char[] pattern)
{
if (str == null || pattern == null) {
return false;
}
int strIndex = 0;
int patternIndex = 0;
return matchCore(str, strIndex, pattern, patternIndex);
}
public boolean matchCore(char[] str, int strIndex, char[] pattern, int patternIndex) {
//str到尾,pattern到尾,匹配成功
if (strIndex == str.length && patternIndex == pattern.length) {
return true;
}
//str未到尾,pattern到尾,匹配失败
if (strIndex != str.length && patternIndex == pattern.length) {
return false;
}
//str到尾,pattern未到尾(不一定匹配失败,因为a*可以匹配0个字符)
if (strIndex == str.length && patternIndex != pattern.length) {
//只有pattern剩下的部分类似a*b*c*的形式,才匹配成功
if (patternIndex + 1 < pattern.length && pattern[patternIndex + 1] == '*') {
return matchCore(str, strIndex, pattern, patternIndex + 2);
}
return false;
}
//str未到尾,pattern未到尾
if (patternIndex + 1 < pattern.length && pattern[patternIndex + 1] == '*') {
if (pattern[patternIndex] == str[strIndex] || (pattern[patternIndex] == '.' && strIndex != str.length)) {
return matchCore(str, strIndex, pattern, patternIndex + 2)//*匹配0个,跳过
|| matchCore(str, strIndex + 1, pattern, patternIndex + 2)//*匹配1个,跳过
|| matchCore(str, strIndex + 1, pattern, patternIndex);//*匹配1个,再匹配str中的下一个
} else {
//直接跳过*(*匹配到0个)
return matchCore(str, strIndex, pattern, patternIndex + 2);
}
}
if (pattern[patternIndex] == str[strIndex] || (pattern[patternIndex] == '.' && strIndex != str.length)) {
return matchCore(str, strIndex + 1, pattern, patternIndex + 1);
}
return false;
}
}
33.表示数值的字符串
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。
方法一:正则匹配
public class Solution {
public boolean isNumeric(char[] str) {
String string = String.valueOf(str);
return string.matches("[\\+-]?[0-9]*(\\.[0-9]*)?([eE][\\+-]?[0-9]+)?");
}
}
方法二:
public class Solution {
public boolean isNumeric(char[] str) {
if(str==null||str.length==0)return false;
boolean hase=false;
boolean dot=false;
boolean sign=false;
for(int i=0;i<str.length;i++){
char ch=str[i];
if(str[i]=='e'||str[i]=='E'){
if(hase)
return false;
if(i==str.length-1)
return false;
hase=true;
}
else if(str[i]=='+'||str[i]=='-'){
//第二次出现正负号,前面一位一定是e
if(sign&&str[i-1]!='e'&&str[i-1]!='E')
return false;
//第一次出现正负号,且不在开头那么前面一位一定是e
if(!sign&&i>0&&str[i-1]!='e'&&str[i-1]!='E')
return false;
sign=true;
}
else if(str[i]=='.'){
if(hase||dot)
return false;
dot=true;
}
else if(str[i]>'9'||str[i]<'0')
return false;
}
return true;
}
}
34.字符流中第一个不重复的字符
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
如果当前字符流没有存在出现一次的字符,返回#字符。
import java.util.*;
public class Solution {
//Insert one char from stringstream
HashMap<Character, Integer> h=new HashMap();
ArrayList<Character> list=new ArrayList<Character>();
public void Insert(char ch)
{
if(h.containsKey(ch))
h.put(ch,h.get(ch)+1);
else
h.put(ch,1);
list.add(ch);
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
char c='#';
for(char key:list){
if(h.get(key)==1){
c=key;
break;
}
}
return c;
35.链表中环的入口结点
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
思路:
- 第一步,找环中相汇点。分别用p1,p2指向链表头部,p1每次走一步,p2每次走二步,直到p1==p2找到在环中的相汇点。
- 第二步,找环的入口。接上步,当p1==p2时,p2所经过节点数为2x,p1所经过节点数为x,设环中有n个节点,p2比p1多走一圈有2x=n+x; n=x;可以看出p1实际走了一个环的步数,再让p2指向链表头部,p1位置不变,p1,p2每次走一步直到p1==p2; 此时p1指向环的入口。
/*
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 p1=pHead;
ListNode p2=pHead;
while(p2.next!=null&&p1.next!=null){
p1=p1.next;
p2=p2.next.next;
if(p1==p2){
p2=pHead;
while(p1!=p2){
p1=p1.next;
p2=p2.next;
}
if(p1==p2)
return p1;
}
}return null;
}
}
36.删除列表中重复的结点
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
思路:设置一个指针pre指向不重复的结点 设置一个指针last为当前工作指针
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode deleteDuplication(ListNode pHead)
{
if(pHead==null||pHead.next==null)return pHead;
ListNode Head=new ListNode(0);
Head.next=pHead;
ListNode pre=Head;//设置指针pre指向当前不重复的结点
ListNode last=Head.next;//设置last为当前工作指针
while(last!=null){
if(last.next!=null&&last.val==last.next.val){
while(last.next!=null&&last.val==last.next.val){
last=last.next;
}
pre.next=last.next;
last=last.next;
}
else{
pre=pre.next;
last=last.next;
}
}
return Head.next;
}
}
37.二叉树的下一个结点
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
思路:1.如果当前结点有有右子树,下一结点就是右子树的最左子节点
2.如果当前结点没有右子树,如果当前结点是下一结点的左子结点,那么下一结点就是父节点
/*
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)
{
if(pNode==null)return null;
//1.当前结点有有右子树,那么下一结点就是右子树的最左子节点
if(pNode.right!=null){
pNode=pNode.right;
while(pNode.left!=null){
pNode=pNode.left;
}
return pNode;
}
//2.当前结点没有右子树
while(pNode.next!=null){
if(pNode.next.left==pNode)return pNode.next;//当前结点是下一结点的左子树,那么下一结点就是该节点的父节点
pNode=pNode.next;
}
return null;
}
}
38.对称的二叉树
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
boolean isSymmetrical(TreeNode pRoot)
{
return issame(pRoot,pRoot);
}
boolean issame(TreeNode pRoot1,TreeNode pRoot2){
if(pRoot1==null&&pRoot2==null)
return true;
if(pRoot1==null||pRoot2==null)
return false;
if(pRoot1.val!=pRoot2.val)
return false;
return issame(pRoot1.left,pRoot2.right)&&issame(pRoot1.right,pRoot2.left);
}
}
39.按之字形顺序打印二叉树
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
思路:设置两个栈,奇数行保存在栈1中,因为奇数行要从左到右打印,所以入栈顺序先右后左
偶数行保存在栈2中,因为偶数行要从右往左打印,所以入栈顺序要先左后右
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<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> list=new ArrayList<ArrayList<Integer>>();
if(pRoot==null)return list;
Stack s1=new Stack();//奇数行,要求从左到右打印,那么压栈顺序就应是先右再左
Stack s2=new Stack();//偶数行,要求从右向左打印,那么压栈顺序就应是先左后右
s1.push(pRoot);
ArrayList<Integer> arr=new ArrayList<Integer>();
while(true){
while(s1.size()!=0){
TreeNode node=(TreeNode)s1.pop();
arr.add(node.val);
if(node.left!=null)
s2.push(node.left);
if(node.right!=null)
s2.push(node.right);
}
list.add(arr);
arr=new ArrayList<Integer>();
if(s1.size()==0&&s2.size()==0)
break;
while(s2.size()!=0){
TreeNode node=(TreeNode)s2.pop();
arr.add(node.val);
if(node.right!=null)
s1.push(node.right);
if(node.left!=null)
s1.push(node.left);
}
list.add(arr);
arr=new ArrayList<Integer>();
if(s1.size()==0&&s2.size()==0)
break;
}
return list;
}
}
40.把二叉树打印成多行
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行
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 {
ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> list=new ArrayList<ArrayList<Integer>>();
if(pRoot==null)return list;
Queue<TreeNode> layer=new LinkedList<TreeNode>();
ArrayList<Integer> layerlist=new ArrayList<Integer>();
int start=0;
int end=1;//start记录本层要打印多少个,end记录下一层要打印多少个
layer.add(pRoot);
while(!layer.isEmpty()){
TreeNode node=(TreeNode)layer.remove();
layerlist.add(node.val);
start++;
if(node.left!=null)
layer.add(node.left);
if(node.right!=null)
layer.add(node.right);
if(start==end){//本层打印完毕
end=layer.size();//此时的layer中存储的都是下一层的结点,则end就为layer的大小
start=0;
list.add(layerlist);
layerlist = new ArrayList<Integer>();//重置layerlist
}
}
return list;
}
}
41.序列化二叉树
请实现两个函数,分别用来序列化和反序列化二叉树
序列化:把二叉树变成字符串,#表示空结点,!表示一个结点值的结束
反序列化:把字符串恢复成二叉树,当前遍历元素为 # 则表示此子树已结束,遍历下一元素作为上一结点的右儿子
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
//序列化
String Serialize(TreeNode root) {
if(root==null)
return "";
StringBuffer sb=new StringBuffer();
Serialize1(root,sb);
return sb.toString();
}
void Serialize1(TreeNode root,StringBuffer sb){
if(root==null){
sb.append("#!");
return;
}
sb.append(root.val);
sb.append("!");
Serialize1(root.left,sb);
Serialize1(root.right,sb);
}
//反序列化
TreeNode Deserialize(String str) {
if("".equals(str))
return null;
String[] string =str.split("!");
return Deserialize1(string);
}
int index=-1;
TreeNode Deserialize1(String[] str){
index++;
if(!str[index].equals("#")){
TreeNode root=new TreeNode(0);
root.val=Integer.parseInt(str[index]);
root.left=Deserialize1(str);
root.right=Deserialize1(str);
return root;
}
return null;
}
}
42.二叉搜索树的第k个结点
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
思路:二叉搜索树,中序遍历的结果是从小到大排序
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
int index=0;
TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot!=null){
TreeNode node=KthNode(pRoot.left,k);
if(node!=null)
return node;
index++;
if(index==k)
return pRoot;
node=KthNode(pRoot.right,k);
if(node!=null)
return node;
}
return null;
}
}
43.数据流中的中位数
如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。
方法一:
import java.util.*;
public class Solution {
ArrayList<Integer> list=new ArrayList<Integer>();
public void Insert(Integer num) {
list.add(num);
}
public Double GetMedian() {
if(list.size()<1)
return 0.0;
if(list.size()%2==1){
Collections.sort(list);
return Double.valueOf(list.get(list.size()/2));
}
else{
Collections.sort(list);
Double num1=Double.valueOf(list.get(list.size()/2));
Double num2=Double.valueOf(list.get(list.size()/2-1));
return (num1+num2)/2;
}
}
}
方法二:
44.滑动窗口的最大值
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{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]}
方法一
import java.util.*;
public class Solution {
public ArrayList<Integer> maxInWindows(int [] num, int size)
{
ArrayList<Integer> arr=new ArrayList<Integer>();
int len=num.length;
if(len<1||size>len||size<=0)return arr;
for(int i=0;i<len-size+1;i++){
int max=num[i];
for(int j=i;j<i+size;j++){
if(num[j]>max)
max=num[j];
} arr.add(max);
}
return arr;
}
}
方法二
import java.util.*;
public class Solution {
public ArrayList<Integer> maxInWindows(int [] num, int size)
{
ArrayList<Integer> arr=new ArrayList<Integer>();
int len=num.length;
if(len<1||size<=0||size>len)return arr;
Deque<Integer> dq= new ArrayDeque<Integer>();
//处理第一个滑动窗口
for(int i=0;i<size;i++){
while(!dq.isEmpty()&&num[i]>=num[dq.getLast()]){
dq.removeLast();
}
dq.addLast(i);
}
//后续滑动窗口,每移动一位产生一个滑动窗口,同时直接取队首元素获得滑动窗口最大值
for(int j=size;j<len;j++){
arr.add(num[dq.getFirst()]);
while(dq.size()!=0&&num[j]>=num[dq.getLast()]){
dq.removeLast();
}
if(dq.size()!=0&&(j-dq.getFirst())>=size)
dq.removeFirst();
dq.addLast(j);
}
arr.add(num[dq.getFirst()]);
return arr;
}
}
45.矩阵中的路径
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。