Java algorithm Yi Jin Jing: common Java API tips

Time:2021-12-30

Summary:The essence of algorithm practice also lies in training programming thinking and strengthening the internal force of programmers. Therefore, give yourself the content of algorithm skills that will be continuously updated later, referred to as algorithm Yi Jin Jing.

This article is shared from Huawei cloud community《Common Java API usage of < Java algorithm Yi Jin Jing > >》, original author: breakdraw.

Yi Jin Jing originated from the guidance of traditional Chinese medicine in ancient China. It has the effect of strengthening physique and preventing diseases. It has been widely spread among Buddhists and folk martial arts practitioners for a long time. The essence of algorithm practice also lies in training programming thinking and strengthening the internal force of programmers. Therefore, give yourself the content of algorithm skills that will be continuously updated later, referred to as algorithm Yi Jin Jing.

No matter what language you use to start training algorithms, you always have to master the basics. I only take Java as an example, which is similar to other languages. Mainly leetcode platform.

Java array and list to each other

Sometimes the given input is an array. In the intermediate process, we want to turn it into a list and use some APIs of the list. But it’s not that simple.

Please open your compiler and see if the following questions can be written successfully without a for loop. (it’s also right to use the for loop. If you forget during the exam, choose the method that can be used)

  • Please convert the string array to list
  • Please convert the string list to an array
  • Please transfer list < integer > to int []
  • Please convert int [] to list < integer >

Create your own class and test whether it can be written in seconds as follows:

public class ListArrayUtil {
    //Please convert the string array to list
    public List<String> arrToListStr(String[] arr) {
        return null;
    }

    //Please convert the string list to an array
    public String[] listToArrStr(List<String> list) {
        return null;
    }

    //Please convert the list array to int []
    public List<Integer> arrToListInt (List<Integer> num) {
        return null;
    }

    //Please convert int [] array to list
    public List<Integer> arrToListInt (int[] num) {
        return null;
    }
}

Some people may mistakenly think that int [] and integer [] can be automatically converted. Then, for arrays, the compiler cannot recognize them and will report an error. Therefore, if you involve array list conversion of this base type, rememberEither use stream immediately or write directly in the for loop, don’t get stuck in this compilation error for a long time.

My answer:

public class ListArrayUtil {
    //Please convert the string array to list
    public List<String> arrToListStr(String[] arr) {
        return Arrays.asList(arr);
    }

    //Please convert the string list to an array
    public String[] listToArrStr(List<String> list) {
        return list.toArray(new String[list.size()]);
    }

    //Please convert the list array to int []
    public int[] arrToListInt (List<Integer> list) {
        //No, toArray, int [] and integer [] are different
        //return list.toArray(new int[list.size()]);
        return list.stream()
                .mapToInt(Integer::valueOf)
                .toArray();
    }

    //Please convert int [] array to list
    public List<Integer> arrToListInt (int[] num) {
        //Aslist is not allowed because int [] and integer [] are different
        // return Arrays.<Integer>asList(num);
        return Arrays
                .stream(num)
                .boxed()
                .collect(Collectors.toList());
    }
}

Initialization of list and array

Initialization is not that simple, especially when it comes to returning list [] as a result, some people will always forget to initialize each list in the array before using it. Please complete the following:

  • Initialize list < integer > to 5 1
  • Initialize int [] to 5 1
  • Initialize a LIS [] array containing 5 lists, and the list inside has been initialized

The correct answer is as follows:

public class ListUtil {

    //Initialize the list to 5 1
    public static List<Integer> fillList() {
        List<Integer> list = Collections.nCopies(5,1);
        System.out.println(list);
        return list;
    }

    //Initialize arr to 5 1
    public static int[] fillArr() {
        int[] arr = new int[5];
        Arrays.fill(arr, 1);
        return arr;
    }

    //Returns a list array, and the list inside has been initialized
    public static List[] fillListArray() {
        List[] lists = new List[5];
        IntStream.rangeClosed(0, 4).boxed()
                .forEach(i->lists[i] = new ArrayList());
        return lists;
    }
}

sort

On how to quickly sort lists and arrays, answer the following questions in idea:

  • How do arrays and list sort int [] arrays in reverse order
    Arrays.sort()
    Collections.sort()
  • How to do custom sorting for a new object?
    As follows. Define a comparable
public class Student implements Comparable<Student> {
    private  int stuId;
    private String stuName;
    private int score;
    @Override
    public int compareTo(Student o) {
        return stuId-o.stuId;
    }
}

Reference title:https://leetcode-cn.com/probl…

Map correlation

  • If the value in the map is a list, you must initialize the list every time you put data into the list in a key. How to reduce the initialization code?

answer:
Use getordefault:
map.getOrDefault(key, new ArrayList<>()).add(xxx)
The result is quite common

Do not repeat

if (!map.containsKey(key)) {    
    map.put(key, value);
}

Can be optimized into
map.putIfAbsent(key, value)
Literal meaning: absent means that if it does not exist, it means that when it does not exist, it puts value into it. If it does exist, it directly returns the original value.

Update the value in the map

For example, add 1 to the value in the key each time
There are two ways:

map.put(key, map.getOrDefault(key, 0)+1);
map.compute(key, (k,v)->(v==null?1:v+1));

In a complex situation, compute is useful.

Computeifabsent (key, (k, V) – > F (k, V)) calculates the labmda formula only when the key does not exist. If it exists, it will not be calculated and the old value will be returned directly.

Computeifpresent (key, (k, V) – > F (k, V)) will be updated only if it exists. If it does not exist, it will not be updated.

Common queue usage

  • Normal queue:
  • Priority queue:
    To ensure that the team is always in accordance with the maximum or minimum elements you set.
    Very useful.

Write the internal comparison formula in labma to avoid forgetting how to write the interface
PriorityQueue<int[]> queue = new PriorityQueue<>((a, b) -> a[1] – b[1]);
A [1] – B [1] is a small top pile
If a [1] – B [1] > 0, exchange.

How to remember?
When the heap is updated, it is updated from top to bottom
thatA is the upper point and B is the lower point (son node)
When the return is greater than 0, exchange a and B.

That’s easy to understand
Big top pile: when A-B < 0, it needs to be exchanged, that is, the father is younger than the son, so it needs to be exchanged
Xiaodingdui: if A-B > 0, it needs to be exchanged, that is, the father is older than his son, so he has to be exchanged, so that the father is Xiaoding.

  • Priority queue delay deletion
    When an element in the priority queue will be deleted, but it is not at the top of the heap, delayed deletion is used, and it will not be cleaned up until it reaches the top of the heap.
    Therefore, at this time, the additional quantity realcount is used to count the actual number of queues, and the specific deletion flag bit is used (do not set the deletion flag bit in a way that will interfere with the queue compare method)

Simple binary search

  • Find the element closest to X and greater than or equal to the value of X in a list

If you don’t want to write two points by hand, use this method:

  • Find the element closest to X and less than or equal to X in a list
    Placing data using treemap
    Floorkey (key) can find the maximum key less than or equal to the given key
    If no such key exists, null is returned.

Ceilingkey (key) finds the smallest key greater than or equal to the given key
Null if it does not exist

Memory:

The ceiling is rounded up, which is the upper edge of the key. Ceiling means ceiling, so it is understood as looking up.

Take the floor down, that is to find the bottom of the key. It means to sink underwater, so it is understood as downward.

  • Find the element closest to X and greater than (not equal to) x in the list

Example:https://leetcode-cn.com/probl…

Click focus to learn about Huawei cloud’s new technologies for the first time~