Algorithm contest Java foundation template (update)

1. Define an object read

static Scanner sc=new Scanner(System.in);

2.String common operations

  • public char charAt (int index): Returns the string of index characters;
  • public int length (): returns the length of the string;
  • public int indexOf (String str): Returns the string str occurs first position;
  • public int indexOf (String str, int fromIndex): Returns a string from fromIndex position str began to appear for the first time;
  • public String substring (int beginIndex): Returns the string from beginIndex beginning to the end of the sub-string;
  • public String substring (int beginIndex, int endIndex): Returns the string from beginIndex start to endsIndex end substring
  • int the compareTo public (STR String) : Comparison of the size of the string , is less than returns negative, it returns a positive number greater than equal returns 0
  • public boolean equals (String str): determines whether or not the same character string
  • char public [] toCharArray ()  : this string into a new character array
  • public String [] split (String regex ): The separation of a string delimiter as specified, it returns an array of strings separated after

 split () method to match the given string to split a regular expression.

Note:. , | And * such as the escape character, have to add \\ .

Note: more than one delimiter can be used | as a hyphen. 

String[] s=str.split(" +");
String[] s=str.split("\\s+");
以一个或多个空格分割
  • Replace String public (CharSequence target, CharSequence replacement)  : The target string matching using the replacement string substitution.
  • String replaceAll (String regex, String replacement ): given this string of all replacement alternative matches the given regular expression substring
String ss=str.replaceAll(" +",",");
String ss=str.replaceAll("\\s+",",");
二者都能把一个或多个空格换成逗号,没有学过正则表达式,具体区别并不懂

 

  • String type can not be changed, you can use if you need to change the StringBuilder

 

 import java.util.*;
public class Main {
    static Scanner sc=new Scanner(System.in);
    public static void main(String[] args) {
        String s="abc def ghi";
        String[] a=s.split(" ");//a[0]=abc a[1]=def a[2]=ghi
        for(int i=0;i<a.length;i++) {
            System.out.print("a["+i+"]="+a[i]+" ");
        }
        System.out.println();
        String str="abcabc";
        char[] ch=str.toCharArray();
        //ch[0]=a ch[1]=b ch[2]=c ch[3]=a ch[4]=b ch[5]=c
        for(int i=0;i<ch.length;i++) {
            System.out.print("ch["+i+"]="+ch[i]+" ");
        }
        System.out.println();
        System.out.println(str.indexOf("b"));//1
        System.out.println(str.indexOf("b",3));//4
        System.out.println(str.substring(3));//abc
        System.out.println(str.substring(3,5));//ab
        System.out.println(str.compareTo("abc"));//3
        System.out.println(str.compareTo("abcabcabc"));//-3
        System.out.println(str.compareTo("abcabc"));//0
        System.out.println(str.equals("abcabc"));//true
        System.out.println(str.equals("abc"));//false
        System.out.println(str.replace("abc","ac"));//acac
        System.out.println(str.toLowerCase());//abcabc
        System.out.println(str.toUpperCase());//ABCABC
    }
}

3.StringBuilder

  • Creating Stringbuilder objects: StringBuilder strB = new StringBuilder ();
  • the append (String STR) / the append (Char C) : connecting string
  • toString () : Returns a string from the same construct or the buffer contents
  • setCharAt (int i, char C) : The i-th unit of code set C (as will be appreciated replacement)
  • INSERT (int offset, String STR) / INSERT (int offset, Char C) : insert a character (string) prior to the specified position
  • delete (int startIndex, int endIndex) string between a delete start position (inclusive) to the end position (free):
import java.util.*;
public class Main {
	static Scanner sc=new Scanner(System.in);
	public static void main(String[] args) {
		//输入abc
		StringBuilder strB=new StringBuilder(sc.next());
		System.out.println(strB.toString());//abc
		//输入def
		strB.append(sc.next());
		System.out.println(strB.toString());//abcdef
		//将第2个代码单元设置为m
		strB.setCharAt(2,'m');
		System.out.println(strB.toString());//abmdef
		//在第4个代码单元之前插入pq
		strB.insert(4,"pq");
		System.out.println(strB.toString());//abmdpqef
		//删除下标[2,5)之间的字符串
		strB.delete(2,5);
		System.out.println(strB.toString());//abqef
	}
}

4.Java uses class structure and implement sorting

Example: output by scores from high to low test scores and the number of candidates on the line, if the candidates more than the same fraction of their output in ascending order of test number.

  • Comparator (c ++ cmp wording similar function)

import java.util.*;
public class Main {
	static Scanner sc=new Scanner(System.in);
	static class student{
		String ID;
		int score;
		public student(String ID,int score) {
			this.ID=ID;
			this.score=score;
		}
	}
	static student[] stu=new student[1005];
	static Comparator cmp=new Comparator<student>() {
		public int compare(student a,student b) {
			if(a.score!=b.score) return b.score-a.score;//分数从高到低
			else return a.ID.compareTo(b.ID);//字典序从小到大
		}
	};
	static int mp[]=new int[15];
	public static void main(String[] args) {
		int N,M,G;
		while(sc.hasNext()) {
			N=sc.nextInt();
			if(N==0) break;
			M=sc.nextInt();
			G=sc.nextInt();
			for(int i=1;i<=M;i++) mp[i]=sc.nextInt();
			int cnt=0;
			for(int i=1;i<=N;i++) {
				String s=sc.next();
				int m=sc.nextInt();
				int sum=0;
				for(int j=1;j<=m;j++) {
					sum+=mp[sc.nextInt()];
				}
				if(sum>=G)
				stu[cnt++]=new student(s,sum);
			}
			Arrays.sort(stu,0,cnt,cmp);
			System.out.println(cnt);
			for(int i=0;i<cnt;i++) {
				System.out.println(stu[i].ID+" "+stu[i].score);
			}
		}
	}
}
  • The Comparable (similar to C ++ overload less than)

import java.util.*;
public class Main {
	static Scanner sc=new Scanner(System.in);
	static class student implements Comparable<student>{
		String ID;
		int score;
		public student(String ID,int score) {
			this.ID=ID;
			this.score=score;
		}
		public int compareTo(student other) {
			if(this.score!=other.score) return other.score-this.score;
			else return (this.ID).compareTo(other.ID);
		}
	}
	static student[] stu=new student[1005];
	static int mp[]=new int[15];
	public static void main(String[] args) {
		int N,M,G;
		while(sc.hasNext()) {
			N=sc.nextInt();
			if(N==0) break;
			M=sc.nextInt();
			G=sc.nextInt();
			for(int i=1;i<=M;i++) mp[i]=sc.nextInt();
			int cnt=0;
			for(int i=1;i<=N;i++) {
				String s=sc.next();
				int m=sc.nextInt();
				int sum=0;
				for(int j=1;j<=m;j++) {
					sum+=mp[sc.nextInt()];
				}
				if(sum>=G)
				stu[cnt++]=new student(s,sum);
			}
			Arrays.sort(stu,0,cnt);
			System.out.println(cnt);
			for(int i=0;i<cnt;i++) {
				System.out.println(stu[i].ID+" "+stu[i].score);
			}
		}
	}
}

5.List

ArrayList: variable-size arrays

  • ArrayList underlying array is implemented, it can be considered a ArrayList can change the size of the array. As more and more elements are added to the ArrayList, its size is dynamically increased.
  • Faster query and modify, add, and delete slower

LinkedList: list

  • LinkedList bottom is achieved through a doubly linked list.
  • Add and delete faster, slower query and modify

Vector: not recommended ( the Vector using synchronized, will inevitably affect the efficiency)

  • Vector and ArrayList, are achieved through the array, but Vector is thread-safe. And compared to ArrayList, which are many ways to ensure the security thread through the synchronization (synchronized) process.
  • There is also a difference between the two is not the same expansion strategy. When List was first created, there will be an initial size, with the increasing elements to the List, the List when the capacity is not enough time to think it will be expansion. Automatic double the increase of the original length of the array of default under Vector, ArrayList growth of the original 50%.

Reference from: https://blog.csdn.net/qq_38218238/article/details/82904926

Common methods:

  • boolean add (Object e): inserted at the end of element
  • void add (int index, Object element ): insert elements in the specified location, after all elements of a previous shift
  • Object set (int index, Object element ): Modify element at the location
  • Object get (int index): Returns the element at the location
  • Object remove (int index): Removes the specified position of the element, the element behind all move forward one

note:

  • Traversing ArrayList with a for loop a little faster
  • LinkedList with traverse a lot faster forEach
import java.util.*;
public class Main {
    static Scanner sc=new Scanner(System.in);
    static List<Integer> arraylist=new ArrayList<Integer>();
    static List<Integer> linkedlist=new LinkedList<Integer>();
    static void query() {//查询
        for(int i=0;i<arraylist.size();i++) {
            System.out.print(arraylist.get(i)+" ");
        }
        System.out.println();
        for(int i=0;i<linkedlist.size();i++) {
            System.out.print(linkedlist.get(i)+" ");
        }
        System.out.println();
//        forEach循环
        for(Integer x:arraylist) {
            System.out.print(x+" ");
        }
        System.out.println();
        for(Integer x:linkedlist) {
            System.out.print(x+" ");
        }
        System.out.println();
    }
    public static void main(String[] args) {
        //增 --在末尾增
        for(int i=0;i<=10;i++) {
            arraylist.add(i);
            linkedlist.add(i);
        }
        query();//0 1 2 3 4 5 6 7 8 9 10
        //删 --把第0个元素删掉
        arraylist.remove(0);
        linkedlist.remove(0);
        query();//1 2 3 4 5 6 7 8 9 10
        //增 --在下标1处增一个元素0
        arraylist.add(1,0);
        linkedlist.add(1,0);
        query();//1 0 2 3 4 5 6 7 8 9 10
        //改 --把下标为1的那个元素改为2
        arraylist.set(1,2);
        linkedlist.set(1,2);
        query();//1 2 2 3 4 5 6 7 8 9 10
    }
}

Two-dimensional ArrayList 

import java.util.*;
public class Main {
	static Scanner sc=new Scanner(System.in);
	static int INF=0x3f3f3f3f;
	static int N=200005;
	static char s[]=new char[N];
	static ArrayList[] pos=new ArrayList[N];
	static void init() {
		for(int i=0;i<26;i++) {
			pos[i]=new ArrayList<Integer>();
		}
	}
	public static void main(String[] args) {
		init();
		int n=sc.nextInt();
		int k=sc.nextInt();
		String string=sc.next();
		s=string.toCharArray();
		for(int i=0;i<n;i++) {
			pos[s[i]-'a'].add(i);
		}
		int ans=INF;
		for(int i=0;i<26;i++) {
			int len=pos[i].size();
			for(int j=0;j+k-1<len;j++) {
				int a=
				ans=Math.min(ans,(int)pos[i].get(j+k-1)-(int)pos[i].get(j)+1);
			}
		}
		if(ans==INF) ans=-1;
		System.out.println(ans);
	}
}

6.Map

definition:

  • TreeMap: static Map<String,Integer> map=new TreeMap<String,Integer>();
  • HashMap:  static Map<String,Integer> map=new HashMap<String,Integer>();

Common operations:

  • V put (K key, V value ): add elements. This fact, there is another function? Replaced

       If the first key is stored, the storage element directly, or null
       if the first key is not present, to replace it with the value of the previous value, the previous value returned

  • void clear (): Removes all of the elements key
  • V remove (Object key): delete the key according to the key element, and returns the value
  • int size (): returns the set of key-value pairs the number of
  • V get (Object key): Gets the value according to the key
  • boolean containsKey (Object key): determining whether the collection contains a specified key
  • boolean containsValue (Object value): determining whether the collection contains a specified value
  • boolean isEmpty (): determines whether the set is empty
  • Set <Map.Entry <K, V >>  entrySet (): returns a set of key-value pairs Set
  • Set keySet (): Gets a collection of all the keys of the collection
  • Collection values (): Get the set of all values in the set
import java.util.*;
public class Main {
    static Scanner sc=new Scanner(System.in);
    static Map<String,Integer> map=new TreeMap<String,Integer>();
//  static Map<String,Integer> map=new HashMap<String,Integer>();
    static void query() {
    	//forEach:通过Map.entrySet遍历key和value(效率高?)
    	for(Map.Entry<String,Integer> entry:map.entrySet()) {
    		System.out.print(entry.getKey()+":"+entry.getValue()+" ");
    	}
    	System.out.println();
    	//forEach:利用 keyset 集合遍历map
    	for(String key:map.keySet()) {
    		System.out.print(key+":"+map.get(key));
    	}
    	System.out.println();
    	//通过Iterator
    }
    public static void main(String[] args) {
    	map.put("ac",1);
    	map.put("wa",0);
    	query();//ac:1 wa:0
    	map.put("ac",666);
    	System.out.println(map.get("ac"));//666
    	query();//ac:666 wa:0
    	System.out.println(map.size());//2
    	map.remove("wa");
    	query();//ac:666 
    	System.out.println(map.size());//1
    }
}

7.Set 

definition:

  • TreeSet: static Set<Integer> set=new TreeSet<Integer>();
  • Hashset:static Set<Integer> set=new HashSet<Integer>();

Common Operations

  • add (): add elements to the collection    
  • clear (): remove all of the elements in the set
  • contains ():  determines whether the collection contains a certain element
  • isEmpty (): determines whether the set is empty
  • remove (): remove a specific object from the collection    
  • size ():  Returns the size of the collection
import java.util.*;
public class Main {
    static Scanner sc=new Scanner(System.in);
    static Set<Integer> set=new TreeSet<Integer>();
//  static Set<Integer> set=new HashSet<Integer>();
    public static void main(String[] args) {
    	set.add(1);
    	set.add(2);
    	set.add(3);
    	System.out.println(set.contains(1));//true
    	System.out.println(set.size());//3
    	set.remove(1);
    	System.out.println(set.size());//2
    	System.out.println(set.contains(1));//false
    	//forEach遍历   输出结果为:2 3
    	for(Integer x:set) {
    		System.out.print(x+" ");
    	}
    }
}

8.Queue 

definition

  • Queue:           static Queue<Integer> q=new LinkedList<Integer>();
  • PriorityQueue:static PriorityQueue<Integer> pq=new PriorityQueue<Integer>();

Common Operations

  • boolean offer (E e): add an element and returns true if the queue is full, it returns false
  • E poll (): remove and return the head of the queue elements ask if the queue is empty, null is returned
  • E peek (): returns the element head of the queue if the queue is empty, null is returned
import java.util.*;
public class Main {
    static Scanner sc=new Scanner(System.in);
    static Queue<Integer> q=new LinkedList<Integer>();
    static PriorityQueue<Integer> pq=new PriorityQueue<Integer>();
    public static void main(String[] args) {
    	/*--Queue--*/
    	//添加
    	q.offer(0);
    	q.offer(3);
    	q.offer(2);
    	q.offer(1);
    	//删除队首并返回队首的值
    	System.out.println(q.poll());//0
    	//返回队首值
    	System.out.println(q.peek());//3
    	//forEach  输出结果为:3 2 1
    	for(Integer x:q) {
    		System.out.print(x+" ");
    	}
    	System.out.println();
    	/*--PriorityQueue--*/
    	//添加
    	pq.offer(0);
    	pq.offer(3);
    	pq.offer(2);
    	pq.offer(1);
    	//删除队首并返回队首的值
    	System.out.println(pq.poll());//0
    	//forEach  输出结果为:1 3 2(用forEach并不会排序输出)
    	for(Integer x:pq) {
    		System.out.print(x+" ");
    	}
    	System.out.println();
    	//返回队首值
    	System.out.println(pq.peek());//1
    	//while循环单个输出    输出结果为:1 2 3
    	while(!pq.isEmpty()) {
    		System.out.print(pq.poll()+" ");
    	}
    }
}

9.Stack

定义:static Stack<Integer> s=new Stack<Integer>();

Common operations:

  • Object peek (): View the object at the top of the stack, without removing it from the stack.
  • Object pop (): removing the top stack object, and the value of this function returns the object.
  • Object push (Object element): the item onto the top of the stack.
import java.util.*;
public class Main {
    static Scanner sc=new Scanner(System.in);
    static Stack<Integer> s=new Stack<Integer>();
    public static void main(String[] args) {
    	s.push(1);
    	s.push(2);
    	s.push(3);
    	System.out.println(s.peek());//3
    	System.out.println(s.pop());//3
    	System.out.println(s.peek());//2
    	s.push(3);
    	//forEach   输出结果:1 2 3(不符合后进先出)
    	for(Integer x:s) {
    		System.out.print(x+" ");
    	}
    	System.out.println();
    	//while     输出结果:3 2 1
    	while(!s.isEmpty()) {
    		System.out.print(s.pop()+" ");
    	}
    }
}

10.int conversion and a String

int x=123;
String sx=String.valueOf(x);
String sy="321";
int y=Integer.parseInt(sy);

11. The full array

import java.util.*;
public class Main {
    static Scanner sc=new Scanner(System.in);
    static char s[]=new char[15];
    static void swap(char s[],int i,int j) {//交换函数
    	char tmp=s[i];
    	s[i]=s[j];
    	s[j]=tmp;
    }
    static void reverse(char s[],int begin,int end) {//逆序函数
    	while(begin<end) {
    		char tmp=s[begin];
    		s[begin]=s[end-1];
    		s[end-1]=tmp;
    		begin++;
    		end--;
    	}
    }
    static void fullsort(char s[],int begin,int end) {//递归实现全排列
    	if(begin==end) {
    		System.out.println(s);
    		return ;
    	}
    	for(int i=begin;i<end;i++) {
    		swap(s,i,begin);
    		fullsort(s,begin+1,end);
    		swap(s,i,begin);
    	}
    }
    static boolean next_permutation(char s[],int begin,int end) {//下一个字典序
    	int i=end-1;
    	while(i>begin&&s[i-1]>=s[i]) i--;
    	if(i==begin) return false;
    	i--;
    	int j=end-1;
    	while(j>i&&s[j]<=s[i]) j--;
    	swap(s,i,j);
    	reverse(s,i+1,end);
    	return true;
    }
    public static void main(String[] args) {
    	String str=sc.next();
    	s=str.toCharArray();
    	Arrays.sort(s);
    	do {
    		System.out.println(s);
    	}while(next_permutation(s,0,s.length));
    }
}

 

Published 428 original articles · won praise 55 · views 50000 +

Guess you like

Origin blog.csdn.net/qq_42936517/article/details/104066185