java常用算法笔记
1.将一个10进制的c转换为n进制
String s=new BigInteger(c+"",10).toString(n);
2.
求一个解退出
System.exit(0);
3.比较器
Arrays.sort(p,0,m,new Comparator<Point>(){//按照第0列排序
public int compare(Point x,Point y){
return x.a-y.a;
}
});
4.翻转字符串
String t=new StringBuilder(s).reverse().toString();
5.队列
Queue<String> queue = new LinkedList<String>();
6.HashMap遍历
for(String s:dict.keySet()) {
System.out.println(s+" is "+dict.get(s));
}
6.种子填充
void dfs(char[][] a, boolean[][] b, int i, int j,int n)
if(i<0||j<0||i>=n||j>=n)
return;
if(b[i][j]==true||a[i][j]!='@')
return;
else
{
b[i][j]=true;
for(int dr=-1;dr<2;dr++)
{
for(int dc=-1;dc<2;dc++)
{
if(dc==0&&dr==0)continue;
else
{
dfs(a,b,i+dr,j+dc,n);
}
}
}
}
7.星期几
static int whatday(int y, int m, int d)
{
return (m==1||m==2)?
(d+2*(m+12)+3*(m+13)/5+(y-1)+(y-1)/4-(y-1)/100+(y-1)/400)%7
:(d+2*m+3*(m+1)/5+y+y/4-y/100+y/400)%7;
}
8.全排列
private static void dfs(int n, int k) {
if(k==n) {
for(int i=0;i<n;i++) {
System.out.print(a[i]+" ");
}
System.out.println();
}
else {
for(int i=0;i<n;i++) {
int ok=1;
for(int j=0;j<k;j++) {
if(a[j]==i+1) {
ok=0;
}
}
if(ok==1) {
a[k]=i+1;
dfs(n,k+1);
}
}
}
}
9.欧几里得
private static int gcd(int a, int b) {
// TODO Auto-generated method stub
if(b==0)return a;
else {
return gcd(b,a%b);
}
}
10.快速幂
public static long ex(long n,long m) {
long result=1;
long pingfangshu=n;
while(m!=0) {
if((m&1)==1) result*=pingfangshu;
pingfangshu=pingfangshu*pingfangshu;
m>>=1;
}
return result;
}
11.可重集全排列
public static void dfs(int n,int k)
{
if(k==n)
{
for(int i=0;i<n;i++)
System.out.print(a[i]);
System.out.println();
}
else {
for(int i=0;i<n;i++)
{
if(i==0||b[i-1]!=b[i])
{
int c1=0,c2=0;
for(int j=0;j<k;j++)
if(a[j]==b[i])c1++;
for(int j=0;j<n;j++)
if(b[i]==b[j])c2++;
if(c1<c2)
{
a[k]=b[i];
dfs(n,k+1);
}
}
}
}
}
12.过了某天是几月几日
Calendar cd=Calendar.getInstance();
cd.set(y, m-1,d);
cd.add(Calendar.DATE, k);
String format=(new SimpleDateFormat("yyyy-MM-dd")).format(cd.getTime());
13.比较器
Arrays.sort(p,0,m,new Comparator<Point>() {
public int compare(Point x,Point y) {
return x.a-y.a;
}
});
14.Arraylist排序
Collections.sort(list);