Java算法比賽常用方法實例總結(jié)
1. 開方:Math.sqrt(x);
2. x的a方:Math.pow(x,a);
3. 絕對值:Math.abs(x);
4. BigInteger:大數(shù)(加,減,乘,除,取余)
c.add(d) ; c.subtract(d);c.multiply(d);c.divide(d);c.mod(d)
5. 判斷回文:
public static void main(String[] args) {
String list="12321";
StringBuilder str=new StringBuilder(list);
if (str.reverse().toString().equals(list)){
System.out.println(true);
}
}6. HashMap
(key,value)put,get,remove,獲取key使用keySet()

7.HashSet:去重

8.字符串相關(guān)



6.字符串轉(zhuǎn)化成字符數(shù)組

7.字符數(shù)組轉(zhuǎn)發(fā)成字符串 String helloString = new String(helloArray);
8.忽略字符串大小寫的比較方法,這就是 equalsIgnoreCase( )方法。同樣返回boolean值。
9.去除首尾空白字符串 trim()
10.包含子字符串contains
補充:hashMap按值排序
輸入
第一行 輸入n個字符串
其余n行 :n個字符串
輸出每個字符串從大到小出現(xiàn)次數(shù)
格式 出現(xiàn)次數(shù) - 字符串
eg:
5
2 -1 -1 22
1 11 66 0
1 28 74 35
3 35 28 7
2 -1 -1 22
實現(xiàn)代碼
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Map<String, Integer>map=new HashMap<>();
Scanner sca=new Scanner(System.in);
int n=sca.nextInt();
sca.nextLine();
for(int i=0;i<n;i++) {
String str=sca.nextLine();
int num=map.getOrDefault(str, 0)+1;
map.put(str, num);
}
List<Map.Entry<String, Integer>>list=new ArrayList<>();
for(Map.Entry<String, Integer>mv:map.entrySet()) {
list.add(mv);
}
Collections.sort(list,new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
// TODO Auto-generated method stub
return o2.getValue()-o1.getValue();
}
});
System.out.println();
for(int i=0;i<list.size();i++) {
Map.Entry<String, Integer> mvEntry=list.get(i);
String key=mvEntry.getKey();
Integer value=mvEntry.getValue();
System.out.println(value +" - "+ key);
}
}
}輸出
2 - 2 -1 -1 22
1 - 1 28 74 35
1 - 1 11 66 0
1 - 3 35 28 7
總結(jié)
到此這篇關(guān)于Java算法比賽常用方法的文章就介紹到這了,更多相關(guān)Java算法比賽方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于Spring Boot使用JpaRepository刪除數(shù)據(jù)時的注意事項

