Code Caprice Summary

The records are all knowledge points that I don't know, for my own reference only.

1. Array

theoretical basis

Continuity of two-dimensional array in memory space address: C++ continuous, Java discontinuous
Java defines two-dimensional dynamic array (I can’t always remember): ArrayList<List<Integer>> list = new ArrayList<List<Integer>>( );

insert image description here

dichotomy

Key point: left-closed right-open interval or left-closed right-closed interval. The while loop is a legal interval, and the loop does not include the interval of the previous loop.

  • C++ finds the length of the array: (vector class array)
    • One-dimensional array: arr.size()
    • Two-dimensional array row length: arr.size()
    • Two-dimensional array length: arr[0].size()
  • Java finds the length of an array:
    • One-dimensional array: arr.length Note: without ()
    • Two-dimensional array row length: arr.length
    • Two-dimensional array column length: arr[i].length

remove element

C++ removes array element library functions (do not use library functions directly when writing questions):
erase() Time complexity: o(n)

Double pointer method to remove array elements: https://www.bilibili.com/video/BV12A4y1Z7LP/?vd_source=5c915cf57c18c90b48105ad42b2a7ef9&t=368.0

// 时间复杂度:O(n)
// 空间复杂度:O(1)
class Solution {
    
    
public:
    int removeElement(vector<int>& nums, int val) {
    
    
        int slowIndex = 0;
        for (int fastIndex = 0; fastIndex < nums.size(); fastIndex++) {
    
    
            if (val != nums[fastIndex]) {
    
    
                nums[slowIndex++] = nums[fastIndex];
            }
        }
        return slowIndex;
    }
};

Common functions of arrays:
Array sorting: Arrays.sort(arr, new Comparator(){})
Arrays are converted to strings: Arrays.toString(arr)

Two, linked list

Remove linked list elements

Note: When C++ deletes linked list elements, it needs to manually release the deleted elements: delete()

The deletion method of the head node is different from that of the middle node.

头结点删除方式:head = head->next;
中间节点删除方式:p->next = q->next;

So there are two ways to delete.
Method 1: delete the head node first, and then delete the middle node

class Solution {
    
    
public:
    ListNode* removeElements(ListNode* head, int val) {
    
    
        // 删除头结点
        while (head != NULL && head->val == val) {
    
     // 注意这里不是if
            ListNode* tmp = head;
            head = head->next;
            delete tmp;
        }

        // 删除非头结点
        ListNode* cur = head;
        while (cur != NULL && cur->next!= NULL) {
    
    
            if (cur->next->val == val) {
    
    
                ListNode* tmp = cur->next;
                cur->next = cur->next->next;
                delete tmp;
            } else {
    
    
                cur = cur->next;
            }
        }
        return head;
    }
};

Method 2: Add an additional head node whose value is empty to point to the current head node, and unify the deletion methods of the head node and the intermediate node.

class Solution {
    
    
public:
    ListNode* removeElements(ListNode* head, int val) {
    
    
        ListNode* dummyHead = new ListNode(0); // 设置一个虚拟头结点
        dummyHead->next = head; // 将虚拟头结点指向head,这样方面后面做删除操作
        ListNode* cur = dummyHead;
        while (cur->next != NULL) {
    
    
            if(cur->next->val == val) {
    
    
                ListNode* tmp = cur->next;
                cur->next = cur->next->next;
                delete tmp;
            } else {
    
    
                cur = cur->next;
            }
        }
        head = dummyHead->next;
        delete dummyHead;
        return head;
    }
};

Java linked list

Create a node structure

public class ListNode<E> {
    
    
    public E val;
    public ListNode next;
    ListNode(E x)
    {
    
    
        this.val = x;
        this.next = null;
    }
}

linked list operation

package Link;

import java.util.LinkedList;

public class MyLinkedList<E> {
    
    
    //头结点
    public ListNode<E> head = null;

    //头插法插入新节点
    public void addFirst(E data){
    
    
        ListNode<E> node = new ListNode<>(data);
        if(head==null){
    
    
            head = node;
        }else{
    
    
            node.next = head;
            head = node;
        }
    }

    //尾插法插入新节点
    public void addLast(E data){
    
    
        ListNode<E> node = new ListNode<>(data);
        if(head==null){
    
    
            head = node;
        }else{
    
    
            ListNode<E> p = head;
            while(p.next!=null){
    
    
                p = p.next;
            }
            p.next = node;
        }
    }

    //任意位置插入新节点
    public void addAny(E data, int num){
    
    
        //判断num范围
        if(num<0||num>this.size()){
    
    
            //Java异常还没学,学完了修改
            System.out.println("异常,插入索引错误");
        }else if(num==0){
    
    
            ListNode<E> q = new ListNode<>(data);
            q.next = head;
            head = q;
        }else{
    
    
            ListNode<E> q = new ListNode<>(data);
            ListNode<E> p = head;
            while(num--!=1){
    
    
                p = p.next;
            }
            q.next = p.next;
            p.next = q;
        }
    }

    //打印链表
    public void display(){
    
    
        //链表空
        if(head==null){
    
    
            System.out.println("链表为空");
        }
        ListNode<E> p = head;
        while(p!=null){
    
    
            System.out.println(p.val);
            p = p.next;
        }
    }

    //判断节点是否存在
    public boolean isInstance(E data){
    
    
        ListNode<E> p = head;
        while(p!=null){
    
    
            if(p.val==data){
    
    
                return true;
            }
            p = p.next;
        }
        return false;
    }

    //查找节点,返回下标
    public int find(E data){
    
    
        if(this.isInstance(data)){
    
    
            ListNode<E> p = head;
            int count = 0;
            while(p!=null){
    
    
                if(p.val==data){
    
    
                    return count;
                }
                count++;
                p = p.next;
            }
        }
        return -1;
    }

    //删除第一个关键字为data的链表节点并返回元素
    public void remove(E data){
    
    
        ListNode<E> p = head;
        //头结点需特判
        if(head!=null&&head.val==data){
    
    
            head = head.next;
            return;
        }
        while(p!=null&&p.next!=null){
    
    
            if(p.next.val==data){
    
    
                p.next = p.next.next;
                return;
            }
            p = p.next;
        }
    }

    //删除所有关键字为key的节点
    public void removeAll(E data){
    
    
        ListNode<E> dummyHead = new ListNode<>(data);
        dummyHead.next = head;
        ListNode<E> p = dummyHead;
        while(p.next!=null){
    
    
            if(p.next.val==data){
    
    
                p.next = p.next.next;
            }else{
    
    
                p = p.next;
            }
        }
        head = dummyHead.next;
    }

    //删除指定位置节点
    public E removeAt(int num){
    
    

        //判断num范围
        if(num<0||num>this.size()-1){
    
    
            System.out.println("索引异常");
            return null;
        }else if(num==0){
    
    
            ListNode<E> q = head;
            head = head.next;
            return q.val;
        }else {
    
    
            ListNode<E> p = head;
            while (num-- != 1) {
    
    
                p = p.next;
            }
            ListNode<E> q = p.next;
            p.next = p.next.next;
            return q.val;
        }
    }

    //获取指定位置节点元素
    public E get(int num){
    
    
        if(num<0||num>this.size()-1){
    
    
            System.out.println("索引异常");
            return null;
        }else {
    
    
            ListNode<E> p = head;
            while (num-- != 0) {
    
    
                p = p.next;
            }
            return p.val;
        }
    }

    //链表长度
    public int size(){
    
    
        int count = 0;
        ListNode p = head;
        while(p!=null){
    
    
            p = p.next;
            count++;
        }
        return count;
    }

    //清空链表
    public void clear(){
    
    
        //链表本身为空
        head = null;
    }
}

test

package Link;
import java.util.LinkedList;

public class main {
    
    
    public static void main(String[] args) {
    
    
        MyLinkedList<Integer> ll = new MyLinkedList<>();
//        ll.display();
        ll.addLast(0);
        ll.addLast(1);
        ll.addLast(2);
//        ll.display();
        System.out.println(ll.isInstance(100));
        ll.addAny(100, 3);
        System.out.println(ll.isInstance(100));
        ll.display();
        System.out.println("size:"+ll.size());
        System.out.println(ll.find(101));
        System.out.println("-------------------");
        ll.remove(100);
        ll.remove(0);
        ll.display();
        System.out.println("-----------------");
        ll.addLast(0);
        ll.addLast(0);
        ll.addLast(0);
        ll.addLast(0);
        ll.addLast(1);
        ll.display();
        System.out.println("-----------------");
        ll.removeAll(100);
        ll.display();
        System.out.println("-----------------");
        System.out.println("删除的是:"+ll.removeAt(5));
        ll.display();
        System.out.println("-----------------");
        System.out.println(ll.get(0));
        System.out.println("-----------------");
        ll.clear();
        ll.display();
    }

}

3. Hash Table

The premise of using the hash method: whether the element has appeared
Java Notes:

  • The default initialization of the array has a value, not a random number, it is 0
  • Get the length of the array: arr.length
  • Get the string length: str.lenrth()
  • True/false in Java cannot be represented by 1/0. For example, while(1) cannot be written like this, and an error will be reported.
  • Convert Java character array to string: String.valueOf()

4. String

Java

Java strings cannot be modified in place, you can recreate a StringBuilder, StringBuilder can be modified

  • StringBuilder common functions:

sb.append("aaa") Add string
sb.reverse() String reverse
sb.toString() Convert StringBuilder type to String type
sb.charAt(i) Return the character at position i
sb.setCharAt(i , u) Set the character at the i-th position to u

//字符转换为字符串
String str = String.valueOf(Char);
//字符串转换为字符数组
char[] c = s.toCharArray();
//字符数组转换为字符串

  • Splitting a string: substring()
String s = "abcde";
String str = s.substring(0,2);//左闭右开,此时str的值为ab

C++

Unlike Java, C++ strings can use the array index to obtain characters in the string, and can also modify the characters in the string
Expand the size of the string: s.resize(k) k represents the length of the string

Five, KMP algorithm

The KMP algorithm is really too big! Xiaobai, who is new to this concept, really can’t understand it no matter how hard he listens. He feels that there are many details in the video that are not clearly explained. Watch this: https://www.cnblogs.com/dusf/p/kmp.html

Six, stack and queue

Java stack:

  • Reference: https://www.jianshu.com/p/01192de8c21a
  • The stack inherits from Vector, and both vector and ArrayList inherit from List.
  • Guide package: import java.util.Stack;
  • Create an object: Stack<> st = new Stack<>();
  • Commonly used functions: push(); pop(); isEmpty(); peek(); (peek is to obtain the value of the top element of the stack, and the element does not come out of the stack)
  • Note: Java's stack inherits from Vector, and there is no restriction on insertion and deletion, which destroys the encapsulation structure of the stack (refer to https://zhuanlan.zhihu.com/p/164795238 ).

java queue

  • Reference: https://www.jianshu.com/p/7a86c56c632b
  • Guide package: import java.util.Queue;
  • Define the queue: LinkedList<String> queue;
  • Implement queue: queue = new LinkedList<String>();
  • Common methods:
    • offer()/add(); Add an element and return true if the addition is successful
    • poll()/remove(); delete the element at the head of the queue and return a value, and return null if the deletion fails
    • peek(); returns the element at the head of the queue
    • size(); returns the number of queue elements
    • isEmpty(); Determine whether it is empty

Java double-ended queue (doubtful)

Java priority queue

The priority queue will sort the elements in the queue and leave the queue according to a certain priority order. (The principle is not carefully read, you can look at the source code)

  • Reference: https://www.cnblogs.com/CarpenterLee/p/5488070.html
  • Package: import java.util.PriorityQueue;
  • 定义:PriorityQueue<String> q = new PriorityQueue<String>();
  • Common method: same as general queue
  • Sorting rewriting rules: I searched a bunch but couldn't find it... probably the same as C++'s sort. If it returns a positive number, o1 should replace o2 as the top of the heap; if it returns a negative number, the opposite is true. Guessing through the code is not necessarily correct

Knowledge involved in the topic:

Java integer and string conversions:

//整数转换为字符串:
String a = " ";  
int b = Integer.parseInt(a);
//字符串转换为整数:
int b = 0;
String a = STring.valueOf(b);

Seven, binary tree

  • Java flips ArrayList: Collections.reverse(list);
    no return value, flips the list in place

  • Java sorting function:
    sorting arrays: Arrays.sort(arr);
    sorting lists: use the sorting function that comes with the list
    ArrayList<Integer> list = new ArrayList<>();
    list.sort();

  • Java's int maximum minimum value:
    maximum value: Integer.MAX_VALUE, 2^31 - 1
    minimum value: Integer.MIN_VALUE

  • An array can be used as the return value of a Java method: int[] func(int a, int b){}
    When calling a function: int[] arr = func(a, b);

  • Common mathematical operations in Math Power
    : Math.pow(a, b) a to the bth power
    Square root: Math.sqrt(double a)

Guess you like

Origin blog.csdn.net/yeeanna/article/details/127290182