蓝桥杯java算法学习(二)

注意:以下部分内容摘自Acwing,仅用于个人学习记录,不做任何商业用途。

(1)单链表操作

public class Main {
	
	//数据结构
private static int N=100010;
private static int[] e=new int[N];//表示结点i的值
private static int[] ne=new int[N];//表示结点i下一个结点的序号
private static int head;//头结点的下标
private static int idx;//表示存储当前结点已经使用结点的下一个结点
  

    private static void init() {
    	head=-1;//没有头结点
    	idx=0;
    }
    
    //插入头结点
    private static void addToHead(int val) {
    	e[idx]=val;  // 赋值
    	ne[idx]=head;// 插入之前头结点的前面
    	head=idx;    // 更新头结点信息
    	idx++; 		 // idx向右移动
    }
    
    // 将下标是 k的点后面的点删掉
    private static void remove(int k) {
    	ne[k]=ne[ne[k]]; // 让下标为 k的结点指向 下个结点的下个结点
    }
    
    // 将 val插入下标为 k的点的后面
    private static void add(int k, int val) {
        e[idx]=val;
        ne[idx]=ne[k];
        ne[k]=idx;
        idx++;
    }
    
    //主程序
    public static void main(String[] args) {
    	//略
    }
}

(2)表达式求值

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Stack;

public class Main {
    public static void main(String[] args) throws IOException {
    	
    	//num用来存储数字,op用来存储运算符
    	Stack<Integer> num=new Stack<Integer>();
    	Stack<Character> op=new Stack<Character>();
    	BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    	
        //把运算符的优先级引入到键值对中
    	HashMap<Character,Integer> map=new HashMap<Character,Integer>();
    	map.put('+',1);
    	map.put('-',1);
    	map.put('*',2);
    	map.put('/',2);
    	
    	//读入
    	String s=br.readLine();
    	
    	//处理
    	for(int i=0;i<s.length();i++) {
    		
    		if(Character.isDigit(s.charAt(i))) {
    			//如果是数字的话
    			int x=0,j=i;
    			while(j<s.length()&&Character.isDigit(s.charAt(j)))x=x*10+s.charAt(j++)-'0';
    			num.push(x);
    			i=j-1;
    		}else if(s.charAt(i)=='(') {
    			//如果是左括号的话
    			op.push(s.charAt(i));
    		}else if(s.charAt(i)==')') {
    			//如果是右括号的话
    			while(op.peek()!='(')eval(num,op);
    			op.pop();
    		}else {
    			//如果是运算符的话,高优先级的运算符需要优先处理后低优先级的运算符才能进栈
    			while(!op.isEmpty()&&op.peek()!='('&&map.get(op.peek())>=map.get(s.charAt(i)))eval(num,op);
    			op.push(s.charAt(i));
    		}
    		
    	}
    	while (op.size() > 0) eval(num, op);
        System.out.print(num.peek());
    }
    public static void eval (Stack<Integer> num, Stack<Character> op){
    	 int num1 = num.pop();
         int num2 = num.pop();
         char x = op.pop();
         if(x == '*') num.push(num2 * num1);
         else if (x == '/') num.push(num2 / num1);
         else if (x == '+') num.push(num2 + num1);
         else if (x == '-') num.push(num2 - num1);
    }
}

(3)单调栈

import java.util.*;

public class Main{
    static int m;
    static int N = 100010;
    static int[] stack = new int[N];
    static int tt = 0;
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        m = sc.nextInt();
        while(m -- > 0){
            int x;
            x = sc.nextInt();
            while(tt != 0 && stack[tt] >= x) tt --;
            if(tt != 0) System.out.print(stack[tt] + " ");
            else System.out.print("-1 ");
            stack[++ tt] = x;
        }
    }
}

图片来自:

作者:Hasity
链接:https://www.acwing.com/solution/content/27437/
来源:AcWing

(4)Trie树(字典树)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
	
	private static int N=100010;
	private static int[][] son=new int[N][26];//Trie树中每个节点的所有儿子
	private static int[] cnt=new int[N];//以当前这个点结尾的单词有多少个
	private static int idx;//当前用的的哪个下标,下标0:既是根节点又是空节点
	
	public static void main(String[] args) throws IOException {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		int n=Integer.parseInt(br.readLine());
		while(n-->0) {
			String[] s=br.readLine().split(" ");
			if(s[0].equals("I"))insert(s[1].toCharArray());
			if(s[0].equals("Q"))System.out.println(query(s[1].toCharArray()));
		}
	}
	
   public static void insert(char[] str) {
	   int p=0;
	   for(int i=0;i<str.length;i++) {
		   int u=str[i]-'a';
		   if(son[p][u]==0)son[p][u]=++idx;
		   p=son[p][u];
	   }
	   cnt[p]++;
   }
   
   public static int query(char[] str) {
	   int p=0;
	   for(int i=0;i<str.length;i++) {
		   int u=str[i]-'a';
		   if(son[p][u]==0)return 0;;
		   p=son[p][u];
	   }
	   return cnt[p];
   }

}

参考链接:https://www.acwing.com/solution/content/27771/

(5)并查集

import java.util.*;

public class Main{
    static int n, m;
    static int N = 100010;
    static int[] p = new int[N];


    public static int find(int x){
        if(x != p[x]) p[x] = find(p[x]);
        return p[x];
    }

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        m = sc.nextInt();

        for(int i = 0; i < n; i ++) p[i] = i;

        String opt;
        int a, b;
        while(m -- > 0){
            opt = sc.next();
            a = sc.nextInt();
            b = sc.nextInt();
            if(opt.equals("M")) p[find(a)] = find(b);
            else{
                if(find(a) == find(b)) System.out.println("Yes");
                else System.out.println("No");
            }
        }
    }
}

作者:派大星的梦想
链接:https://www.acwing.com/solution/content/33345/
来源:AcWing

(6)堆排序

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
	private static int N = 100010;
	private static int[] a=new int[N];//保存数组
	private static int n, m;//n个点,求前m小
	private static int r ;//堆得右边界
	public static void main(String[] args) throws IOException {
	   BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	   String[] s=br.readLine().split(" ");
	   n=Integer.parseInt(s[0]);
	   m=Integer.parseInt(s[1]);
	   r=n;
	   String[] s2=br.readLine().split(" ");
	   for(int i=1;i<=s2.length;i++) {
		   a[i]=Integer.parseInt(s2[i-1]); 	
	   }
	   
	 //从第一个非叶节点开始,从右到左,从下到上处理每个节点
	   for(int i = n /2 ; i >= 1; i--)
	   {
	       down(i);
	   }
	 //输出m个最小值
	    while (m -->0)
	    {
	        //堆顶保存的最小值,输出堆顶
	        System.out.print(a[1]+" ");

	        //将堆顶和右边界交换
	        int x=a[1];
	        a[1]=a[r];
	        a[r]=x;

	        //右边界左移
	        r--;

	        //重新处理堆顶
	        down(1);
	    }
	}
	
	public static void down(int i) {
		int p=i;
		if(i*2<=r&&a[i*2]<a[p])p=2*i;
		if(i*2+1<=r&&a[i*2+1]<a[p])p=i*2+1;
		if(i!=p) {
			int x=a[i];
			a[i]=a[p];
			a[p]=x;
			down(p);
		}
	}
}

思路参考:https://www.acwing.com/solution/content/120483/

(7)java哈希表

两种方式:(1)拉链法;(2)开放寻址法

(1)拉链法

import java.util.*;

public class Main{
    private static int N = 100003;
    private static int[] a = new int[N];
    private static int[] e = new int[N];
    private static int[] ne = new int[N];
    //设0为空,地址从1开始
    private static int idx = 1;
    public static boolean find(int x){
        int k = (x % N + N) % N;
        //这里需要指针t来遍历,不能直接移动a[k]
        int t = a[k];
        while(t != 0){
            if(x == e[t]){
                return true;
            }
            t = ne[t];
        }
        return false;
    }
    public static void insert(int x){
        int k = (x % N + N) % N;
        e[idx] = x;
        ne[idx] = a[k];
        a[k] = idx++;
    }
    public static void main(String[] args){

        Scanner scanner = new Scanner(System.in);
        int m = scanner.nextInt();
        while(m-- > 0){
           String opt = scanner.next();
           int x = scanner.nextInt();
           if("I".equals(opt)){
              insert(x);
           }else{
               System.out.println(find(x) == false ? "No" : "Yes");
           }
        }
    }
}

(2)开放寻址法

import java.util.*;

public class Main{
    private static int N = 200003;
    //因为要用null标识节点空,所以类型为Integer
    private static Integer[] a = new Integer[N];
    public static int find(int x){
        int k = (x % N + N) % N;
        //别忘了第二个已存在的条件
        while(a[k] != null && a[k] != x){
            k++;
            if(k == N){
                k = 0;
            }
        }
        return k;
    }

    public static void main(String[] args){
        //先将所有位置设为null,标识为空
        for(int i = 0;i < a.length;i++){
            a[i] = null;
        }        
        Scanner scanner = new Scanner(System.in);
        int m = scanner.nextInt();
        while(m-- > 0){
           String opt = scanner.next();
           int x = scanner.nextInt();
           if("I".equals(opt)){
              a[find(x)] = x;
           }else{
               //这是比较的是a[find(x)]
               System.out.println(a[find(x)] == null ? "No" : "Yes");
           }
        }
    }
}

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值