Java算法基础

2025/04/26 Java 共 4985 字,约 15 分钟

基本知识

输入输出

常用的包

  1. java.io
  2. java.util
  3. java.math

基本输入输出

    Scanner in = new Scanner (System.in);//基本方法
    Scanner in = new Scanner (new BufferedInputStream(System.in));//更快
    XXX foo = in.nextXXX();//然后这样给一个XXX类型的变量从标准输入获取值
    while(in.hasNext()) doSomeThing();//循环到EOF时这么写,后面也可以加上变量类型
    in.next().charAt(0);
    PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));//使用缓存加速,比直接使用System.out快
    out.println(n); 
    out.printf("%.2f\n", ans); // 与c语言中printf用法相同
    //输入char

无限输入

java中有个hasNext()函数,作用就是判断是否还有下一个元素,以CTRL+D结束。

import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
	    Scanner in = new Scanner(System.in);
	   double sum = 0.0;
	   int num = 0;
	   while(in.hasNext())
	   {
		   double a=in.nextDouble();
		   num++;
		   sum+=a;
	   }
	   System.out.println(sum/num);
	}
}

控制台输入输出重定向到文件

    FileInputStream fis = new FileInputStream("b.in");  
    System.setIn(fis);  
    PrintStream ps = new PrintStream(new FileOutputStream("b.out"));  
    System.setOut(ps);

文件读写

    PrintStream ps=new PrintSteam(new FileOutputStream("c:\\datain.txt"));
    ps.println(s);
    BufferedReader br = new BufferedReader(new FileReader("/home/zjz/Desktop/myfile.txt"));  

int和String

java.Math

  • max(a,b)方法
  • sqrt返回double类型,记住两个数比较时转换为复杂类型,int比较double会都变double再比较
  • floor()返回double类型 floor(-8.5)=-9.0

四舍五入

这个是四舍五入输出

System.out.printf("%.2f",3.14);

这个也是四舍五入输出

    DecimalFormat decimalFormat=new DecimalFormat("0.00");
    System.out.println(decimalFormat.format(113.146134321));

想要截取输出的办法

    System.out.println(decimalFormat.format(113.146134321-0.005));

或

  double   d   =   13.4324;   
  d=((int)(d*100))/100;   

算法基础

package org.example;


import java.math.BigInteger;
import java.util.*;

public class Main {
    public static void main(String[] args) {

        // Object
        Object a1 = "abc";
        // getClass(). getClass() 会严格比较对象的类,不考虑继承关系。因此,只能判断对象是否确切为某个类,而不能判断它是否是该类的子类。
        System.out.println(a1.getClass() == String.class); // true
        System.out.println(a1 instanceof String); // true

        // Integer
        int max = Integer.MAX_VALUE;
        int min = Integer.MIN_VALUE;
        System.out.println(3 / 2);
        System.out.println((double) 3 / 2);
        System.out.println(3 % 2);
        System.out.println(Math.pow(3, 2));

        // 进制转换
        int num = 10;
        String binaryString = Integer.toBinaryString(num);  // 输出 "1010"
        String s10 = Integer.toString(10, 2); //把int型数据转换乘X进制数并转换成string型

        num = Integer.parseInt(binaryString, 2);  // 输出 9
        // compare. 从小到大时compare返回负数, 返回负数,表示前面的“小”;谁想排在前面,就让它减掉对方!
        System.out.println(Integer.compare(3, 2) > 0);

        // BigInteger
        BigInteger bigInteger = new BigInteger("341241");
        System.out.println(bigInteger);
        System.out.println(bigInteger.toString());

        // String-Integer && Integer-String
        int i = 1;
        String a = Integer.toString(i);
        i = Integer.parseInt(a);

        // char
        String s = 'a' + "bad" + 'j';
        System.out.println(s.charAt(3));
        System.out.println(s.toCharArray());
        char[] cs = new char[10];
        System.out.println(cs.toString());

        // char - ascii
        char c = 'A';
        int asciiValue = (int) c;  // 转换为 ASCII 值
        asciiValue = 65;
        c = (char) asciiValue;  // 转换为字符

        Character.toUpperCase('c');
        Character.toLowerCase('C');
        Character.isLetter('a');
        Character.isDigit('3');

        // String
        String s1 = String.join("#", new String[]{"adf", "df"});
        String[] s2 = "da#4#jk43#43".split("#");
        System.out.println(s2);
        String s3 = String.format("%d111%.2f", 4, 3.1465926);
        // 长度
        s1.length();

        // List
        List<Integer> nums = new ArrayList<>();
        nums = new ArrayList<>(Arrays.asList(1, 23, 4));
        System.out.println(nums);
        // api: add, remove, get, set, contains, size()

        // Queue
        LinkedList<Integer> queue = new LinkedList<>();
//        这个也行Deque<Integer> queue = new LinkedList<>();
        // tail: add, poll
        // head: addFirst, pollFirst
//        queue.getFirst();
//        queue.getLast();

        // heap
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        //改为大顶堆
        pq = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer i1, Integer i2) {
                return i2 - i1;
            }
        });
        //简化写法(匿名Lambda表达式)
        pq = new PriorityQueue<>((n1, n2) -> n2 - n1);

        pq.add(3);
        pq.poll();
        pq.peek();

        /**
         * Map
         */

        Map<Integer, Integer> map = new HashMap<>();
        map.put(3, 2);
        map.getOrDefault(3, 0);
        map.clear();
        map.size();

        //遍历
        //按键遍历
        for (int key : map.keySet())
            System.out.println(key);
        //按值遍历
        for (int value : map.values())
            System.out.println(value);
        //按Entry遍历
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            entry.getKey();
            entry.getValue();
        }


        /**
         * Set
         */
        Set<Integer> set = new HashSet<Integer>();
        set.add(3);
        set.remove(3);
        set.contains(3);
        //需要排序使用TreeSet
        TreeSet<Integer> set1 = new TreeSet<Integer>((o1, o2) -> o2 - o1);
        TreeSet<int[]> set2 = new TreeSet<int[]>(((o1, o2) -> (o1[0] - o2[0])));
        set2.add(new int[]{1, 2});
        // lower, higher 小于 大于,不包括等于
        // floor, ceiling 包含等于
        // first, last最小,最大

        /**
         * List
         */
        ArrayList<Integer> arrayList = new ArrayList<>(Arrays.asList(1, 34, 1, 23, 413, 4, 123, 4132, 4, 123, 4, 31));
        arrayList.sort((o1, o2) -> (o2 - o1));
        System.out.println(arrayList);
        Arrays.sort(new int[]{1, 34, 13, 1, 34});
        List<int[]> ansList = new ArrayList<int[]>();
        ansList.sort(((o1, o2) -> (o1[0] - o2[0])));

        /**
         * Array
         */
        int[] x = new int[10];
        System.out.println(x.length);
        System.out.println(x[2]);
        x = new int[]{134, 3, 3143};

        /**
         * Collections
         */
//        Collections.sort;
//        Collections.reverse();
        /**
         * 二分查找
         * 存在时返回index. 不存在时返回-(index+1), 是负数,index是插入点, 可还原
         */
//        Arrays.binarySearch(, );
//        Collections.binarySearch()

      	/**
      	* Stack
      	*/
              Stack<Integer> stack = new Stack<>();
        stack.add(3);
        stack.pop();
        stack.peek();

    }
}

Search

    Table of Contents