当前位置:   article > 正文

java经典算法题_java算法题

java算法题

目录

1.Java多线程:写一下两个线程交替打印 0~100 的奇偶数

2.线程安全的单例模式

3.用两个栈实现队列

4.实现单链表反转操作

5.Java实现二分查找

6.冒泡排序

7.快速排序

快速排序的基本思想:

8.Java单链表实现快速排序

9.二叉树的前序遍历

10.二叉树的中序遍历

11.二叉树的后序遍历

12.java实现逆波兰表达式

13.斐波那契数列及青蛙跳台阶问题


1.Java多线程:写一下两个线程交替打印 0~100 的奇偶数

这种实现方式的原理就是线程1打印之后唤醒其他线程,然后让出锁,自己进入休眠状态。因为进入了休眠状态就不会与其他线程抢锁,此时只有线程2在获取锁,所以线程2必然会拿到锁。线程2以同样的逻辑执行,唤醒线程1并让出自己持有的锁,自己进入休眠状态。这样来来回回,持续执行直到任务完成。就达到了两个线程交替获取锁的效果了。

  1. private int count = 0;
  2. private final Object lock = new Object();
  3. public void turning() throws InterruptedException {
  4. Thread even = new Thread(() -> {
  5. while (count <= 100) {
  6. synchronized (lock) {
  7. System.out.println("偶数: " + count++);
  8. lock.notifyAll();
  9. try {
  10. // 如果还没有结束,则让出当前的锁并休眠
  11. if (count <= 100) {
  12. lock.wait();
  13. }
  14. } catch (InterruptedException e) {
  15. e.printStackTrace();
  16. }
  17. }
  18. }
  19. });
  20. Thread odd = new Thread(() -> {
  21. while (count <= 100) {
  22. synchronized (lock) {
  23. System.out.println("奇数: " + count++);
  24. lock.notifyAll();
  25. try {
  26. // 如果还没有结束,则让出当前的锁并休眠
  27. if (count <= 100) {
  28. lock.wait();
  29. }
  30. } catch (InterruptedException e) {
  31. e.printStackTrace();
  32. }
  33. }
  34. }
  35. });
  36. even.start();
  37. // 确保偶数线程线先获取到锁
  38. Thread.sleep(1);
  39. odd.start();
  40. }

2.线程安全的单例模式

双锁判断机制创建单例模式

  1. public class DoubleCheckLockSinglenon {
  2. private static volatile DoubleCheckLockSinglenon doubleCheckLockSingleon = null;
  3. public DoubleCheckLockSinglenon(){}
  4. public static DoubleCheckLockSinglenon getInstance(){
  5. if (null == doubleCheckLockSingleon) {
  6. synchronized(DoubleCheckLockSinglenon.class){
  7. if(null == doubleCheckLockSingleon){
  8. doubleCheckLockSingleon = new DoubleCheckLockSinglenon();
  9. }
  10. }
  11. }
  12. return doubleCheckLockSingleon;
  13. }
  14. public static void main(String[] args) {
  15. System.out.println(DoubleCheckLockSinglenon.getInstance());
  16. }
  17. }

3.用两个栈实现队列

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

解题思路
两个栈stack1和stack2 。
开始时,每次添加队尾元素到stack1中。
如果需要弹出队头元素,则将stack1中的元素弹出并push到stack2中,再将stack2的栈顶元素弹出,即为弹出了队头元素。
如果stack2中是非空的,再在队尾中添加元素的时候仍然加到stack1中,从stack2中弹出队头元素。
只有当stack2为空的时候,弹出队头元素才需要将stack1中的元素转移到stack2中。

  1. import java.util.Stack;
  2. public class Solution {
  3. Stack<Integer> stack1 = new Stack<Integer>();
  4. Stack<Integer> stack2 = new Stack<Integer>();
  5. public void push(int node) {
  6. stack1.push(node);
  7. }
  8. public int pop() {
  9. if(stack2.size() == 0) {
  10. while(!stack1.isEmpty()) {
  11. int temp = stack1.peek();
  12. stack2.push(temp);
  13. stack1.pop();
  14. }
  15. }
  16. int res = stack2.peek();
  17. stack2.pop();
  18. return res;
  19. }
  20. }

4.实现单链表反转操作

 单链表是一种常见的数据结构,由一个个节点通过指针方式连接而成,每个节点由两部分组成:一是数据域,用于存储节点数据。二是指针域,用于存储下一个节点的地址。在Java中定义如下:

  1. public class Node {
  2. private Object data;//数据域
  3. private Node next;//指针域
  4. public Node(Object data){
  5. this.data = data;
  6. }
  7. public Node(Object data,Node next){
  8. this.data = data;
  9. this.next = next;
  10. }
  11. public Object getData() {
  12. return data;
  13. }
  14. public void setData(Object data) {
  15. this.data = data;
  16. }
  17. public Node getNext() {
  18. return next;
  19. }
  20. public void setNext(Node next) {
  21. this.next = next;
  22. }
  23. }

先说下思路:所谓的单链表反转,就是把每个节点的指针域由原来的指向下一个节点变为指向其前一个节点。但由于单链表没有指向前一个节点的指针域,因此我们需要增加一个指向前一个节点的指针pre,用于存储每一个节点的前一个节点。此外,还需要定义一个保存当前节点的指针cur,以及下一个节点的next。定义好这三个指针后,遍历单链表,将当前节点的指针域指向前一个节点,之后将定义三个指针往后移动,直至遍历到最后一个节点停止。
 

  1. public static Node reverseListNode(Node head){
  2. //单链表为空或只有一个节点,直接返回原单链表
  3. if (head == null || head.getNext() == null){
  4. return head;
  5. }
  6. //前一个节点指针
  7. Node preNode = null;
  8. //当前节点指针
  9. Node curNode = head;
  10. //下一个节点指针
  11. Node nextNode = null;
  12. while (curNode != null){
  13. nextNode = curNode.getNext();//nextNode 指向下一个节点
  14. curNode.setNext(preNode);//将当前节点next域指向前一个节点
  15. preNode = curNode;//preNode 指针向后移动
  16. curNode = nextNode;//curNode指针向后移动
  17. }
  18. return preNode;
  19. }

5.Java实现二分查找

二分查找又称折半查找,查找效率不错

适用场景:顺序存储结构且按有序排列,这也是它的缺点。

  1. /*
  2. *递归实现二分算法
  3. */
  4. public static int binSearch_2(int key,int[] array,int low,int high){
  5. //防越界
  6. if (key < array[low] || key > array[high] || low > high) {
  7. return -1;
  8. }
  9. int middle = (low+high)/2;
  10. if(array[middle]>key){
  11. //大于关键字
  12. return binSearch_2(key,array,low,middle-1);
  13. }else if(array[middle]<key){
  14. //小于关键字
  15. return binSearch_2(key,array,middle+1,high);
  16. }else{
  17. return array[middle];
  18. }
  19. }

6.冒泡排序

N个数字要排序完成,总共进行N-1趟排序,每i趟的排序次数为(N-i)次,所以可以用双重循环语句,外层控制循环多少趟,内层控制每一趟的循环次数,即

  1. /*
  2. * 冒泡排序
  3. */
  4. public class BubbleSort {
  5.   public static void main(String[] args) {
  6.     int[] arr={6,3,8,2,9,1};
  7.     System.out.println("排序前数组为:");
  8.     for(int num:arr){
  9.       System.out.print(num+" ");
  10.     }
  11.     for(int i=0;i<arr.length-1;i++){//外层循环控制排序趟数
  12.       for(int j=0;j<arr.length-1-i;j++){//内层循环控制每一趟排序多少次
  13.         if(arr[j]>arr[j+1]){
  14.           int temp=arr[j];
  15.           arr[j]=arr[j+1];
  16.           arr[j+1]=temp;
  17.         }
  18.       }
  19.     }
  20.     System.out.println();
  21.     System.out.println("排序后的数组为:");
  22.     for(int num:arr){
  23.       System.out.print(num+" ");
  24.     }
  25.   }
  26. }

用时间复杂度来说:

  1.如果我们的数据正序,只需要走一趟即可完成排序。所需的比较次数C和记录移动次数M均达到最小值,即:Cmin=n-1;Mmin=0;所以,冒泡排序最好的时间复杂度为O(n)。

  2.如果很不幸我们的数据是反序的,则需要进行n-1趟排序。每趟排序要进行n-i次比较(1≤i≤n-1),且每次比较都必须移动记录三次来达到交换记录位置。在这种情况下,比较和移动次数均达到最大值:

冒泡排序的最坏时间复杂度为:O(n2) 。

综上所述:冒泡排序总的平均时间复杂度为:O(n2) 。

7.快速排序

快速排序的基本思想:

  1. 1). 先从数列中取出一个数作为基准数。
  2. 2). 分区过程,将比这个数大的数全放到它的右边,小于或等于它的数全放到它的左边。
  3. 3). 再对左右区间重复第二步,直到各区间只有一个数。
  1. public class Main {
  2. //快排实现方法
  3. public static void quickRow(int[] array,int low,int high) {
  4. int i,j,pivot;
  5. //结束条件
  6. if(low >= high) {
  7. return;
  8. }
  9. i = low;
  10. j = high;
  11. //选择的节点,这里选择的数组的第一数作为节点
  12. pivot = array[low];
  13. while(i<j) {
  14. //从右往左找比节点小的数,循环结束要么找到了,要么i=j
  15. while(array[j] >= pivot && i<j) {
  16. j--;
  17. }
  18. //从左往右找比节点大的数,循环结束要么找到了,要么i=j
  19. while(array[i] <= pivot && i<j) {
  20. i++;
  21. }
  22. //如果i!=j说明都找到了,就交换这两个数
  23. if(i<j) {
  24. int temp = array[i];
  25. array[i] = array[j];
  26. array[j] = temp;
  27. }
  28. }
  29. //i==j一轮循环结束,交换节点的数和相遇点的数
  30. array[low] = array[i];
  31. array[i] = pivot;
  32. //数组“分两半”,再重复上面的操作
  33. quickRow(array,low,i-1);
  34. quickRow(array,i+1,high);
  35. }
  36. public static void main(String[] args) {
  37. int[] array = {6,17,38,59,2,10};
  38. int low = 0,high = array.length-1;
  39. quickRow(array,low,high);
  40. for (int i : array){
  41. System.out.println(i);
  42. }
  43. }
  44. }

8.Java单链表实现快速排序

单链表的实现为:
(1)使第一个节点为中心点
(2)创建2个指针(p,q),p指向头结点,q指向p的下一个节点
(3)q开始遍历,如果发现q的值比中心点的值小,则此时p=p->next,并且执行当前p的值和q的值交换,q遍历到链表尾即可
(4)把头结点的值和p的值执行交换。此时p节点为中心点,并且完成1轮快排
(5)使用递归的方法即可完成排序

  1. public static void main(String[] args) {
  2. ListNode head = new ListNode(2);
  3. ListNode l1 = new ListNode(2);
  4. ListNode l2 = new ListNode(5);
  5. ListNode l3 = new ListNode(3);
  6. ListNode l4 = new ListNode(8);
  7. ListNode l5 = new ListNode(4);
  8. ListNode l6 = new ListNode(2);
  9. ListNode l7 = new ListNode(1);
  10. /*ListNode p = l1;
  11. System.out.println(p.equals(head));
  12. System.out.println(p == head);*/
  13. head.next = l1;
  14. l1.next = l2;
  15. l2.next = l3;
  16. l3.next = l4;
  17. l4.next = l5;
  18. l5.next = l6;
  19. l6.next = l7;
  20. l7.next = null;
  21. ListNode p = head;
  22. while (p.next != null) {
  23. System.out.print(p.val);
  24. p = p.next;
  25. }
  26. System.out.print(p.val);
  27. System.out.println();
  28. ListNode begin = head, end = p;
  29. new SingleLinkedListSorting().quickSort(begin, end);
  30. p = head;
  31. while (p != null) {
  32. System.out.print(p.val);
  33. p = p.next;
  34. }
  35. }
  36. public void quickSort(ListNode begin, ListNode end) {
  37. //判断为空,判断是不是只有一个节点
  38. if (begin == null || end == null || begin == end)
  39. return;
  40. //从第一个节点和第一个节点的后面一个几点
  41. ListNode first = begin;
  42. ListNode second = begin.next;
  43. int nMidValue = begin.val;
  44. //结束条件,second到最后了
  45. while (second != end.next && second != null) {
  46. if (second.val < nMidValue) {
  47. first = first.next;
  48. //判断一下,避免后面的数比第一个数小,不用换的局面
  49. if (first != second) {
  50. int temp = first.val;
  51. first.val = second.val;
  52. second.val = temp;
  53. }
  54. }
  55. second = second.next;
  56. }
  57. //判断,有些情况是不用换的,提升性能
  58. if (begin != first) {
  59. int temp = begin.val;
  60. begin.val = first.val;
  61. first.val = temp;
  62. }
  63. //前部分递归
  64. quickSort(begin, first);
  65. //后部分递归
  66. quickSort(first.next, end);
  67. }

9.二叉树的前序遍历

  前序遍历(DLR,lchild,data,rchild),是二叉树遍历的一种,也叫做先根遍历、先序遍历、前序周游,可记做根左右。前序遍历首先访问根结点然后遍历左子树,最后遍历右子树。

  1. package test;
  2. //前序遍历的递归实现与非递归实现
  3. import java.util.Stack;
  4. public class Test
  5. {
  6. public static void main(String[] args)
  7. {
  8. TreeNode[] node = new TreeNode[10];//以数组形式生成一棵完全二叉树
  9. for(int i = 0; i < 10; i++)
  10. {
  11. node[i] = new TreeNode(i);
  12. }
  13. for(int i = 0; i < 10; i++)
  14. {
  15. if(i*2+1 < 10)
  16. node[i].left = node[i*2+1];
  17. if(i*2+2 < 10)
  18. node[i].right = node[i*2+2];
  19. }
  20. preOrderRe(node[0]);
  21. }
  22. public static void preOrderRe(TreeNode biTree)
  23. {//递归实现
  24. System.out.println(biTree.value);
  25. TreeNode leftTree = biTree.left;
  26. if(leftTree != null)
  27. {
  28. preOrderRe(leftTree);
  29. }
  30. TreeNode rightTree = biTree.right;
  31. if(rightTree != null)
  32. {
  33. preOrderRe(rightTree);
  34. }
  35. }
  36. public static void preOrder(TreeNode biTree)
  37. {//非递归实现
  38. Stack<TreeNode> stack = new Stack<TreeNode>();
  39. while(biTree != null || !stack.isEmpty())
  40. {
  41. while(biTree != null)
  42. {
  43. System.out.println(biTree.value);
  44. stack.push(biTree);
  45. biTree = biTree.left;
  46. }
  47. if(!stack.isEmpty())
  48. {
  49. biTree = stack.pop();
  50. biTree = biTree.right;
  51. }
  52. }
  53. }
  54. }
  55. class TreeNode//节点结构
  56. {
  57. int value;
  58. TreeNode left;
  59. TreeNode right;
  60. TreeNode(int value)
  61. {
  62. this.value = value;
  63. }
  64. }

10.二叉树的中序遍历

中序遍历(LDR)是 二叉树遍历的一种,也叫做 中根遍历、中序周游。在二叉树中,先左后根再右。巧记:左根右。

  1. import java.util.Stack;
  2. public class Test
  3. {
  4. public static void main(String[] args)
  5. {
  6. TreeNode[] node = new TreeNode[10];//以数组形式生成一棵完全二叉树
  7. for(int i = 0; i < 10; i++)
  8. {
  9. node[i] = new TreeNode(i);
  10. }
  11. for(int i = 0; i < 10; i++)
  12. {
  13. if(i*2+1 < 10)
  14. node[i].left = node[i*2+1];
  15. if(i*2+2 < 10)
  16. node[i].right = node[i*2+2];
  17. }
  18. midOrderRe(node[0]);
  19. System.out.println();
  20. midOrder(node[0]);
  21. }
  22. public static void midOrderRe(TreeNode biTree)
  23. {//中序遍历递归实现
  24. if(biTree == null)
  25. return;
  26. else
  27. {
  28. midOrderRe(biTree.left);
  29. System.out.println(biTree.value);
  30. midOrderRe(biTree.right);
  31. }
  32. }
  33. public static void midOrder(TreeNode biTree)
  34. {//中序遍历费递归实现
  35. Stack<TreeNode> stack = new Stack<TreeNode>();
  36. while(biTree != null || !stack.isEmpty())
  37. {
  38. while(biTree != null)
  39. {
  40. stack.push(biTree);
  41. biTree = biTree.left;
  42. }
  43. if(!stack.isEmpty())
  44. {
  45. biTree = stack.pop();
  46. System.out.println(biTree.value);
  47. biTree = biTree.right;
  48. }
  49. }
  50. }
  51. }
  52. class TreeNode//节点结构
  53. {
  54. int value;
  55. TreeNode left;
  56. TreeNode right;
  57. TreeNode(int value)
  58. {
  59. this.value = value;
  60. }
  61. }

11.二叉树的后序遍历

后序遍历(LRD)是 二叉树遍历的一种,也叫做 后根遍历、后序周游,可记做左右根。后序遍历有 递归算法和非递归算法两种。在二叉树中,先左后右再根。巧记:左右根。

  1. import java.util.Stack;
  2. public class Test
  3. {
  4. public static void main(String[] args)
  5. {
  6. TreeNode[] node = new TreeNode[10];//以数组形式生成一棵完全二叉树
  7. for(int i = 0; i < 10; i++)
  8. {
  9. node[i] = new TreeNode(i);
  10. }
  11. for(int i = 0; i < 10; i++)
  12. {
  13. if(i*2+1 < 10)
  14. node[i].left = node[i*2+1];
  15. if(i*2+2 < 10)
  16. node[i].right = node[i*2+2];
  17. }
  18. postOrderRe(node[0]);
  19. System.out.println("***");
  20. postOrder(node[0]);
  21. }
  22. public static void postOrderRe(TreeNode biTree)
  23. {//后序遍历递归实现
  24. if(biTree == null)
  25. return;
  26. else
  27. {
  28. postOrderRe(biTree.left);
  29. postOrderRe(biTree.right);
  30. System.out.println(biTree.value);
  31. }
  32. }
  33. public static void postOrder(TreeNode biTree)
  34. {//后序遍历非递归实现
  35. LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
  36. // 指向上一个被访问的节点
  37. TreeNode pre = null;
  38. while(biTree!=null || !stack.isEmpty()){
  39. // 遍历到左下
  40. while(biTree!=null){
  41. stack.push(biTree);
  42. biTree = biTree.left;
  43. }
  44. biTree = stack.pop();
  45. if(biTree.right==null || biTree.right == pre){
  46. System.out.println(biTree.value);
  47. pre = biTree;
  48. // 保证了不会再次遍历已经遍历过的左子树
  49. biTree= null;
  50. }else{
  51. stack.push(biTree);
  52. biTree= biTree.right;
  53. }
  54. }
  55. }
  56. }
  57. class TreeNode//节点结构
  58. {
  59. int value;
  60. TreeNode left;
  61. TreeNode right;
  62. TreeNode(int value)
  63. {
  64. this.value = value;
  65. }
  66. }

12.java实现逆波兰表达式

逆波兰表达式把运算量写在前面,把算符写在后面。

  1. private static List<String> sign=new ArrayList<>();
  2. static {
  3. sign.add("+");
  4. sign.add("-");
  5. sign.add("*");
  6. sign.add("/");
  7. }
  8. public static void main(String[] args) {
  9. String[] arrs={"2", "1", "+", "3", "*"};
  10. System.out.println(evalRPN(arrs)); //9
  11. String[] arrs1={"4", "13", "5", "/", "+"};
  12. System.out.println(evalRPN(arrs1)); //6
  13. }
  14. public static int evalRPN(String[] tokens) {
  15. Stack<Integer> mathStack=new Stack<>();
  16. for (int i = 0; i <tokens.length ; i++) {
  17. String s=tokens[i];
  18. if(sign.contains(s)){
  19. Integer sum=0;
  20. Integer num2=mathStack.pop();
  21. Integer num1=mathStack.pop();
  22. if("+".equals(s)){
  23. sum=num1+num2;
  24. }else if("-".equals(s)){
  25. sum=num1-num2;
  26. }else if("*".equals(s)){
  27. sum=num1*num2;
  28. }else if("/".equals(s)){
  29. sum=num1/num2;
  30. }
  31. // System.out.println(num1+s+num2+"="+sum);
  32. mathStack.push(sum);
  33. }else {
  34. mathStack.push(Integer.parseInt(s));
  35. }
  36. }
  37. return mathStack.pop();
  38. }

13.斐波那契数列及青蛙跳台阶问题

递归方式:

  1. public int Fibonacci1(int n) {
  2. if (n <= 0) return 0;
  3. if (n == 1) return 1;
  4. return Fibonacci1(n-1) + Fibonacci1(n - 2);
  5. }

非递归:

  1. public int Fibonacci2(int n) {
  2. if (n <= 0) return 0;
  3. if (n == 1) return 1;
  4. int i=0;int j=1;
  5. int res=0;
  6. for(int x=2;x<=n;x++){
  7. res = i+j;
  8. i=j;
  9. j=res;
  10. }
  11. return res;
  12. }

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号