Table of Contents 算法竞赛中的JAVA使用笔记输入与输出基本输入输入挂输出控制台输入输出重定向到文件大整数与高精度大整数BigInteger高精度BigDecimal字符串与进制转换字符串基本操作进制转换排序默认排序实现Comparator接口自定义比较器对自定义类的排序用lambda自定义比较器(仅 JAVA8 以上支持)C++STL中部分数据结构在JAVA中对应的用法setmapvectorlistpriority_queuequeuestackdeque
输入与输出
基本输入
Scanner in = new Scanner (System.in);
Scanner in = new Scanner (new BufferedInputStream(System.in));//更快
输入挂
class InputReader {
BufferedReader buf;
StringTokenizer tok;
InputReader() {
buf = new BufferedReader(new InputStreamReader(System.in));
}
boolean hasNext() {
while (tok == null || !tok.hasMoreElements()) {
try {
tok = new StringTokenizer(buf.readLine());
} catch (Exception e) {
return false;
}
}
return true;
}
String next() {
if (hasNext())
return tok.nextToken();
return null;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
BigInteger nextBigInteger() {
return new BigInteger(next());
}
BigDecimal nextBigDecimal() {
return new BigDecimal(next());
}
}
输出
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));//使用缓存加速,比直接使用System.out快
out.println(n);
out.printf("%.2f\n", ans); // 与c语言中printf用法相同
控制台输入输出重定向到文件
FileInputStream fis = new FileInputStream("b.in");
System.setIn(fis);
PrintStream ps = new PrintStream(new FileOutputStream("b.out"));
System.setOut(ps);
大整数与高精度
大整数BigInteger
import java.math.BigInteger;
//主要有以下方法可以使用:
BigInteger add(BigInteger other)
BigInteger subtract(BigInteger other)
BigInteger multiply(BigInteger other)
BigInteger divide(BigInteger other)
BigInteger [] dividedandRemainder(BigInteger other) //数组第一位是商,第二位是余数
BigInteger pow(int other)// other次方
BigInteger mod(BigInteger other)
BigInteger gcd(BigInteger other)
int compareTo(BigInteger other) //负数则小于,0则等于,正数则大于
static BigInteger valueOf(long x)
//输出数字时直接使用 System.out.println(a) 即可
高精度BigDecimal
BigDecimal add(BigDecimal other)
BigDecimal subtract(BigDecimal other)
BigDecimal multiply(BigDecimal other)
BigInteger divide(BigInteger other)
BigDecimal divide(BigDecimal divisor, int scale, BigDecimal.ROUND_HALF_UP)//除数,保留小数位数,保留方法四舍五入
BigDecimal.setScale()方法用于格式化小数点 //setScale(1)表示保留一位小数,默认用四舍五入方式
字符串与进制转换
字符串基本操作
String st = "abcdefg";
char [] ch;
ch = st.toCharArray(); // 字符串转换为字符数组.
for (int i = 0; i < ch.length; i++){
ch[i] += 1; //字符数组可以像C++ 一样操作
}
System.out.println(ch); // 输入为“bcdefgh”.
进制转换
String st = "abcdefg";
char [] ch;
ch = st.toCharArray(); // 字符串转换为字符数组.
for (int i = 0; i < ch.length; i++){
ch[i] += 1; //字符数组可以像C++ 一样操作
}
System.out.println(ch); // 输入为“bcdefgh”.
排序
默认排序
原型:
Arrays.sort(int[] a, int fromIndex, int toIndex)
这种形式是对数组部分排序,也就是对数组a的下标从fromIndex到toIndex-1的元素排序,
注意:下标为toIndex的元素不参与排序哦!
实现Comparator接口自定义比较器
原型:
public static <T> void sort(T[] a,int fromIndex, int toIndex, Comparator<? super T> c)
将整形数组从大到小排序:
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Main2 {
public static void main(String[] args) {
Scanner sca=new Scanner(System.in);
Integer a[]= {23,324,442,2,1};
Arrays.sort(a,new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
Integer c,b;
o1=o1-100;
o2=o2-100;
return o2-o1; //从大到小
//return o1.name.compareTo(o2.name);//小的放前面
}
});
System.out.println(a[4]);
}
}
对自己定义的类,除了上述在sort时制定比较器,还可以类似C++重载<,在定义类的时候实现Comparable接口,然后用方法1的语法进行排序,这样比较简洁,推荐!
C++STL中部分数据结构在JAVA中对应的用法
set
如果要像C++中使用set进行去重,或者查询是否存在这方面的应用,在Java中主要使用HashSet类。
HashSet定义、插入、查询是否存在、删除元素的例子如下:
Set<Integer> s = new HashSet<Integer>();//无序,对应标准C++的unordered_set
s.add(1);
System.out.println(s.contains(1) ? "1 is in set s" : "1 isn't in set s");
//根据key删除元素
m.remove(1);
Set遍历放在下文的Map中演示,因为Java中Map是转化为Set遍历的。
HashSet中元素是无序的(可以理解为顺序不确定),LinkedHashSet是遍历时是按照插入顺序排序的,TreeSet是升序排列的,最接近C++中的set,但是在没有要求元素有序的情况下,Java中一般是使用HashSet的(因为复杂度的优势?我感觉是这样的),这也是我在例子中使用HashSet来对应set的原因(其实我感觉C++中这种情况使用unordered_set会更好啊,可能是因为C++11才出现,比较晚,所有不普及)。下节的map的情况与之类似。如果使用有序的TreeSet,还可以进行如下的查找操作:
TreeSet<Integer> s = new TreeSet<Integer>();
//使用s.add(1);等把1-5都加进去,代码省略
System.out.println(s.ceiling(3)); //>=3的最小的数,输出3
System.out.println(s.floor(3)); //<=3的最大的数,输出3
System.out.println(s.higher(3)); //>3的最小的数,输出4
System.out.println(s.lower(3)); //<3的最大的数,输出2
System.out.println(s.headSet(3)); //<3的数组成的TreeSet,输出[1, 2]
System.out.println(s.tailSet(3)); //>=3的数组成的TreeSet,输出[3, 4, 5]
System.out.println(s.subSet(2,4)); //>=2且<4的数组成的TreeSet,输出[2, 3]
System.out.println(s.subSet(2,false,4,true)); //>2且<=4的数组成的TreeSet,输出[3, 4]
map
如果只需要C++中map的key对value的映射功能,而不关心顺序,Java中一般使用HashMap类,例子如下:
//这里使用的是HashMap,是无序的,对于标准C++的unordered_map
//定义与存取
Map<Integer, Integer> m = new HashMap<Integer, Integer>();
m.put(1, 111);
System.out.println(m.get(1));//如果get一个不存在的key,则返回null,否则返回对应value
//用迭代器遍历
Iterator<Entry<Integer, Integer>> it = m.entrySet().iterator();
while(it.hasNext()){
Entry<Integer, Integer> e = it.next();
System.out.println(e.getKey() + " " + e.getValue());
}
//根据key删除元素
m.remove(1);
//用for-each循环遍历
for(Map.Entry<Integer, Integer> e:m.entrySet()){
System.out.println(e.getKey() + " " + e.getValue());
}
如需有序,与Set类似,有LinkedHashMap、TreeMap等类可以使用。
vector
在Java中,C++的vector对应的是ArrayList类。虽然Java中也有Vector这个类,但它是历史遗留下来的,不建议使用。
ArrayList<Integer> a = new ArrayList<Integer>();//创建一个储存整形的ArrayList
a.add(1); //向其最后添加“1”这个元素
a.add(2); //向其最后添加“2”这个元素
a.add(1, 3); //向其index为1的位置添加“3”这个元素,原来index为1及后续元素向后顺延一位;index以0起始
System.out.println(a); //输出a,结果为[1, 3, 2]
a.remove(1); //删除index为1的元素,注意不是删除值为1的元素
System.out.println(a); //输出a,结果为[1, 2]
a.remove(Integer.valueOf(1)); //删除值为1的元素
System.out.println(a); //输出a,结果为[2]
a.set(0, 1); //将index为0的元素的值改成1
System.out.println(a.get(0)); //取出index为0的元素并输出,结果为1
list
在Java 中,C++的list对于LinkedList类,其基本用法跟ArrayList类似,只是实现上使用链表而不是数组,从而在一些操作的复杂度上有变化,将上文代码的ArrayList改为LinkedList可直接使用,故在此省略。(其实它还实现了C++中queue、deque、stack等的功能,有使用链表实现的这些数据结构的需求的话可以用它。)
priority_queue
在Java中,C++的priority_queue对应的是PriorityQueue类(终于碰到名字像的了?用起来都是坑啊)。示例如下:
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();//定义一个储存整形的优先队列,值
//【小】的在前
pq.offer(1);//将1添加进去,不能用add(),虽然能过编译!!!
pq.offer(3);
pq.offer(2);
//跟C++的不同,你可以遍历它,但是你会发现遍历的结果并不是排序了的……我这里输出1 3 2
for(int t :pq){
System.out.print(t + " ");
}
System.out.println();
System.out.println(pq.peek());//取出第一个值(默认是最【小】的那个),并不删除它,这句代码输出1!!!
System.out.println(pq.poll());//取出第一个值(默认是最【小】的那个),并且删除它,这句代码输出1!!!
System.out.println(pq);//输出剩下的元素,结果是[2, 3],但是并不是排序之后的!!!这只是巧合,不信试试其他值
queue
C++中的queue在Java中可以使用ArrayDeque类,实例如下:
ArrayDeque<Integer> queue = new ArrayDeque<Integer>();
queue.offer(1);//成功返回true,失败返回false,别写成push了,否则……看看下个例子就知道了
queue.offer(2);
queue.offer(3);
System.out.println(queue.peek());//类似于C++中queue的front(),返回第一个元素
while (!queue.isEmpty()) {
System.out.println(queue.pop());//跟C++中的queue()一样可以删除第一个元素,但是会返回它,不像C++中是void的
}
输出为1、1、2、3(我就不换行了)。
stack
C++中的stack在Java中使用ArrayDeque类(你没看错,还是它,我知道Java也有Stack类,那也是历史遗留问题),语法基本相同,下面是例子:
ArrayDeque<Integer> stack = new ArrayDeque<Integer>();
stack.push(1);//跟上面那个代码的不同之处就在这了
stack.push(2);
stack.push(3);
System.out.println(stack.peek());//类似于C++中stack的top(),返回栈顶元素
while(!stack.isEmpty()){
System.out.println(stack.pop());//跟C++中的pop()一样可以弹出栈顶元素,但是会返回它,不像C++中是void的
}
上述代码的输出为3、3、2、1(我就不换行了)。
———————
作者:runnerxin
来源:CSDN
原文:https://blog.csdn.net/runnerxin/article/details/73863235