面试题目汇总(JAVA算法/数据结构)

原文:https://blog.csdn.net/zyx520ytt/article/details/72466255


1.题目:输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。

代码:

[java]  view plain  copy
  1. import java.util.ArrayList;  
  2. import java.util.Collections;  
  3. import java.util.Comparator;  
  4. import java.util.Iterator;  
  5.   
  6. public class Solution {  
  7.     public static String PrintMinNumber(int [] numbers) {  
  8.         String result = "";  
  9.         int length=numbers.length;  
  10.         if(length<1){  
  11.             return result;  
  12.         }  
  13.         ArrayList<Integer> list=new ArrayList<Integer>();  
  14.         for(int i=0;i<length;i++){  
  15.             list.add(numbers[i]);  
  16.         }  
  17.         Collections.sort(list,new Comparator<Integer>() {  
  18.             @Override  
  19.             public int compare(Integer o1, Integer o2) {  
  20.                 String result1=o1+""+o2;  
  21.                 String result2=o2+""+o1;  
  22.                 return result1.compareTo(result2);  
  23.             }  
  24.         });  
  25.         Iterator<Integer> iterator=list.iterator();  
  26.         while(iterator.hasNext()){  
  27.             result+=(iterator.next()+"");  
  28.         }  
  29.         return result;  
  30.     }  
  31. }  

2.题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

代码:

[java]  view plain  copy
  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. public class Solution {  
  11.     public TreeNode reConstructBinaryTree(int[] pre, int[] in) {  
  12.         return DFS(pre,in,0,pre.length-1,0,in.length-1);  
  13.     }  
  14.   
  15.     private TreeNode DFS(int []pre,int []in,int prestart,int preend,int instart,int endstart){  
  16.         if(prestart>preend||instart>endstart){  
  17.             return null;  
  18.         }  
  19.         TreeNode root=new TreeNode(pre[prestart]);  
  20.         for(int indexstart=instart;indexstart<=endstart;indexstart++){  
  21.             if(pre[prestart]==in[indexstart]){  
  22.                 root.left=DFS(pre, in, prestart+1, prestart+indexstart-instart, instart, indexstart-1);  
  23.                 root.right=DFS(pre, in, indexstart-instart+prestart+1, preend, indexstart+1, endstart);  
  24.             }  
  25.         }  
  26.         return root;  
  27.     }  
  28. }  


3.题目:给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。

代码:

[java]  view plain  copy
  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.   
  15. import java.util.ArrayList;  
  16. import java.util.Arrays;  
  17. import java.util.Collections;  
  18. import java.util.Comparator;  
  19. import java.util.Iterator;  
  20. public class Solution {  
  21.     //思路:二叉搜索树的中序遍历就是按顺序排列的,所以,直接中序查找就可以了  
  22.    int index=0;  
  23.      TreeNode KthNode(TreeNode pRoot, int k) {  
  24.         if(pRoot!=null){  
  25.             TreeNode left=KthNode(pRoot.left, k);  
  26.             if(left!=null)  
  27.                 return left;  
  28.             index++;  
  29.             if(index==k)  
  30.                 return pRoot;  
  31.             TreeNode right=KthNode(pRoot.right, k);  
  32.             if(right!=null)  
  33.                 return right;  
  34.         }  
  35.         return null;  
  36.      }  
  37. }  


题目描述

HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢?例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。你会不会被他忽悠住?(子向量的长度至少是1)
代码:
[java]  view plain  copy
  1. public class Solution {  
  2.     public int FindGreatestSumOfSubArray(int[] array) {  
  3.         if(array.length==0){  
  4.             return 0;  
  5.         }  
  6.         int sum=array[0];  
  7.         int Maxsum=array[0];  
  8.         for(int i=1;i<array.length;i++){  
  9.             if(sum<0){  
  10.                 sum=0;  
  11.             }  
  12.             sum+=array[i];  
  13.             Maxsum=Math.max(Maxsum, sum);  
  14.         }  
  15.         return Maxsum;  
  16.     }  
  17. }  

题目描述

在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是重复的数字2或者3。
代码:
[java]  view plain  copy
  1. import java.util.HashSet;  
  2. import java.util.Iterator;  
  3. import java.util.LinkedHashSet;  
  4. import java.util.Set;  
  5. public class Solution {  
  6.     // Parameters:  
  7.     //    numbers:     an array of integers  
  8.     //    length:      the length of array numbers  
  9.     //    duplication: (Output) the duplicated number in the array number,length of duplication array is 1,so using duplication[0] = ? in implementation;  
  10.     //                  Here duplication like pointor in C/C++, duplication[0] equal *duplication in C/C++  
  11.     //    这里要特别注意~返回任意重复的一个,赋值duplication[0]  
  12.     // Return value:       true if the input is valid, and there are some duplications in the array number  
  13.     //                     otherwise false  
  14.     //  private static final int Max=(int) (1e5+10);  
  15.     private static int []vis;  
  16.     public static boolean duplicate(int numbers[], int length, int[] duplication) {  
  17.         if(length<1){  
  18.             return false;  
  19.         }  
  20.         vis=new int [length];  
  21.         for(int i=0;i<length;i++){  
  22.             vis[numbers[i]]++;  
  23.         }  
  24.         Set<Integer> set=new HashSet<Integer>();  
  25.         for(int i=0;i<length;i++){  
  26.             if(vis[numbers[i]]>1){  
  27.                 set.add(numbers[i]);  
  28.             }  
  29.         }  
  30.         Iterator<Integer> iterator=set.iterator();  
  31.         int cnt=0;  
  32.         while(iterator.hasNext()){  
  33.             duplication[cnt++]=iterator.next();  
  34.             break;  
  35.         }  
  36. //      for(int i=0;i<cnt;i++){  
  37. //          System.out.print(duplication[i]+" ");  
  38. //      }  
  39.         if(cnt!=0){  
  40.             return true;  
  41.         }  
  42.         return false;  
  43.     }  
  44. }  

题目描述

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。
代码:
[java]  view plain  copy
  1. import java.util.HashSet;  
  2. import java.util.Set;  
  3. public class Solution {  
  4.     //思路:判断不合法的情况:1.numbers长度不为5,2.numbers中除0外,有重复的数,3.最大值减最小值>=5  
  5.     //剩下的就是合法的情况了  
  6.    public boolean isContinuous(int[] numbers) {  
  7.         int length=numbers.length;  
  8.         if(length!=5){  
  9.             return false;  
  10.         }  
  11.         Set<Integer> hashSet=new HashSet<Integer>();  
  12.         int ans=0;//0的个数  
  13.         int Max=-1,Min=100;  
  14.         for(int i=0;i<length;i++){  
  15.             if(numbers[i]!=0){  
  16.                 hashSet.add(numbers[i]);  
  17.                 Max=Math.max(Max, numbers[i]);  
  18.                 Min=Math.min(Min, numbers[i]);  
  19.             }else{  
  20.                 ans++;  
  21.             }  
  22.         }  
  23.         if(ans+hashSet.size()!=length){  
  24.             return false;  
  25.         }  
  26.         if(Max-Min>=5){  
  27.             return false;  
  28.         }  
  29.         return true;  
  30.     }  
  31. }  

题目描述

汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
代码:
[java]  view plain  copy
  1. public class Solution {  
  2.  public  String LeftRotateString(String str, int n) {  
  3.         if(str.length()==0){  
  4.             return str;  
  5.         }  
  6.         n%=(str.length());  
  7.         if(str.length()<1)  
  8.             return null;  
  9.         for(int i=0;i<n;i++)  
  10.             str=GetString(str);  
  11.         return str;  
  12.     }  
  13.     private  String GetString(String str){  
  14.         return str.substring(1, str.length())+str.charAt(0);  
  15.     }  
  16. }  

题目描述

牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
代码:
[java]  view plain  copy
  1. public class Solution {  
  2.  public static String ReverseSentence(String str) {  
  3.         String string=str.trim();  
  4.         String a="";  
  5.         if(string.equals(a)){  
  6.             return str;  
  7.         }  
  8.         StringBuilder result=new StringBuilder();  
  9.         String []split=str.split(" ");  
  10.         for(int i=split.length-1;i>=0;i--){  
  11.             result.append((split[i]+" "));  
  12.         }  
  13.         return result.toString().trim();  
  14.     }  
  15. }  

题目描述

给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{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]}。
代码:
[java]  view plain  copy
  1. import java.util.ArrayList;  
  2. public class Solution {  
  3.    public static ArrayList<Integer> maxInWindows(int [] num, int size)  
  4.     {  
  5.         ArrayList<Integer> list=new ArrayList<Integer>();  
  6.         int length=num.length;  
  7.         if(size<=0){  
  8.             return list;  
  9.         }  
  10.         if(length>=1){  
  11.             int Max=Integer.MIN_VALUE;  
  12.             for(int i=0;i<length;i++){  
  13.                 Max=Math.max(Max, num[i]);  
  14.             }  
  15.             if(size>length){  
  16.                 return list;  
  17.             }else{  
  18.                 for(int i=0;i<length-size+1;i++){  
  19.                     int MAX=Integer.MIN_VALUE;  
  20.                     for(int j=i;j<size+i;j++){  
  21.                         MAX=Math.max(MAX, num[j]);  
  22.                     }  
  23.                     list.add(MAX);  
  24.                 }  
  25.             }  
  26.         }  
  27.         return list;  
  28.     }  
  29. }  

题目描述

每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为牛客的资深元老,自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m,让编号为0的小朋友开始报数。每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续0...m-1报数....这样下去....直到剩下最后一个小朋友,可以不用表演,并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!^_^)。请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从0到n-1)
代码:
[java]  view plain  copy
  1. public class Solution {  
  2.     private final static int Max=(int) (1e5+10);  
  3.     public int LastRemaining_Solution(int n, int m) {  
  4.         int []array=new int[Max];  
  5.         int i=-1,count=n,step=0;  
  6.         while(count>0){//模拟环  
  7.             i++;  
  8.             if(i>=n){  
  9.                 i=0;  
  10.             }  
  11.             if(array[i]==-1)  
  12.                 continue;  
  13.             step++;  
  14.             if(step==m){  
  15.                 step=0;  
  16.                 count--;  
  17.                 array[i]=-1;  
  18.             }  
  19.         }  
  20.         return i;  
  21.     }  
  22. }  

题目描述

请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
代码:
[java]  view plain  copy
  1. import java.util.ArrayList;  
  2. import java.util.LinkedList;  
  3. import java.util.Queue;  
  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.     public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {  
  19.         ArrayList<ArrayList<Integer>> list=new ArrayList<ArrayList<Integer>>();  
  20.         if(pRoot==null){  
  21.             return list;  
  22.         }  
  23.         int ans=1;  
  24.         Queue<TreeNode> queue=new LinkedList<TreeNode>();  
  25.         queue.add(pRoot);  
  26.         while(!queue.isEmpty()){  
  27.             ArrayList<Integer> nodes=new ArrayList<Integer>();  
  28.             int size=queue.size();  
  29.             for(int i=0;i<size;i++){  
  30.                 TreeNode root=queue.poll();  
  31.                 if(ans%2==0){  
  32.                     nodes.add(0,root.val);  
  33.                 }else{  
  34.                     nodes.add(root.val);  
  35.                 }  
  36.                 if(root.left!=null){  
  37.                     queue.add(root.left);  
  38.                 }  
  39.                 if(root.right!=null){  
  40.                     queue.add(root.right);  
  41.                 }  
  42.             }  
  43.             list.add(nodes);  
  44.             ans++;  
  45.         }  
  46.         return list;  
  47.     }  
  48.   
  49. }  

题目描述

从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
代码:
[java]  view plain  copy
  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.ArrayList;  
  15. import java.util.LinkedList;  
  16. import java.util.Queue;  
  17. public class Solution {  
  18.     ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {  
  19.         ArrayList<ArrayList<Integer>> list=new ArrayList<ArrayList<Integer>>();  
  20.         if(pRoot==null){  
  21.             return list;  
  22.         }  
  23.         Queue<TreeNode> queue=new LinkedList<TreeNode>();  
  24.         queue.add(pRoot);  
  25.         while(!queue.isEmpty()){  
  26.             ArrayList<Integer> arrayList=new ArrayList<Integer>();  
  27.             int size=queue.size();  
  28.             for(int i=0;i<size;i++){  
  29.                 TreeNode root=queue.poll();  
  30.                 arrayList.add(root.val);  
  31.                 if(root.left!=null){  
  32.                     queue.add(root.left);  
  33.                 }  
  34.                 if(root.right!=null){  
  35.                     queue.add(root.right);  
  36.                 }  
  37.             }  
  38.             list.add(arrayList);  
  39.         }  
  40.         return list;  
  41.     }  
  42.       
  43. }  

题目描述

如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。
代码:
[java]  view plain  copy
  1. import java.util.ArrayList;  
  2. import java.util.Collections;  
  3. import java.util.Comparator;  
  4. public class Solution {  
  5.   
  6.     private ArrayList<Integer> list=new ArrayList<Integer>();  
  7.     public void Insert(Integer num) {  
  8.         list.add(num);  
  9.         Collections.sort(list,new Comparator<Integer>() {  
  10.   
  11.             @Override  
  12.             public int compare(Integer o1, Integer o2) {  
  13.                 return o1-o2;  
  14.             }  
  15.         });  
  16.     }  
  17.   
  18.     public Double GetMedian() {  
  19.         int length=list.size();  
  20.         int MID=length>>1;  
  21.         double mid=0;  
  22.         if((length&1)==0){  
  23.             Integer a1=list.get(MID);  
  24.             Integer a2=list.get(MID-1);  
  25.             mid=(Double.valueOf(a1+"")+Double.valueOf(a2+""))/2;  
  26.         }else{  
  27.             Integer a3=list.get(MID);  
  28.             mid=Double.valueOf(a3+"");  
  29.         }  
  30.         return mid;  
  31.     }  
  32. }  

题目描述

小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck! 
输出描述:
输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序
代码:
[java]  view plain  copy
  1. import java.util.ArrayList;  
  2. public class Solution {  
  3.     public static ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) {  
  4.         ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();  
  5.         if (sum < 0) {  
  6.             return list;  
  7.         }  
  8.         for (int i = 1; i <= sum; i++) {  
  9.             for (int j = i; j <= sum; j++) {  
  10.                 int n = j - i + 1;  
  11.                 int ans = i*n+(n*(n-1))/2;  
  12.                 if (ans != sum) {  
  13.                     continue;  
  14.                 }  
  15.                 ArrayList<Integer> arrayList = new ArrayList<>();  
  16.                 for (int k = i; k <= j; k++) {  
  17.                     arrayList.add(k);  
  18.                 }  
  19.                 if(arrayList.size()>=2){//至少包括两个数  
  20.                     list.add(arrayList);  
  21.                 }  
  22.             }  
  23.         }  
  24.         return list;  
  25.     }  
  26. }  

题目描述

有一副由NxN矩阵表示的图像,这里每个像素用一个int表示,请编写一个算法,在不占用额外内存空间的情况下(即不使用缓存矩阵),将图像顺时针旋转90度。

给定一个NxN的矩阵,和矩阵的阶数N,请返回旋转后的NxN矩阵,保证N小于等于500,图像元素小于等于256。

测试样例:
[[1,2,3],[4,5,6],[7,8,9]],3
返回:[[7,4,1],[8,5,2],[9,6,3]]
代码:
[java]  view plain  copy
  1. import java.util.*;  
  2.   
  3. public class Transform {  
  4.     public  int[][] transformImage(int[][] mat, int n) {  
  5.         int [][]A=new int[n][n];  
  6.         int x=0,y=n-1;  
  7.         for(int i=0;i<n;i++){  
  8.             for(int j=0;j<n;j++){  
  9.                 A[x][y]=mat[i][j];  
  10.                 if(x==n-1){  
  11.                     y--;  
  12.                     x=0;  
  13.                 }else{  
  14.                     x++;  
  15.                 }  
  16.             }  
  17.         }  
  18.         return A;  
  19.     }  
  20. }  

题目描述

假定我们都知道非常高效的算法来检查一个单词是否为其他字符串的子串。请将这个算法编写成一个函数,给定两个字符串s1和s2,请编写代码检查s2是否为s1旋转而成,要求只能调用一次检查子串的函数。

给定两个字符串s1,s2,请返回bool值代表s2是否由s1旋转而成。字符串中字符为英文字母和空格,区分大小写,字符串长度小于等于1000。

测试样例:
"Hello world","worldhello "
返回:false
"waterbottle","erbottlewat"
返回:true
代码:
[java]  view plain  copy
  1. import java.util.*;  
  2.   
  3. public class ReverseEqual {  
  4.     public boolean checkReverseEqual(String s1, String s2) {  
  5.         if(s1==null||s2==null||s1.length()!=s2.length()){  
  6.             return false;  
  7.         }  
  8.         return (s1+s1).contains(s2);  
  9.     }  
  10. }  

题目描述

输入一个链表,输出该链表中倒数第k个结点。
[java]  view plain  copy
  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.LinkedHashMap;  
  12. public class Solution {  
  13.   
  14.     public ListNode FindKthToTail(ListNode head, int k) {  
  15.         LinkedHashMap<Integer, ListNode> map=new LinkedHashMap<Integer, ListNode>();  
  16.         int cnt=0;  
  17.         while(head!=null){  
  18.             map.put(cnt++, head);  
  19.             head=head.next;  
  20.         }  
  21.         return map.get(cnt-k);  
  22.   
  23.     }  
  24.   
  25. }  

题目描述

实现一个算法,删除单向链表中间的某个结点,假定你只能访问该结点。

给定带删除的节点,请执行删除操作,若该节点为尾节点,返回false,否则返回true

代码:
[java]  view plain  copy
  1. import java.util.*;  
  2.   
  3. /* 
  4. public class ListNode { 
  5.     int val; 
  6.     ListNode next = null; 
  7.  
  8.     ListNode(int val) { 
  9.         this.val = val; 
  10.     } 
  11. }*/  
  12. public class Remove {  
  13.     public boolean removeNode(ListNode pNode) {  
  14.         if(pNode==null){  
  15.             return false;  
  16.         }  
  17.         if(pNode.next==null){  
  18.             return false;  
  19.         }  
  20.         return true;  
  21.     }  
  22. }  

题目描述

编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前

给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。


代码:
[java]  view plain  copy
  1. import java.util.*;  
  2. import java.util.Collections;  
  3. import java.util.Comparator;  
  4. import java.util.LinkedList;  
  5. /* 
  6. public class ListNode { 
  7.     int val; 
  8.     ListNode next = null; 
  9.  
  10.     ListNode(int val) { 
  11.         this.val = val; 
  12.     } 
  13. }*/  
  14. public class Partition {  
  15.  public ListNode partition(ListNode pHead, int x) {  
  16.         if(pHead==null||pHead.next==null){  
  17.             return pHead;  
  18.         }  
  19.           
  20.         ListNode cur=pHead;  
  21.         ListNode Ahead=new ListNode(-1);  
  22.         ListNode Bhead=new ListNode(-1);  
  23.         ListNode Atemp=Ahead;  
  24.         ListNode Btemp=Bhead;  
  25.         while(cur!=null){  
  26.             if(cur.val<x){  
  27.                 Atemp.next=new ListNode(cur.val);  
  28.                 Atemp=Atemp.next;  
  29.             }else{  
  30.                 Btemp.next=new ListNode(cur.val);  
  31.                 Btemp=Btemp.next;  
  32.             }  
  33.             cur=cur.next;  
  34.         }  
  35.         ListNode newhead=Ahead;  
  36.         while(newhead.next!=null&&newhead.next.val!=-1){  
  37.             newhead=newhead.next;  
  38.         }  
  39.         newhead.next=Bhead.next;  
  40.         return Ahead.next;//取Ahead->next而不取Ahead是因为Ahead头的val是-1,不是链表中的值  
  41.     }  
  42. }  

题目描述

有两个用链表表示的整数,每个结点包含一个数位。这些数位是反向存放的,也就是个位排在链表的首部。编写函数对这两个整数求和,并用链表形式返回结果。

给定两个链表ListNode* A,ListNode* B,请返回A+B的结果(ListNode*)。

测试样例:
{1,2,3},{3,2,1}
返回:{4,4,4}
代码:
[java]  view plain  copy
  1. import java.util.*;  
  2. /* 
  3. public class ListNode { 
  4.     int val; 
  5.     ListNode next = null; 
  6.  
  7.     ListNode(int val) { 
  8.         this.val = val; 
  9.     } 
  10. }*/  
  11. public class Plus {  
  12.   public static ListNode plusAB(ListNode a, ListNode b) {  
  13.         if (a == null && b == null) {  
  14.             return null;  
  15.         }  
  16.         ListNode Ahead = a;  
  17.         ListNode Bhead = b;  
  18.         ListNode newhead = new ListNode(-1);  
  19.         ListNode newtemp = newhead;  
  20.         int temp = 0;  
  21.         while (Ahead != null || Bhead != null) {  
  22.             // 三种情况:1:Ahead!=null&&Bhead!=null  
  23.             // 2:Ahead==null&&Bhead!=null  
  24.             // 3:Ahead!=null&&Bhead==null  
  25.             if (Ahead != null && Bhead != null) {  
  26.                 ListNode node = new ListNode((Ahead.val + Bhead.val + temp) % 10);  
  27.                 temp = (Ahead.val + Bhead.val + temp) / 10;  
  28.                 newtemp.next = node;  
  29.                 newtemp = newtemp.next;  
  30.                 Ahead = Ahead.next;  
  31.                 Bhead = Bhead.next;  
  32.             } else if (Ahead == null && Bhead != null) {  
  33.                 ListNode node = new ListNode((Bhead.val + temp) % 10);  
  34.                 temp = (Bhead.val + temp) / 10;  
  35.                 newtemp.next = node;  
  36.                 newtemp = newtemp.next;  
  37.                 Bhead = Bhead.next;  
  38.             } else if (Ahead != null && Bhead == null) {  
  39.                 ListNode node = new ListNode((Ahead.val + temp) % 10);  
  40.                 temp = (Ahead.val + temp) / 10;  
  41.                 newtemp.next = node;  
  42.                 newtemp = newtemp.next;  
  43.                 Ahead = Ahead.next;  
  44.             }  
  45.         }  
  46.         if (temp != 0) {  
  47.             ListNode node = new ListNode(temp);  
  48.             newtemp.next = node;  
  49.             newtemp = newtemp.next;  
  50.         }  
  51.         return newhead.next;  
  52.     }  
  53.   
  54. }  

题目描述

输入一个链表,反转链表后,输出链表的所有元素。
代码:
[java]  view plain  copy
  1. /* 
  2. public class ListNode { 
  3.     int val; 
  4.     ListNode next = null; 
  5.  
  6.     ListNode(int val) { 
  7.         this.val = val; 
  8.     } 
  9. }*/  
  10. import java.util.LinkedHashMap;  
  11. public class Solution {  
  12.     public ListNode ReverseList(ListNode head) {  
  13.            if(head==null){  
  14.                return null;  
  15.            }  
  16.            ListNode newhead=null;  
  17.            ListNode phead=head;  
  18.            ListNode prehead=null;  
  19.            while(phead!=null){  
  20.                ListNode pnext=phead.next;  
  21.                if(pnext==null){  
  22.                    newhead=phead;  
  23.                }  
  24.                phead.next=prehead;  
  25.                prehead=phead;  
  26.                phead=pnext;  
  27.            }  
  28.            return newhead;  
  29.     }  
  30. }  

题目描述

请编写一个函数,检查链表是否为回文。

给定一个链表ListNode* pHead,请返回一个bool,代表链表是否为回文。

测试样例:
{1,2,3,2,1}
返回:true
{1,2,3,2,3}
返回:false
代码:
[java]  view plain  copy
  1. import java.util.*;  
  2.   
  3. /* 
  4. public class ListNode { 
  5.     int val; 
  6.     ListNode next = null; 
  7.  
  8.     ListNode(int val) { 
  9.         this.val = val; 
  10.     } 
  11. }*/  
  12. public class Palindrome {  
  13.    public boolean isPalindrome(ListNode pHead) {  
  14.         if (pHead == null) {  
  15.             return false;  
  16.         }  
  17.         LinkedList<Integer> linkedList = new LinkedList<Integer>();  
  18.         while (pHead != null) {  
  19.             linkedList.add(pHead.val);  
  20.             pHead = pHead.next;  
  21.         }  
  22.         return Check(linkedList);  
  23.     }  
  24.   
  25.     // 检查是否为回文串  
  26.     private boolean Check(LinkedList<Integer> linkedList) {  
  27.         boolean result = true;  
  28.         int len = linkedList.size();  
  29.         int length =len>>1;  
  30.         for (int i = 0; i < length; i++) {  
  31.             if (linkedList.get(i) != linkedList.get(len - i - 1)) {  
  32.                 result = false;  
  33.                 break;  
  34.             }  
  35.         }  
  36.         return result;  
  37.     }  
  38. }  

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
代码:
[java]  view plain  copy
  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(node);  
  9.     }  
  10.       
  11.     public int pop() {  
  12.         while(!stack1.isEmpty()){  
  13.             stack2.push(stack1.pop());  
  14.         }  
  15.         int node=stack2.pop();  
  16.         while(!stack2.isEmpty()){  
  17.             stack1.push(stack2.pop());  
  18.         }  
  19.         return node;  
  20.     }  
  21. }  

题目描述

有一些数的素因子只有3、5、7,请设计一个算法,找出其中的第k个数。

给定一个数int k,请返回第k个数。保证k小于等于100。

测试样例:
3
返回:7
代码:
[java]  view plain  copy
  1. import java.util.*;  
  2.   
  3. public class KthNumber {  
  4.    private static final int Max = (int) (1e5 + 10);  
  5.     private static int cnt;  
  6.     private static int []A;  
  7.     public static int findKth(int k) {  
  8.         InitData();  
  9.         return A[k];  
  10.     }  
  11.   
  12.     private static void InitData() {  
  13.         cnt=1;  
  14.         int a=0,b=0,c=0;  
  15.         A=new int[Max];  
  16.         A[0]=1;  
  17.         while(cnt<=100){  
  18.             int temp=Math.min(A[a]*3, Math.min(A[b]*5, A[c]*7));  
  19.             if(temp==A[a]*3)  
  20.                 a++;  
  21.             if(temp==A[b]*5)  
  22.                 b++;  
  23.             if(temp==A[c]*7)  
  24.                 c++;  
  25.             A[cnt++]=temp;  
  26.         }  
  27.     }  
  28. }  


题目描述

现在我们有一个int数组,请你找出数组中每个元素的下一个比它大的元素。

给定一个int数组A及数组的大小n,请返回一个int数组,代表每个元素比他大的下一个元素,若不存在则为-1。保证数组中元素均为正整数。

测试样例:
[11,13,10,5,12,21,3],7
返回:[13,21,12,12,21,-1,-1]
代码:
[java]  view plain  copy
  1. import java.util.*;  
  2.   
  3. public class NextElement {  
  4.     public static int[] findNext(int[] A, int n) {  
  5.         int []B=new int[n];  
  6.         for(int i=0;i<n;i++){  
  7.             int temp=-1;  
  8.             for(int j=i+1;j<n;j++){  
  9.                 if(A[i]<A[j]){  
  10.                     temp=A[j];  
  11.                     break;  
  12.                 }  
  13.             }  
  14.             B[i]=temp;  
  15.         }  
  16.         return B;  
  17.     }  
  18. }  

题目描述

现在有一个数组,请找出数组中每个元素的后面比它大的最小的元素,若不存在则为-1。

给定一个int数组A及数组的大小n,请返回每个元素所求的值组成的数组。保证A中元素为正整数,且n小于等于1000。

测试样例:
[11,13,10,5,12,21,3],7
[12,21,12,12,21,-1,-1]
代码:
[java]  view plain  copy
  1. import java.util.*;  
  2.   
  3. public class NextElement {  
  4.     public static int[] findNext(int[] A, int n) {  
  5.         int []B=new int[n];  
  6.         for(int i=0;i<n;i++){  
  7.             int temp=Integer.MAX_VALUE;  
  8.             boolean ok=false;  
  9.             for(int j=i+1;j<n;j++){  
  10.                 if(A[i]<A[j]){  
  11.                     ok=true;  
  12.                     temp=Math.min(temp, A[j]);  
  13.                 }  
  14.             }  
  15.             if(ok){  
  16.                 B[i]=temp;  
  17.             }else{  
  18.                 B[i]=-1;  
  19.             }  
  20.         }  
  21.         return B;  
  22.     }  
  23. }  

题目描述

请编写一个程序,按升序对栈进行排序(即最大元素位于栈顶),要求最多只能使用一个额外的栈存放临时数据,但不得将元素复制到别的数据结构中。

给定一个int[] numbers(C++中为vector&ltint>),其中第一个元素为栈顶,请返回排序后的栈。请注意这是一个栈,意味着排序过程中你只能访问到第一个元素。

测试样例:
[1,2,3,4,5]
返回:[5,4,3,2,1]
代码:
[java]  view plain  copy
  1. import java.util.*;  
  2.   
  3. public class TwoStacks {  
  4.     public  ArrayList<Integer> twoStacksSort(int[] numbers) {  
  5.         ArrayList<Integer> list=new ArrayList<>();  
  6.         if(numbers.length==0){  
  7.             return list;  
  8.         }  
  9.         Stack<Integer> stack1=new Stack<Integer>();  
  10.         Stack<Integer> stack2=new Stack<Integer>();  
  11.         for(int i=0;i<numbers.length;i++){  
  12.             stack1.push(numbers[i]);  
  13.         }  
  14.         while(!stack1.isEmpty()){  
  15.             int temp=stack1.pop();  
  16.             while(!stack2.isEmpty()&&stack2.peek()>temp){  
  17.                 stack1.push(stack2.pop());  
  18.             }  
  19.             stack2.push(temp);  
  20.         }  
  21.         int len=stack2.size();  
  22.         for(int i=0;i<len;i++){  
  23.             list.add(stack2.pop());  
  24.         }  
  25.         return list;  
  26.     }  
  27. }  

题目描述

实现一个函数,检查二叉树是否平衡,平衡的定义如下,对于树中的任意一个结点,其两颗子树的高度差不超过1。

给定指向树根结点的指针TreeNode* root,请返回一个bool,代表这棵树是否平衡。

代码:
[java]  view plain  copy
  1. import java.util.*;  
  2.   
  3. /* 
  4. public class TreeNode { 
  5.     int val = 0; 
  6.     TreeNode left = null; 
  7.     TreeNode right = null; 
  8.     public TreeNode(int val) { 
  9.         this.val = val; 
  10.     } 
  11. }*/  
  12. public class Balance {  
  13.    public boolean isBalance(TreeNode root) {  
  14.         if (root == null)  
  15.             return true;  
  16.         TreeNode left=root.left;  
  17.         TreeNode right=root.right;  
  18.         int val=Math.abs(GetHigh(left)-GetHigh(right));//判断左数和右树的高度差  
  19.         if(val>1)//如果大于1,不符合  
  20.             return false;  
  21.         //如果不大于1,继续判断左树的子树和右树的子树  
  22.         return isBalance(left)&&isBalance(right);  
  23.     }  
  24.     //获取一棵树的高度  
  25.     private int GetHigh(TreeNode root){  
  26.         if(root==null)  
  27.             return 0;  
  28.         int lefthigh=GetHigh(root.left);  
  29.         int righthigh=GetHigh(root.right);  
  30.         return lefthigh>righthigh?(lefthigh+1):(righthigh+1);  
  31.     }  
  32. }  

题目描述

对于一个有向图,请实现一个算法,找出两点之间是否存在一条路径。

给定图中的两个结点的指针UndirectedGraphNode* a,UndirectedGraphNode*b(请不要在意数据类型,图是有向图),请返回一个bool,代表两点之间是否存在一条路径(a到b或b到a)。

代码:
[java]  view plain  copy
  1. import java.util.*;  
  2. import java.util.ArrayList;  
  3. /* 
  4. public class UndirectedGraphNode { 
  5.     int label = 0; 
  6.     UndirectedGraphNode left = null; 
  7.     UndirectedGraphNode right = null; 
  8.     ArrayList<UndirectedGraphNode> neighbors = new ArrayList<UndirectedGraphNode>(); 
  9.  
  10.     public UndirectedGraphNode(int label) { 
  11.         this.label = label; 
  12.     } 
  13. }*/  
  14. public class Path {  
  15.     public boolean checkPath(UndirectedGraphNode a, UndirectedGraphNode b) {  
  16.         if(a==b){  
  17.             return true;  
  18.         }  
  19.         HashMap<UndirectedGraphNode, Boolean> map=new HashMap<UndirectedGraphNode, Boolean>();  
  20.         boolean ok=Check(a,b,map);//从a开始找,b不动  
  21.         map.clear();  
  22.         return ok||Check(b,a,map);//从b开始找,a不动  
  23.     }  
  24.     private boolean Check(UndirectedGraphNode a, UndirectedGraphNode b,HashMap<UndirectedGraphNode, Boolean> map){  
  25.         if(a==b){  
  26.             return true;  
  27.         }  
  28.         map.put(a, true);  
  29.         for(int i=0;i<a.neighbors.size();i++){//从a的邻居找,看看有没有等于b的  
  30.             if(!map.containsKey(a.neighbors.get(i))&&Check(a.neighbors.get(i), b, map)){  
  31.                 return true;  
  32.             }  
  33.         }  
  34.         return false;  
  35.     }  
  36.   
  37. }  

题目描述

对于一个元素各不相同且按升序排列的有序序列,请编写一个算法,创建一棵高度最小的二叉查找树。

给定一个有序序列int[] vals,请返回创建的二叉查找树的高度。

代码:
[java]  view plain  copy
  1. import java.util.*;  
  2.   
  3. public class MinimalBST {  
  4.     public int buildMinimalBST(int[] vals) {  
  5.         int length=vals.length;  
  6.         if(length==0){  
  7.             return 0;  
  8.         }  
  9.         int sum=1;  
  10.         for(int i=1;i<=10000;i++){  
  11.             sum<<=1;  
  12.             if(sum-1>=length){  
  13.                 return i;  
  14.             }  
  15.         }  
  16.         return 0;  
  17.     }  
  18. }  

题目描述

对于一棵二叉树,请设计一个算法,创建含有某一深度上所有结点的链表。

给定二叉树的根结点指针TreeNode* root,以及链表上结点的深度,请返回一个链表ListNode,代表该深度上所有结点的值,请按树上从左往右的顺序链接,保证深度不超过树的高度,树上结点的值为非负整数且不超过100000。

代码:
[java]  view plain  copy
  1. import java.util.*;  
  2.   
  3. /* 
  4. public class ListNode { 
  5.     int val; 
  6.     ListNode next = null; 
  7.  
  8.     ListNode(int val) { 
  9.         this.val = val; 
  10.     } 
  11. }*/  
  12. /* 
  13. public class TreeNode { 
  14.     int val = 0; 
  15.     TreeNode left = null; 
  16.     TreeNode right = null; 
  17.     public TreeNode(int val) { 
  18.         this.val = val; 
  19.     } 
  20. }*/  
  21. public class TreeLevel {  
  22.    public ListNode getTreeLevel(TreeNode root, int dep) {  
  23.         ListNode listNode=new ListNode(-1);  
  24.         ListNode head=listNode;  
  25.         if(root==null||dep==0){  
  26.             return null;  
  27.         }  
  28.         Queue<TreeNode> queue=new LinkedList<TreeNode>();  
  29.         queue.add(root);  
  30.         int ans=1;  
  31.         while(!queue.isEmpty()){  
  32.             int size=queue.size();  
  33.             if(ans==dep){  
  34.                 for(int i=0;i<size;i++){  
  35.                     TreeNode node=queue.poll();  
  36.                     ListNode newhead=new ListNode(node.val);  
  37.                     head.next=newhead;  
  38.                     head=head.next;  
  39.                 }  
  40.                 break;  
  41.             }else{  
  42.                 for(int i=0;i<size;i++){  
  43.                     TreeNode node=queue.poll();  
  44.                     TreeNode left=node.left;  
  45.                     TreeNode right=node.right;  
  46.                     if(left!=null){  
  47.                         queue.add(left);  
  48.                     }  
  49.                     if(right!=null){  
  50.                         queue.add(right);  
  51.                     }  
  52.                 }  
  53.             }  
  54.             ans++;  
  55.         }  
  56.           
  57.         return listNode.next;  
  58.           
  59.     }  
  60. }  

题目描述

请实现一个函数,检查一棵二叉树是否为二叉查找树。

给定树的根结点指针TreeNode* root,请返回一个bool,代表该树是否为二叉查找树。

代码:
[java]  view plain  copy
  1. import java.util.*;  
  2.   
  3. /* 
  4. public class TreeNode { 
  5.     int val = 0; 
  6.     TreeNode left = null; 
  7.     TreeNode right = null; 
  8.     public TreeNode(int val) { 
  9.         this.val = val; 
  10.     } 
  11. }*/  
  12. public class Checker {  
  13.  /*** 
  14.      * 二叉排序树(BinarySortTree),又称二叉查找树、二叉搜索树。 
  15.      * 它或者是一棵空树;或者是具有下列性质的二叉树: 
  16.      * 若左子树不空,则左子树上所有结点的值均小于它的根结点的值; 
  17.      * 若右子树不空,则右子树上所有结点的值均大于它的根结点的值; 
  18.      * 左、右子树也分别为二叉排序树。若子树为空,查找不成功。 
  19.      * @param root 
  20.      * @return 
  21.      */  
  22.   
  23.     public boolean checkBST(TreeNode root) {  
  24.         if (root == null) {  
  25.             return true;  
  26.         }  
  27.         return Check(root,Integer.MIN_VALUE,Integer.MAX_VALUE);  
  28.     }  
  29.   
  30.     private boolean Check(TreeNode root,int min,int max) {  
  31.         if (root == null) {  
  32.             return true;  
  33.         }  
  34.         int rootval = root.val;  
  35.         TreeNode left = root.left;  
  36.         TreeNode right = root.right;  
  37.         if(rootval<min||rootval>max)  
  38.             return false;  
  39.         return Check(left, min, rootval)&&Check(right, rootval, max);  
  40.     }  
  41. }  

题目描述

请设计一个算法,寻找二叉树中指定结点的下一个结点(即中序遍历的后继)。

给定树的根结点指针TreeNode* root和结点的值intp,请返回值为p的结点的后继结点的值。保证结点的值大于等于零小于等于100000且没有重复值,若不存在后继返回-1。

代码:
[java]  view plain  copy
  1. import java.util.*;  
  2.   
  3. /* 
  4. public class TreeNode { 
  5.     int val = 0; 
  6.     TreeNode left = null; 
  7.     TreeNode right = null; 
  8.     public TreeNode(int val) { 
  9.         this.val = val; 
  10.     } 
  11. }*/  
  12. public class Successor {  
  13.     private static LinkedList<TreeNode> list;  
  14.     public int findSucc(TreeNode root, int p) {  
  15.         int result=-1;  
  16.         list=new LinkedList<TreeNode>();  
  17.         if(root==null){  
  18.             return result;  
  19.         }  
  20.         DFS(root);  
  21.         for(int i=0;i<list.size()-1;i++){  
  22.             int val=list.get(i).val;  
  23.             if(val==p){  
  24.                 if(list.get(i+1)!=null){  
  25.                     result=list.get(i+1).val;  
  26.                 }  
  27.                 break;  
  28.             }  
  29.         }  
  30.         return result;  
  31.     }  
  32.     //先中序遍历存下每个节点的信息  
  33.     private void DFS(TreeNode root){  
  34.         if(root==null){  
  35.             return;  
  36.         }  
  37.         DFS(root.left);  
  38.         list.add(root);  
  39.         DFS(root.right);  
  40.     }  
  41. }  

题目描述

请设计一个算法,计算n的阶乘有多少个尾随零。

给定一个int n,请返回n的阶乘的尾零个数。保证n为正整数。

测试样例:
5
返回:1
代码:
[java]  view plain  copy
  1. import java.util.*;  
  2.   
  3. public class Factor {  
  4.     public int getFactorSuffixZero(int n) {  
  5.         int ans2 = 0, ans5 = 0, ans = 0;  
  6.         for (int i = 1; i <= n; i++) {  
  7.   
  8.             if (i % 10 == 0) {  
  9.                 int temp = i;  
  10.                 while (temp > 0) {  
  11.                     if (temp % 10 == 0) {  
  12.                         ans++;  
  13.                         temp /= 10;  
  14.                     }else if(temp%5==0){  
  15.                         ans5++;  
  16.                         temp/=5;  
  17.                     }else if(temp%2==0){  
  18.                         ans2++;  
  19.                         temp/=2;  
  20.                     }else{  
  21.                         break;  
  22.                     }  
  23.                 }  
  24.             } else if (i % 2 == 0) {  
  25.                 int temp = i;  
  26.                 while (temp > 0) {  
  27.                     if (temp % 10 == 0) {  
  28.                         ans++;  
  29.                         temp /= 10;  
  30.                     }else if(temp%5==0){  
  31.                         ans5++;  
  32.                         temp/=5;  
  33.                     }else if(temp%2==0){  
  34.                         ans2++;  
  35.                         temp/=2;  
  36.                     }else{  
  37.                         break;  
  38.                     }  
  39.                 }  
  40.             } else if (i % 5 == 0) {  
  41.                 int temp = i;  
  42.                 while (temp > 0) {  
  43.                     if (temp % 10 == 0) {  
  44.                         ans++;  
  45.                         temp /= 10;  
  46.                     }else if(temp%5==0){  
  47.                         ans5++;  
  48.                         temp/=5;  
  49.                     }else if(temp%2==0){  
  50.                         ans2++;  
  51.                         temp/=2;  
  52.                     }else{  
  53.                         break;  
  54.                     }  
  55.                 }  
  56.             }  
  57.         }  
  58.         return ans + Math.min(ans2, ans5);  
  59.     }  
  60. }  

题目描述

有一棵无穷大的满二叉树,其结点按根结点一层一层地从左往右依次编号,根结点编号为1。现在有两个结点a,b。请设计一个算法,求出a和b点的最近公共祖先的编号。

给定两个int a,b。为给定结点的编号。请返回ab的最近公共祖先的编号。注意这里结点本身也可认为是其祖先。

测试样例:
2,3
返回:1
代码:
[java]  view plain  copy
  1. import java.util.*;  
  2.   
  3. public class LCA {  
  4.     private static final int Max=(int) (1e6+10);  
  5.     private static int dp1[];  
  6.     private static int dp2[];  
  7.     public static int getLCA(int a, int b) {  
  8.         dp1=new int[Max];  
  9.         dp2=new int[Max];  
  10.         int cnt1=0,cnt2=0;  
  11.         while(a>0){//储存父节点的信息  
  12.             dp1[cnt1++]=a;  
  13.             a>>=1;  
  14.         }  
  15.         while(b>0){//储存父节点的信息  
  16.             dp2[cnt2++]=b;  
  17.             b>>=1;  
  18.         }  
  19.         for(int i=0;i<cnt1;i++){  
  20.             for(int j=0;j<cnt2;j++){  
  21.                 if(dp1[i]==dp2[j]){  
  22.                     return dp1[i];  
  23.                 }  
  24.             }  
  25.         }  
  26.         return 1;  
  27.     }  
  28. }  

题目描述

输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
代码:
[java]  view plain  copy
  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.   private ArrayList<Integer> arrayList=new ArrayList<Integer>();  
  17.     private  ArrayList<ArrayList<Integer>> list=new ArrayList<ArrayList<Integer>>();  
  18.     public  ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {  
  19.         if(root==null){  
  20.             return list;  
  21.         }  
  22.         arrayList.add(root.val);  
  23.         target-=root.val;  
  24.         if(target==0&&root.left==null&&root.right==null){  
  25.             list.add(new ArrayList<Integer>(arrayList));  
  26.         }  
  27.         FindPath(root.left,target);  
  28.         FindPath(root.right,target);  
  29.         if(arrayList!=null){  
  30.             int size=arrayList.size();  
  31.             if(size>1){  
  32.                 arrayList.remove(size-1);  
  33.             }  
  34.         }  
  35.         return list;  
  36.     }  
  37.       
  38.       
  39.       
  40. }  

题目描述

有两个32位整数n和m,请编写算法将m的二进制数位插入到n的二进制的第j到第i位,其中二进制的位数从低位数到高位且以0开始。

给定两个数int n和int m,同时给定int j和int i,意义如题所述,请返回操作后的数,保证n的第j到第i位均为零,且m的二进制位数小于等于i-j+1。

测试样例:
1024,19,2,6
返回:1100
代码:
[java]  view plain  copy
  1. import java.util.*;  
  2.   
  3. public class BinInsert {  
  4.     public static int binInsert(int n, int m, int j, int i) {  
  5.         int sum=n;  
  6.         int cnt=j;  
  7.         while(m>0){  
  8.             if((m&1)==1){  
  9.                 sum+=POW(2, cnt);  
  10.             }  
  11.             cnt++;  
  12.             m>>=1;  
  13.         }  
  14.         return sum;  
  15.     }  
  16.       
  17.     private static  int POW(int a,int b){  
  18.         int sum=1;  
  19.         while(b>0){  
  20.             if((b&1)==1){  
  21.                 sum*=a;  
  22.             }  
  23.             b>>=1;  
  24.             a*=a;  
  25.         }  
  26.         return sum;  
  27.     }  
  28. }  

题目描述

有一个介于0和1之间的实数,类型为double,返回它的二进制表示。如果该数字无法精确地用32位以内的二进制表示,返回“Error”。

给定一个double num,表示0到1的实数,请返回一个string,代表该数的二进制表示或者“Error”。

测试样例:
0.625
返回:0.101
代码:
[java]  view plain  copy
  1. import java.util.*;  
  2.   
  3. public class BinDecimal {  
  4.     public String printBin(double num) {  
  5.         if(num>1||num<0){  
  6.             return "Error";  
  7.         }  
  8.         StringBuilder builder=new StringBuilder();  
  9.         builder.append("0.");  
  10.         while(num>0){  
  11.             if(builder.length()>32){  
  12.                 return "Error";  
  13.             }  
  14.             double r=num*2.0;  
  15.             if(r>=1.0){  
  16.                 builder.append(1);  
  17.                 num=r-1.0;  
  18.             }else{  
  19.                 builder.append(0);  
  20.                 num=r;  
  21.             }  
  22.         }  
  23.         return builder.toString();  
  24.           
  25.     }  
  26. }  

题目描述

有一个正整数,请找出其二进制表示中1的个数相同、且大小最接近的那两个数。(一个略大,一个略小)

给定正整数int x,请返回一个vector,代表所求的两个数(小的在前)。保证答案存在。

测试样例:
2
返回:[1,4]
代码:
[java]  view plain  copy
  1. import java.util.*;  
  2.   
  3. public class CloseNumber {  
  4.   public  int[] getCloseNumber(int x) {  
  5.         int small = 0,big=0;  
  6.         int ans=Get1Count(x);  
  7.         for(int i=x-1;i>=1;i--){  
  8.             if(Get1Count(i)==ans){  
  9.                 small=i;  
  10.                 break;  
  11.             }  
  12.         }  
  13.         for(int j=x+1;;j++){  
  14.             if(Get1Count(j)==ans){  
  15.                 big=j;  
  16.                 break;  
  17.             }  
  18.         }  
  19.         return new int[]{small,big};  
  20.     }  
  21.     private  int Get1Count(int n){  
  22.         int ans=0;  
  23.         while(n>0){  
  24.             if((n&1)==1)  
  25.                 ans++;  
  26.             n>>=1;  
  27.         }  
  28.         return ans;  
  29.     }  
  30. }  

题目描述

编写一个函数,确定需要改变几个位,才能将整数A转变成整数B。

给定两个整数int A,int B。请返回需要改变的数位个数。

测试样例:
10,5
返回:4
代码:
[java]  view plain  copy
  1. import java.util.*;  
  2.   
  3. public class Transform {  
  4.     public int calcCost(int A, int B) {  
  5.         return Get1Count(A^B);//求A和B中不相同的的个数,全部转换成1,最后算A^B中有多少个1就是了  
  6.     }  
  7.     private int Get1Count(int ans){  
  8.         int sum=0;  
  9.         while(ans>0){  
  10.             if((ans&1)==1)  
  11.                 sum++;  
  12.             ans>>=1;  
  13.         }  
  14.         return sum;  
  15.     }  
  16. }  

题目描述

请编写程序交换一个数的二进制的奇数位和偶数位。(使用越少的指令越好)

给定一个int x,请返回交换后的数int。

测试样例:
10
返回:5

代码:
[java]  view plain  copy
  1. import java.util.*;  
  2.   
  3. public class Exchange {  
  4.     public int exchangeOddEven(int x) {  
  5.         String ans=Integer.toBinaryString(x);  
  6.         if((ans.length()&1)==1){  
  7.             ans="0"+ans;  
  8.         }  
  9.         char []array=ans.toCharArray();  
  10.         for(int i=0;i<array.length;i+=2){  
  11.             char temp=array[i];  
  12.             array[i]=array[i+1];  
  13.             array[i+1]=temp;  
  14.         }  
  15.         return Integer.valueOf(new String(array),2);  
  16.     }  
  17. }  

题目描述

有一个排过序的字符串数组,但是其中有插入了一些空字符串,请设计一个算法,找出给定字符串的位置。算法的查找部分的复杂度应该为log级别。

给定一个string数组str,同时给定数组大小n和需要查找的string x,请返回该串的位置(位置从零开始)。

测试样例:
["a","b","","c","","d"],6,"c"
返回:3
代码:
[java]  view plain  copy
  1. import java.util.*;  
  2.   
  3. public class Finder {  
  4.     public  int findString(String[] str, int n, String x) {  
  5.         ArrayList<Node> list=new ArrayList<Node>();  
  6.         for(int i=0;i<n;i++){  
  7.             Node node=new Node(str[i],i);  
  8.             list.add(node);  
  9.         }  
  10.         Collections.sort(list,new Comparator<Node>() {  
  11.   
  12.             @Override  
  13.             public int compare(Node o1, Node o2) {  
  14.                 return o1.ans.compareTo(o2.ans);  
  15.             }  
  16.         });  
  17.           
  18.         int low=0;  
  19.         int high=list.size()-1;  
  20.         while(low<=high){  
  21.             int mid=(low+high)>>1;  
  22.              String result=list.get(mid).ans;  
  23.             if(result.equals(x)){  
  24.                 return list.get(mid).index;  
  25.             }else if(result.compareTo(x)>0){  
  26.                 high=mid-1;  
  27.             }else{  
  28.                 low=mid+1;  
  29.             }  
  30.         }  
  31.         return -1;  
  32.     }  
  33.      class Node{  
  34.         String ans;  
  35.         int index;  
  36.         public Node(){  
  37.               
  38.         }  
  39.         public Node(String ans,int index){  
  40.             this.ans=ans;  
  41.             this.index=index;  
  42.         }  
  43.     }  
  44. }  


题目描述

有一个NxM的整数矩阵,矩阵的行和列都是从小到大有序的。请设计一个高效的查找算法,查找矩阵中元素x的位置。

给定一个int有序矩阵mat,同时给定矩阵的大小nm以及需要查找的元素x,请返回一个二元数组,代表该元素的行号和列号(均从零开始)。保证元素互异。

测试样例:
[[1,2,3],[4,5,6]],2,3,6
返回:[1,2]
代码:
[java]  view plain  copy
  1. import java.util.*;  
  2.   
  3. public class Finder {  
  4.     public  int[] findElement(int[][] mat, int n, int m, int x) {  
  5.         int []rws=new int[2];  
  6.         int row=0,col=mat[0].length-1;  
  7.         while(row<mat.length&&col>=0){  
  8.             if(mat[row][col]==x){  
  9.                 rws[0]=row;  
  10.                 rws[1]=col;  
  11.                 break;  
  12.             }else if(mat[row][col]<x){  
  13.                 row++;  
  14.             }else{  
  15.                 col--;  
  16.             }  
  17.         }  
  18.         return rws;  
  19.     }  
  20.       
  21. }  



1.栈和队列的共同特点是(只允许在端点处插入和删除元素) 4.栈通常采用的两种存储结构是(线性存储结构和链表存储结构) 5.下列关于栈的叙述正确的是(D) A.栈是非线性结构B.栈是一种树状结构C.栈具有先进先出的特征D.栈有后进先出的特征 6.链表不具有的特点是(B)A.不必事先估计存储空间 B.可随机访问任一元素 C.插入删除不需要移动元素 D.所需空间与线性表长度成正比 7.用链表表示线性表的优点是(便于插入和删除操作) 8.在单链表中,增加头结点的的是(方便运算的实现) 9.循环链表的主要优点是(从表中任一结点出发都能访问到整个链表) 10.线性表L=(a1,a2,a3,……ai,……an),下列说法正确的是(D) A.每个元素都有一个直接前件和直接后件 B.线性表中至少要有一个元素 C.表中诸元素的排列顺序必须是由小到大或由大到小 D.除第一个和最后一个元素外,其余每个元素都有一个且只有一个直接前件和直接后件 11.线性表若采用链式存储结构时,要求内存中可用存储单元的地址(D) A.必须是连续的 B.部分地址必须是连续的C.一定是不连续的 D.连续不连续都可以 12.线性表的顺序存储结构和线性表的链式存储结构分别是(随机存取的存储结构、顺序存取的存储结构) 13.树是结点的集合,它的根结点数是(有且只有1) 14.在深度为5的满二叉树中,叶子结点的个数为(31) 15.具有3个结点的二叉树有(5种形态) 16.设一棵二叉树中有3个叶子结点,有8个度为1的结点,则该二叉树中总的结点数为(13) 17.已知二叉树后序遍历序列是dabec,中序遍历序列是debac,它的前序遍历序列是(cedba) 18.已知一棵二叉树前序遍历和中序遍历分别为ABDEGCFH和DBGEACHF,则该二叉树的后序遍历为(DGEBHFCA) 19.若某二叉树的前序遍历访问顺序是abdgcefh,中序遍历访问顺序是dgbaechf,则其后序遍历的结点访问顺序是(gdbehfca) 20.数据库保护分为:安全性控制、 完整性控制 、并发性控制和数据的恢复。 1. 在计算机中,算法是指(解题方案的准确而完整的描述) 2.在下列选项中,哪个不是一个算法一般应该具有的基本特征(无穷性) 说明:算法的四个基本特征是:可行性、确定性、有穷性和拥有足够的情报。 3. 算法一般都可以用哪几种控制结构组合而成(顺序、选择、循环) 4.算法的时间复杂度是指(算法执行过程中所需要的基本运算次数) 5. 算法的空间复杂度是指(执行过程中所需要的存储空间) 6. 算法分析的的是(分析算法的效率以求改进) ............ .................
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值