【Java】程序设计竞赛(Java 方向)


1. 头文件

import java.io.*;
import java.math.*;
import java.util.*;
import java.text.*;

2. 输入

Scanner in = new Scanner (new BufferedInputStream(System.in)); // 加Buffer可能会快一些
while(in.hasNext()) // 判断是否有下一个输入可以用
int a;
a = in.nextInt();
double b;
b = in.nextDouble();
String str;
str = in.next();
str = in.nextLine(); // 读一整行
BigInteger c;
c = in.nextBigInteger();
BigDecimal x;
x = in.nextBigDecimal();

3. 输出

// 输出保留几位小数
BigDecimal x = new BigDecimal(0.1415926);
// 这里0指一位数字,#指除0以外的数字(如果是0,则不显示),四舍五入.
DecimalFormat fd = new DecimalFormat("#.00#");
DecimalFormat gd = new DecimalFormat("0.000");
System.out.println("x = " + fd.format(x));
System.out.println("x = " + gd.format(x));
System.out.printf("x = %.6f\n", x);

4. 大数计算

// 赋值
int a;
int[] ar = new int[100];
BigInteger x, y, ans;
BigInteger tmp = new BigInteger(str); //  String 类型转换为BigInteger(BigDecimal)
x = BigInteger.valueOf(a);// int(double)类型转换为BigInteger(BigDecimal)
// BigInteger/BigDecimal 常用方法(所有方法均为1个参数)
ans = x.add(y); // 加
ans = x.subtract(y) // 减
ans = x.multiply(y); // 乘
ans = x.divide(y); // 整除
ans = x.pow(int exponent);// 幂
ans = x.abs(y); // 绝对值
if (x.compareTo(y) == 0) // 比较
// 仅BigInteger:
ans = x.and(y); // 求与
ans = x.or(y); // 求或
ans = x.not(y); // 求反
ans = x.xor(y); // 求异或
ans = x.mod(y); // 取模
ans = x.gcd(y) // 最大公约数

5. 进制转换

String str;
int num, base;
str = Integer.toString(num, base); // 把num当做10进制的数转成base进制的str (base <= 35)
num = Integer.parseInt(str, base); // 把str当做base进制,转成10进制的int
BigInteger m;
m = new BigInteger(str, base); // str是字符串,base进制.
// 进制输入
in.nextBigInteger(2); // 将一个大数以2进制形式读入
BigInteger ans;
String str;
str = ans.toString(2);// 将大数转换成2进制表示的字符串

6. 字符串

String str = "abcdefg";
st.charAt(i); // st.charAt(i)就相当于st[i].
char [] ch;
ch = st.toCharArray(); // 字符串转换为字符数组,java中字符串String是不可以修改的,要修改只能转换为字符数组.
st.startsWith("a"); // 如果字符串以"a"开头.
str.substring(0, 4); // 子串 第2个参数位置上的字符不包括进来,总是有 b-a个字符
BigInteger ans;
String str = ans.toString(); // 转为字符串
BigDecimal tmp;
String str = tmp.toPlainString();// 转换为无格式字符串,比如 1e3 转换为1000
String ors;
ors = in.next();
// 小数点后所有数
str = ors.substring(ors.indexOf(".") + 1, ors.length());
if(str.contains(".")) // 包含

7. 排序

//重写cmp接口
Comparator<person> cmp = new Comparator<person>() {
	public int compare(person o1, person o2) {
		return o1.grade-o2.grade;
	}
};
Arrays.sort(a, 0, n, cmp);//这里还要加上cmp
import java.util.*;  
 
class node implements Comparable<node>  
{  
    int x,y;  
    public node(int x ,int y) {
        this.x = x;
        this.y = y;
    }
    //方法二
//    public int compareTo(node d)  
//    {    
//    	return (x==d.x)?(y-d.y):(x-d.x); // 从小到大
////        if(this.x-a.x != 0)   
////        	return this.x-a.x;  //按x升序排序
////        else return this.y-a.y;  //如果x相同,按y升序排序
//    }  
}  
public class Main
{    
    public static void main(String args[])  
    {  
        node[] d = {new node(0,1), new node(2,3), new node(-1,-2)};
        Comparator<node> cmp = new Comparator<node>() {
			public int compare(node o1, node o2) {
				return o1.x-o2.x;
			}
		};
        Arrays.sort(d, 0, 3, cmp); //排n个数,Arrays.sort(d)则默认排全部  
        for(int i=0; i<3; i++)  
            System.out.println(d[i].x+" "+d[i].y); 
    }  
}

8. 优先队列

// leetcode 1046. Last Stone Weight
// Queue<Integer> q = new PriorityQueue<Integer>(cmp); // 定义
// add、offer 添加
// poll = peek + remove
// size 队列元素个数
// clear 清空
// contains 包含
// toArray 转数组
class Solution {
    public int lastStoneWeight(int[] stones) {
        Comparator<Integer> cmp = new Comparator<Integer>() {
			public int compare(Integer i1, Integer i2) {
				return i2-i1; // 从大到小
			}
		};
        Queue<Integer> q = new PriorityQueue<Integer>(cmp); // 定义
        for(int i:stones) {
            q.add(i); // add 添加 
        }
        while(q.size() > 1) {
            int x = q.poll(); // poll 取出队首元素,并删除队首 
            // peek 单纯取出队首 // remove 单纯删除队首元素
            int y = q.poll();
            int tmp = Math.abs(y-x);
            if(tmp != 0) {
                q.add(tmp);
            }
        }
        int ans = 0;
        if(!q.isEmpty()) {
            ans = q.poll();
        }
        return ans;
    }
}

9. 二分

import java.util.*;  
 
class node
{  
    int x,y;  
    public node(int x ,int y) {
        this.x = x;
        this.y = y;
    }
}  
public class Main
{    
    public static void main(String args[])  
    {  
        node[] d = {new node(0,1), new node(2,3), new node(-1,-2)};
        Comparator<node> cmp = new Comparator<node>() {
			public int compare(node o1, node o2) {
				return (o1.x == o2.x)?(o1.y - o1.y):(o1.x-o2.x);
			}
		};
		Arrays.sort(d, cmp);
		int index = Arrays.binarySearch(d,new node(3, 3), cmp);
		System.out.println(index);  // 负数:没找到,绝对值是插入位置,即第一个大于它的位置
    }  
}

10. Map

// leetcode 3. Longest Substring Without Repeating Characters
public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length(), ans = 0;
        Map<Character, Integer> map = new HashMap<>(); // current index of character
        // try to extend the range [i, j]
        for (int j = 0, i = 0; j < n; j++) {
            if (map.containsKey(s.charAt(j))) { // containsKey
                i = Math.max(map.get(s.charAt(j)), i); // get
            }
            ans = Math.max(ans, j - i + 1);
            map.put(s.charAt(j), j + 1); // put
        }
        return ans;
    }
}

11. Set

// leetcode 3. Longest Substring Without Repeating Characters
public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length();
        int ans = 0;
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j <= n; j++)
                if (allUnique(s, i, j)) ans = Math.max(ans, j - i);
        return ans;
    }

    public boolean allUnique(String s, int start, int end) {
        Set<Character> set = new HashSet<>(); // 定义
        for (int i = start; i < end; i++) {
            Character ch = s.charAt(i);
            if (set.contains(ch)) return false; // contains
            set.add(ch); // add
        }
        return true;
    }
}
发布了76 篇原创文章 · 获赞 20 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Krone_/article/details/83514755