1
Abstract: algorithm exercise is to exercise programming thinking and strengthen the programmer's internal strength. Therefore, the content of algorithm skills that will be continuously updated later is referred to as Algorithm Yi Jin Jing.

This article is shared from the HUAWEI cloud community " <java algorithm Yijinjing> Common java-API use ", the original author: breakDraw.

Yi Jin Jing originated from the traditional Chinese medicine guiding technique in ancient my country, which has the effect of strengthening the body and preventing diseases. It has been widely circulated among Buddhists and folk practitioners for a long time. The essence of algorithm exercise is to exercise programming thinking and strengthen the programmer's internal strength. Therefore, the content of algorithm skills that will be continuously updated later is 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 use java as an example here, other languages are similar. Mainly based on leetcode type platforms.

Java array and list conversion

Sometimes the given input is an array, and in the process we want to convert it into a list and use some APIs of the list. But it's not that simple.

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

  • Please convert the string array to list
  • Please convert string list to array
  • Please turn list<Integer> to int[]
  • Please convert int[] to List<Integer>

Just like the following, create your own class and test to see if it can be written in seconds:

public class ListArrayUtil {
    // 请把字符串数组转list
    public List<String> arrToListStr(String[] arr) {
        return null;
    }

    // 请把字符串list转数组
    public String[] listToArrStr(List<String> list) {
        return null;
    }

    // 请把list数组转成int[]
    public List<Integer> arrToListInt (List<Integer> num) {
        return null;
    }

    // 请把int[] 数组转成list
    public List<Integer> arrToListInt (int[] num) {
        return null;
    }
}

Some people may mistakenly think that int[] and Integer[] can be converted automatically, and for arrays, the compiler cannot recognize them and will report an error. Therefore, if it involves the conversion of this basic type of array list, please remember that either use stream immediately, or write directly in the for loop. Don't get stuck in this compilation error and study for a long time.

my answer:

public class ListArrayUtil {
    // 请把字符串数组转list
    public List<String> arrToListStr(String[] arr) {
        return Arrays.asList(arr);
    }

    // 请把字符串list转数组
    public String[] listToArrStr(List<String> list) {
        return list.toArray(new String[list.size()]);
    }

    // 请把list数组转成int[]
    public int[] arrToListInt (List<Integer> list) {
        // 不可以toArray,int[]和Integer[]是不同的
        //return list.toArray(new int[list.size()]);
        return list.stream()
                .mapToInt(Integer::valueOf)
                .toArray();
    }

    // 请把int[] 数组转成list
    public List<Integer> arrToListInt (int[] num) {
        // 不可以asList,因为int[]和Integer[]不同
        // return Arrays.<Integer>asList(num);
        return Arrays
                .stream(num)
                .boxed()
                .collect(Collectors.toList());
    }
}

Initialization of lists and arrays

Initialization is not that simple, especially when it comes to returning List[] as a result. Someone always forgets to initialize each list in the array before it can be used. Please complete the following:

  • Initialize list<Integer> to 5 ones
  • Initialize int[] to 5 ones
  • Initialize a lis[] array containing 5 lists, and the list inside has been initialized

The correct answer is as follows:

public class ListUtil {

    // 初始化list为5个1
    public static List<Integer> fillList() {
        List<Integer> list = Collections.nCopies(5,1);
        System.out.println(list);
        return list;
    }

    // 初始化arr为5个1
    public static int[] fillArr() {
        int[] arr = new int[5];
        Arrays.fill(arr, 1);
        return arr;
    }

    // 返回1个list数组,并且里面的list已经初始化完成
    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 a custom sort 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/problems/ba-shu-zu-pai-cheng-zui-xiao-de-shu-lcof/

map related

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

answer:
Use getOrDefault:
map.getOrDefault(key, new ArrayList<>()).add(xxx)
The result of the picture is quite commonly used over there

Do not repeat put

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

Can be optimized into
map.putIfAbsent(key, value)
Literal meaning: absent means that it does not exist, then when it does not exist, put the value in, if it exists, it will directly return to the original value.

Update the value in the map

For example, add 1 to the value in 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 more complex situation, compute is more useful.

computeIfAbsent(key, (k,v)->f(k,v)) This labmda formula is calculated 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 only be updated if it exists, and will not be updated if it does not exist.

Common queue usage

  • Normal queue:
  • PriorityQueue priorityQueue:
    It can be guaranteed that the team will always be in accordance with the largest or smallest element you set.
    Very useful.

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

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

So it's easy to understand
Big top heap: when ab<0, exchange is required, that is, the father is younger than the son, so exchange is required
Xiaodingdui: ab>0, it needs to be exchanged, that is, if the father is older than the son, it must be exchanged so that the father is Xiaoding.

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

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 the dichotomy, use this method:

  • Find the element closest to x and less than or equal to x in a list
    Use treeMap to place data
    floorKey(key) can find the largest key less than or equal to the given key
    If there is no such key, null is returned.

ceilingKey(key) find the smallest key greater than or equal to the given key
Returns null if it doesn't exist

memory:

The ceiling is rounded up, that is, to find the upper side of the key. Ceiling means ceiling, so it is understood as looking upward.

Floor down intake, that is, find the bottom of the key. There is the meaning of sinking into the water, 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/problems/previous-permutation-with-one-swap/submissions/

Click to follow and learn about Huawei Cloud's fresh technology for the first time~


华为云开发者联盟
1.4k 声望1.8k 粉丝

生于云,长于云,让开发者成为决定性力量