Brush Title: skills learned by a new JAVA player

Keywords: Java ascii less jvm

Recently, I was brushing some questions of PAT with algorithm notes, and I was going to take a CSP test with JAVA. I found that there are not many JAVA players in algorithm questions, and there are few online guides for JAVA players, so I sorted out some skills I found and learned these days

If you have any questions about my article or other experience and skills, I would like to get your guidance

This article will be updated and improved with my study. If you are a JAVA player, welcome to exchange

I have also written some questions about JAVA implementation and I think I can learn something. Because PAT has not relaxed the standard for JAVA, there are many questions that cannot be AC over time

I think the algorithm is mainly to practice their own thinking ability, learning methods is the most important, so I didn't spend a lot of time to optimize those JAVA timeout problems, just to pass the test points

Tips for JAVA players 1

  • First, make sure that no package is added and the class name is Main.

  • For operational efficiency, please use

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.IOException;
    BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
    
    • Because PAT system is not friendly to scanner support and runs for a long time.
  • PAT is a single point test, that is, each test point has only one set of input

  • codeup is a multi-point test. When() is used to process input

  • Use the close() method to close the bufferedreader as soon as you have finished using it, otherwise a memory leak may occur (the earlier you close, the better).

  • [important] please don't import any unused packages. If you import java.util.Scanner into PAT and you don't use the scanner, it will return non-zero.

  • Generally, for the problem of 100ms time limit, the basic AC can not, even if the optimization is better. Because a lot of class B problems run for a long time (the damn JVM starts) in 100ms, with a lot of good luck in AC, and all bad luck timeout!

  • For problems over 200ms, if the operation is overtime, please do not use violence to solve them.

  • If it's still overtime, it's recommended to change the language. Official note: choosing the right language is also a skill, so do not give you JAVA to relax the time limit

Code skills

1. Use of JAVA

1. Mathematical processing

  1. Math.round() rounding
    Function rounding, note the return value: int (float), float (double), int/2.0 default double

  2. Add two int s to consider whether it is out of limit. Use Long to accept the out of limit

     If the addition of two int s will exceed the range, Long (Long of C) must be used**
    
  3. JAVA's int range is

  4. String to number, if the initial is empty string, note that the final judgment is empty string, and convert the empty string to zero

    String i = "";
    int s = 10;
    while(s-->0){
    	i+="6";
    }
    // Remember to deal with empty strings
    if(i.equals("")) i = 0;
    res = Long.parseLong(i) + 10;
    
  5. Convert any base string to int

    int i = Integer.parseInt("E8", 16); //Hexadecimal string to int, 16 represents the hexadecimal value before
    
  6. int to hexadecimal string

    String s = Integer.toHexString(i); //int to hexadecimal string
    
  7. Conversion of large number string to scientific notation

    import java.math.BigDecimal;
    BigDecimal s =  new BigDecimal(str);
    
  8. Modifying i in for(char i:charArr) does not affect the data in the array

  9. String.valueOf is required to convert char [] to string

    You can't use. toString(), which translates to an address

  10. A variable that is passed in as a parameter, and if the function calls the modification of the variable itself, it will change itself.

    public static void main(String[] args) {
    	StringBuilder sb = new StringBuilder("Hello World");
    	String st = "Hello World"
    	method(sb, st);
    }
    public static void method(StringBuilder stringBuilder, String s) {
    	// sb has changed because "the method of modifying the variable itself in the function changes itself."
    	stringBuilder.append("!")
    	// st does not change. It does not call methods that can modify itself
    	st += "!";
    }
    

2 IO, character, string processing

  1. String equality = = string. equals
    String = = compare memory address, equal compare value
  2. Scanner's next() is terminated with a space
  3. Use of comparator: compare time strings
    Employee[] emp = new Employee[100];
    Arrays.sort(emp, new EComparator());
    class Employee {
        String name;
        String intime;
    }
    class EComparator implements Comparator<Employee> {
        public int compare(Employee o1, Employee o2) {
        	return o1.intime.compareTo(o2.intime);
        }
    }
    
  4. JAVA has the same output System.out.printf() as C, which can be used to control the output format. The usage is basically the same as C's printf
    System.out.printf("%02d, 2);
    
  5. Double slash is required for string splitting with ".": String.split("\ \.")
  6. 0 is 48 less than ASCII of '0'

3 other uses

  1. Array converted to List: arrays.aslist (array), return value of List type

  2. ArrayList to array: arraylist.toarray (accept array)

  3. Array sorting arrays.sort (array of classes), List sorting collections.sort (List < class >); the sorted class class must implement the compatible interface. Default is ascending

  4. Array equality arrays.euqals (array 1, array 2)

  5. int array default 0, reference type array default null

  6. Iterative Map 2

      //The first type: commonly used, secondary value
      System.out.println("adopt Map.keySet ergodic key and value: ");
      for (String key : map.keySet()) {
       System.out.println("key= "+ key + " and value= " + map.get(key));
      }
      
      //Second kinds
      System.out.println("adopt Map.entrySet Use iterator ergodic key and value: ");
      Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
      while (it.hasNext()) {
       Map.Entry<String, String> entry = it.next();
       System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
      }
      
      //Third: recommendation, especially when the capacity is large
      System.out.println("adopt Map.entrySet ergodic key and value");
      for (Map.Entry<String, String> entry : map.entrySet()) {
       System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
      }
     
      //Fourth kinds
      System.out.println("adopt Map.values()Traverse all value,But not traversal key");
      for (String v : map.values()) {
       System.out.println("value= " + v);
      }
    

2, Simple code

  1. Use while to replace for
    int i = 10;
    while(i-- > 0){}
    
  2. Store every bit of a large number into an array
    // n is the number to be stored num is the number of bits
    while(n != 0){
        ans[num] = n % 10;
        num++;
        n /= 10;
    }
    
  3. Output each number in the array, separated by spaces, no spaces after the last number
    public static void dfs(int n){
        if(n / 10 == 0){
            System.out.printf("%s", n % 10);
            return;
        }
        dfs(n / 10);
        System.out.printf(" %s", n % 10);
    }
    

3, Experience and skill

  1. Convert seconds to hh:MM:ss format

    System.out.println(
        String.format("%02d",maxWaitTime/3600) + ":" + // Time
        String.format("%02d",maxWaitTime%3600/60) + ":" +  // branch
        String.format("%02d",maxWaitTime%100) // second
    );
    
  2. compareTo compare time string (hh:MM:ss)

    Employee[] emp = new Employee[100];
    Arrays.sort(emp);
    class Employee implements Comparable{
        String name;
        String intime;
        @Override
    	public int compareTo(Object o) {
            Employee otherEmplyee = (Employee)o;
            // -1: this property is less than other property
            // 0: equal to
            // 1: greater than
            return o1.intime.compareTo(o2.intime);
        }
    }
    
  3. "110101" is palindrome, "110101" is not palindrome

  4. Carry formula

    // Carry is carry mod is base
    // Additive formula
    c[i] = (a[i] + b[i] + carry) % mod;
    // Carry formula
    carry = (a[i] + b[i] + carry) / mod;
    
  5. If you can't remember the ASCII of the character '0' and want the ASCII of the numeric character, you can '0' + number

  6. Put each bit of two large numbers into two int arrays. When calculating the two numbers through arrays, the two lengths should be unified. The short array should be lengthened, and the lengthened part should be 0
    Different lengths of A and B are used for operation, and zero filling has the following advantages

    • If you need to reverse, you can reverse at the same time, with clear thinking
    • When one is short and the other is long, the rest of the long output will not be forgotten
  7. Large number format (three numbers and a comma: 100000000)

    if(sum >= 1000000)
        System.out.printf("%d,%03d,%03d", sum/1000000, sum%1000000/1000; sum % 1000);
    else if(sum >= 1000)
        System.out.printf("%d,%03d", sum/1000, sum%1000);
    else System.out.printf("%d",sum);
    
  8. Scores are ranked by size, with the same score in the same place

    • Same score and same place: that is, the next score is not continuous: for example, five people rank 1, 2, 4, 5)
    • If the current score is not equal to the previous score, the rank = array subscript + 1, otherwise the rank is the same as the previous one, and the rank is generally placed in the category of the ranked person
  9. Sort by score size, same score by name dictionary

    public int compareTo(Object o) {
       Student othStu = (Student)o;
       if(this.grade < othStu.grade)
           return -1;
       else if(this.grade > othStu.grade)
           return 1;
       else 
           return this.name.compareTo(othStu.name);
       }
       ```
    
  10. Ascending: 12345 ABCD abcde...

  11. Descending sort

    • Arrays. Sort (array, Collections.reverseOrder());
    • Implement Comparator interface Comparator implement descending order: return the value of o1 attribute - o2 attribute
      public int compare(Student o1, Student o2) {
      	return o1.grade - o2.grade;
      };
      
  12. Dichotomy: you can also use dichotomy for an ordered array of time strings

    //Binary search algorithm 
    //Features: fast search speed. Requirement: sequence must be in order
    public static int binarySearch(int[] nums,int key){
        int start=0;
        int end=nums.length-1;
        int mid=-1;
        while(start<=end){
            mid=(start+end)/2;
            if(nums[mid]==key){
                return mid;
            }else if(nums[mid]<key){
                start=mid+1;
            }else if(nums[mid]>key){
                end=mid-1;
            }
        }
        return -1;
    }
    
  13. Calculation time interval: time increases by one second continuously (minute, hour, day...) Until time two

    • The advantage of this method is that other operations can be added in the process of time self increasing

    • For example: calculate the cost of calling from the beginning of time to the second of time. Since the cost standard of each hour is different, you can add the cost of one minute to the total time (PAT class a 1016 Phone Bills (25 points))

      while(!Arrays.equals(time1, time2)) {
          // Time 1 forward one minute;
          time1.min++;
          // Total elapsed time + 1
          totalTime++;
          // Total consumption = one minute price of the current hour (toll)
          spand += toll[time.hour];
      
          // Minutes full 60 carry 1 hour
          if(time1.min == 60) {
              time.min = 0;
              time1.hour++;
          }
      
          // 24 hours and 1 day
          if(time1.hour == 24) {
              time1.hour = 0;
              time1.day++;
          }
      }
      
  14. String to number, if the initial is empty string, note that the final judgment is empty string, and convert the empty string to zero

    String i = "";
    int s = 10;
    while(s-->0){
    	i+="6";
    }
    // Remember to deal with empty strings
    if(i.equals("")) i = 0;
    res = Long.parseLong(i) + 10;
    
  1. Reference: https://blog.csdn.net/youyuge34/article/details/60143721 ↩︎

  2. Refer to: https://blog.csdn.net/kyi ABCD article / details / 52769469 ↩︎

Published 29 original articles, won praise 9, visited 4767
Private letter follow

Posted by mrfruits on Thu, 06 Feb 2020 04:58:28 -0800