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

虾皮新手入门考试?shopee新手入门任务 注意:本期shopee新手入门干货,shopee新手入门任务。 任务1:首站店铺需完成50个商品上架 任务2:需要学习并完整观看Shopee新手课程视频 任务3:参加线上考试,成绩大于等于80分合格,只有三次机会。 任务4:新卖家必须填写基本信息对接问卷 ,否则将影响后续分配运营经理! 虾皮新手入门考试 首先是要有一个自己的店铺,开通了站点,按照指引填写好基本资料(注意资料的唯一性)。申请店铺的流程是:提交资料——初审——复审——下店。 一般在申请店铺之后就开始考试了。并且... 阅读详情

原文:https://blog.youkuaiyun.com/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。为给定结点的编号。请返回a和b的最近公共祖先的编号。注意这里结点本身也可认为是其祖先。

测试样例:
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,同时给定矩阵的大小n和m以及需要查找的元素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. }  



【Unity3D】 新手引导 对于我这个小小人来说,ugui做新手引导,是真累啊! 首先,没做过新手引导,没有思路。 其次,ugui的自适应,用着是真不得劲。 方法1. ugui自带的 方法2: 阅读详情

相关推荐

Java常见数据结构面试题(带答案)

主要介绍了Java常见数据结构面试题,带有答案及解释,希望对广大的程序爱好者有所帮助,同时祝大家有一个好成绩,需要的朋友可以参考下。

java 数据结构常见面试题

因为 Set 的底层结构是 Map ,所以三者的特点和使用场景可以参考HashMap 和 TreeMap 和 LinkedHashMap ,需要注意的是,Set 中元素是不允许重复的(Set 的值是底层时存储在 Map 的 Key 中的,key 是不能重复的)。其中 Collection 是所有集合继承的最顶层接口,其中声明的方法有对集合的操作的 增删改查等,所有具体的集合类都继承这个接口。强调:使用map接口的实现类时,切记不要修改key的属性值,否则就会找不到key 所对应的 value值。

Misszhoudandan的博客 3560

Field-Oriented Control (FOC) 矢量控制 磁场定向控制

Field-Oriented Control (FOC) 磁场定向控制(FOC),也称为矢量控制,是一种用于控制永磁同步电动机(PMSM)和交流感应电动机(ACIM)的技术。 FOC在整个扭矩和速度范围内都具有良好的控制能力。 FOC的实现需要将定子电流从固定参考系转换为转子磁通参考系(也称为d-q参考系)。 速度控制和转矩控制是FOC最常用的控制模式。位置控制模式不太常见。大多数牵引应用使用转矩控制模式,在该模式下,电动机控制系统遵循参考转矩值。在速度控制模式下,电机控制器遵循参考速度值,并生成用于形成内

>>> 1万+

Java数据结构面试题以及答案

B树和B+树的区别?B树和B+树的优点分别是?HashMap和Hashtable的区别?ConcurrentHashMap的原理?ArrayList和LinkedList的区别?String、StringBuilder和StringBuffer的区别?ArrayList和Vector的区别?Collection下有哪些子类?Comparable和Comparator的区别?

星空 2088

lidar360 V8.0 & lidar360MLS V8.0雷达点云数据处理软件

机载林业 — 基于机载激光雷达点云数据提取一系列森林结构参数(如:高度分位数、叶面积指数、郁闭度等),分割单木并提取单木参数(包括树的位置、树高、胸径、枝下高、冠幅等属性),利用软件的多种回归分析功能可以结合地面调查数据反演森林生物量、蓄积量等功能参数。还可以生成等高线、山体阴影、坡度、坡向、粗糙度等多种产品。分类 — LiDAR360提供多种分类功能,包括地面点分类、模型关键点分类、选择区域地面点分类、机器学习模型分类(可高效地分离建筑、植被、路灯等通用类别)、深度学习模型分类、自定义深度学习分类等。

2403_83796253的博客 5147

trae CN 配置ida的mcp教程

本文介绍了在TraeCN中配置IDA Pro MCP服务的完整步骤:1)准备IDA Pro 9.0+和Python 3.11+环境;2)安装MCP服务端并配置插件;3)生成MCP配置文件;4)在TraeCN中添加HTTP类型MCP服务(默认端口13337);5)测试连接。重点说明了HTTP配置方式的操作流程,包括手动启动服务、正确填写JSON配置等关键环节。

2401_87915504的博客 1954

应对程序员面试,你必须知道的八大数据结构

大数据文摘出品编译:Hope、睡不着的iris、胡笳、云舟瑞士计算机科学家Niklaus Wirth在1976年写了一本书,名为《算法+数据结构=编程》。40多年后,这个等式仍被奉为真理。...

JAVA高级架构 920

UE4_用户控件_6_通过控件蓝图内部变量来修改进度条的值

发现控件类图类的引用和用户控类引用不兼容,修改变量类型。我们需要添加到视口,同时设置输入模式。创建按钮的点击事件,当点击时调用角色的自定义事件clearwidget。可以了,但是没有退出控件,没有鼠标,所以改进一下。

Growthofnotes的博客 1236

2022年史上最全Java面试题:数据结构+算法+JVM+线程+finalize+GC

无论是对于刚入行工作还是已经工作几年的java开发者来说,面试求职始终是你需要直面的一件事情。首先梳理自己的知识体系,针对性准备,会有事半功倍的效果。我们往往会把重点放在技术上,而忽略了人事部分,实际上人事面试也会影响到最终的结果,把每一个环节做好,最终的结果自然不会差。...

m0_62051288的博客 1718

Synopsys SCL许可证服务器搭建详解:从安装到生成.dat文件

本文详细解析了Synopsys SCL许可证服务器的完整搭建流程,从系统环境准备、SCL安装到生成.dat文件。重点阐述了如何正确获取HOST ID、配置License文件以及调试常见故障,为数字芯片设计工程师提供了一套从零到一的实战避坑指南,确保EDA工具链稳定运行。

weixin_29306011的博客 610

零代码构建AI智能体:COZE可视化工作流实战指南

AI智能体(AI Agent)是当前人工智能领域的重要发展方向,它通过模块化设计和工作流驱动,使大语言模型从被动对话转向主动执行。其核心原理在于将复杂的任务分解为可规划、可执行的步骤,并调用外部工具(插件)完成闭环。这一技术价值在于显著降低了自动化流程的开发门槛,让非程序员也能构建实用的数字助手。典型的应用场景包括智能客服、内容自动生成、数据分析和跨系统业务流程自动化。本文以COZE平台为例,深入解析如何通过其直观的可视化界面和丰富的插件生态,像搭积木一样快速搭建如“早安简报生成器”等实用智能体,并分享指令

467

数据结构常见面试题及详细java示例

如何在给定数组中找到重复的元素? 链表反转 二叉树的深度 如何在给定数组中找到缺失的数? 如何实现一个队列使用两个栈? 如何从链表中删除倒数第n个节点? 如何检查字符串中的括号是否正确配对? 如何从给定数组中找到前k大的元素? 二叉树的层次遍历 合并K个有序链表 二叉树中的最大路径和 找到数组中第K个最大的元素

哎 你看的博客 1160

Colab虚拟环境配置全攻略:从安装到实战应用

本文详细介绍了在Google Colab中配置Python虚拟环境的完整流程与实战技巧。通过安装Anaconda、创建独立环境、解决常见错误及结合深度学习项目应用,帮助用户有效管理依赖、避免冲突,并利用环境持久化策略提升在Colab中的开发效率与项目可复现性。

weixin_29204121的博客 339

程序员:新手到专家的5个阶段

原文链接:https://dsx2016.com/?p=101 程序员需要不断的学习 不仅仅是学习新技术,还包括应用的问题域,用户的奇思妙想,同事的古怪习惯,行业的八卦新闻和项目演进的重要特征 我们必须学习学习再学习,持续不断的学习,然后把学习成果应用到解决日常遇到的一切新旧问题上 ➢ 阶段一:新手 新手在该技能领域经验很少或者根本没有经验,这里提到的经验,指的是通过实施这项技术促进...

大师兄 2561

软件产品国际化:前后端及App多语言版本解决方案(超详细实现过程)

多语言版本解决方案是应对全球化趋势的关键策略,它通过构建灵活且可扩展的架构,支持软件产品在不同语言和文化环境下的顺畅运行与展示。此方案涵盖了前端多语言界面实现、后端多语言数据处理及大数据环境下的多语言支持等多个层面,确保公司能够高效地推出适应全球用户多样化需求的软件产品。在前端多语言界面实现方面,解决方案采用了国际化与本地化的结合方法。国际化过程确保软件的功能和代码设计能够处理多种语言和文化习惯,而本地化则针对特定地区进行界面和内容的调整。

大模型大数据攻城狮的专栏 2752

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

新手引导

服务端发来通知 调用新手引导的Control //新手引导的控制器 public class UIGuideCtrl : Singleton<UIGuideCtrl> { //进入引导 public void Enter() { EventCenter.Broadc...

qq_35647121的博客 578

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

新手引导的一些实现想法

对于全遮罩固定流程必做的新手引导可以试下这种方式: 1.程序初期框架设计好,尽量降低耦合性。通讯与显示严格分离。 2.前台后台各配置好新手引导信息文件,前台主要是一些显示、位置、对应操作序号等信息。后台是每一步新手操作后数据变动信息。 3.将新手引导做成模拟操作。做一个位于顶层的新手引导层。比如点击某个按钮弹出对话框,或者打开某一界面的功能,相当于点击到新手引导层对应位置,然后根据数据发送模...

在代码身上,用心去飞翔 2826

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

请给新手多一些耐心

原创文章,如有转载,请注明出处:http://blog.youkuaiyun.com/yihui823/article/details/6746448 写这篇文章,并不是突然来的想法。写之前也犹豫了很久,因为担心会遭到很多白眼,被众多高手吐槽。反复思量,还是决定写一些,也算是给自己

yihui823的专栏 5059

从新手到专家的的几个阶段

德雷福斯模型–读《程序员的思维修炼:开发认知潜能的九堂课》背景早在20世纪70年代,德雷福斯兄弟(休伯特和斯图尔特)就开始研究人类如何获取和掌握技能。 他们的研究表明,从新手到专家要经历巨大的变化。在这个过程中,人们不只是”知道更多”或者获得了技术,而且还在如何认识世界,如何解决问题以及如何形成使用的思维模型等方面体验到根本性的区别。人们获取新技术的方式发生了变化,影响(促进或阻碍)人们工作业绩的

xidwong的专栏 3826

新手到专家所经历的 5 个阶段

阶段 1 :新手          新手需要指令清单 由定义可知,新手在该技能领域经验很少或者根本没有经验。这里提到的经验,指的是通过实施这项技术促进了思维的改变。举个反例,可能一个开发人员声称拥有十年的经验,但实际上只是一年的经验重复了九次,那么这就不算是经验。 新手非常在乎他们能否成功。没有太多经验指导他们,他们不知道自己的行为是对是错。新手不是特别想要学习,他们只是想实现一个立竿见影的...

雨落本无晴 3312

unity 新手引导

case (int)GSToGC.MsgID.eMsgToGCFromGS_GuideResp: print ("eMsgToGCFromGS_GuideResp"); OnNetMsg_NotifyGuideResp(stream); break; Int32 OnNetMsg_NotifyGuideRe

海涛高软 2694

跨网页的新手引导_IOS中新手引导页面的实现(新手引导,Guide)

1.由于项目的需要,我今天学习了新手的引导,接下我来说下新手引导的使用方法:(在程序中运行一次)接下来是实现代码:在AppDelegate.m 的代码:- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {UIViewControll...

weixin_28518991的博客 255

新手上路来看看

 新手上路来看看,

秦慰(Net) 244

优快云新手教程

<div class="blog-content-box"> <div class="article-header-box"> <div class="article-header"> <div class="article-title-box"> <h1 class="title-article">优快云新手教程</h1> &l.

qq_27148531的博客 2244

大家好,我是新手,请大家指导一下

<br />大家好,我是新手,请大家指导一下

cyzjjx的专栏 321

新手报到来了

大家好,做为一个新手来这里和大家在一起,希望得到大家的帮助。谢谢了。

u011662354的专栏 415
上一篇: [算法]面试时的Java数据结构与算法
下一篇: 常考面试算法题类型总结(来自知乎)
还不够
博客等级 码龄16年 113粉丝 24原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值