Array [double pointer], two-dimensional array [matrix]

concept

  • Collection: A collection of elements that are stored in no order and regardless of type
  • List: formed on the basis of a set, the elements are variable in length and stored in order. Arrays, linked lists, stacks, and queues are all special lists
  • Arrays: On the basis of lists, java: restricts elements to the same type. At the same time, the memory space addresses between its elements are continuous, so we can use the address of the first element to access the value of the element at any position in the array. This concept is: index.
    insert image description here

Features of arrays

Find and modify elements quickly

  • As shown in the previous section, with the help of the index, we just need to do a simple addition to get the address.
//假设ans数组的第一个元素ans[0]内存地址为0x110
//该数组是int型数组,则每个元素占4个字节
int[] ans = new int[10];
//则ans[3]的地址为:0x122

Inserting elements is slow

  • Since the elements in the array are stored in a set of contiguous address spaces, if we want to insert element C between element A and element B, we need to move element B and its subsequent elements to the right by 1 space to make room for element C. out of space.

removing elements is slow

  • If the element we delete is not the last element in the array, then we need to cover all elements after the element over the previous element, so that the memory addresses corresponding to the elements are consecutive.

double pointer

Although the data structure of the array is very simple, there are many algorithms related to the array, such as various sorting algorithms. This article only analyzes double pointers.
Using double pointers can solve a small number of problems with arrays, such as inverting arrays, binary search, etc.

  • double pointer template
int left,right;//用来存储数组索引,代表左右指针(没错,模板就两个变量)

Double pointer initialization

  1. The left pointer is set to 0 to point to the first element, the right pointer is set to the array length, or the array length -1 points to the last element. The two pointers approach the middle according to the algorithm.

insert image description here

  1. The left pointer is set to 0 and points to the first element. The right pointer is set to 1, points to the second element, and moves in the same direction. This type of double pointer is used for the right pointer to move more times or opportunities than the left pointer.

insert image description here

  1. The left and right pointers are both set to 0, pointing to the first element, moving in the same direction, but the right pointer (fast pointer) moves more steps each time than the left pointer (slow pointer). This type of double pointer is called a fast and slow pointer .

insert image description here
The above three are commonly used double pointer types, there are many other ways to initialize double pointers, and different double pointers are selected according to different situations.

binary search

Next, use two pointers to implement binary search.

Note that implementing binary search requires the array itself to be an ordered array.

Search caret position from leetcode

  • Given a sorted array and a target value, find the target value in the array and return its index. If the target value does not exist in the array, returns the position where it will be inserted in order.
    Input: nums = [1,3,5,6], target = 5
    Output: 2
class Solution {
    
    
    public int searchInsert(int[] nums, int target) {
    
    
        return erfen(nums,target,0,nums.length);
    }
    //left为左指针,right为右指针
    public int erfen(int[] nums,int target,int left,int right) {
    
    
    	//当左右指针相等或位置互换,结束递归
        if(left >= right) {
    
     return left; }
        //二分查找的核心语句就在于此句,通过左右指针获取区间中心位置
        int mid = (left + right)/2;
        //判断该位置上的值是否目标值
        if(nums[mid] == target) {
    
     
            return mid; 
        }
        else if(nums[mid] < target) {
    
    
	        //若该位置值比目标小,说明我们要找的目标值一定位于区间中心与右指针之间
            return erfen(nums, target, mid+1, right);
        }
        //若该位置值比目标大,说明我们要找的目标值一定位于区间中心与左指针之间
        else {
    
    
            return erfen(nums, target, left, mid);
        } 
    }
}

Two-dimensional array

The arrays before this article are just one-dimensional arrays.

A two-dimensional array means that each element in a one-dimensional array is a one-dimensional array. We can think of one-dimensional arrays as a line, and two-dimensional arrays can be regarded as a matrix, so we can introduce the concept of coordinates.

  • Two-dimensional array int[][] mat = { {1,2,3},{4,5,6},{7,8,9}};
    [ 1 , 2 , 3 ]
    [ 4 , 5 , 6 ]
    [ 7 , 8 , 9 ]
    where element value 5 is at coordinates (1,1).

You are given an image represented by an N × N matrix, where each pixel is 4 bytes in size. Please design an algorithm to rotate an image by 90 degrees. From leetcode rotation matrix
Source image:
[ 1 , 2 , 3 ]
[ 4 , 5 , 6 ]
[ 7 , 8 , 9 ]
After inversion:
[ 7 , 4 , 1 ]
[ 8 , 5 , 2 ]
[ 9 , 6 , 3 ]

class Solution {
    
    
    public void rotate(int[][] matrix) {
    
    
    	//首先上下翻转
        for(int i=0;i<matrix.length/2;i++){
    
    
            int j = matrix.length - 1 -i;
            for(int k=0;k<matrix[0].length;k++){
    
    
                int num = matrix[i][k];
                matrix[i][k] = matrix[j][k];
                matrix[j][k] = num;
            }
        }
//[ 7 , 8 , 9 ]        
//[ 4 , 5 , 6 ]
//[ 1 , 2 , 3 ]
		//沿对角线交换(8和4交换,9和1交换,6和2交换)
        for(int i=0;i<matrix.length-1;i++){
    
    
            for(int j=i+1;j<matrix[0].length;j++){
    
    
                int num = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = num;
            }
        }
    }
}
  • Experience: When solving the two-dimensional array problem, in fact, the theoretical solution is easier to think and understand, but in practice, many problems will appear when you code by hand.
    The most common problem is the subscript out of bounds problem.
    After this problem occurs, we can use an integrated environment such as idea to troubleshoot (not recommended).
    Or we do the derivation from the case ourselves, but derivation from the case is a distracting thing, because there are so many changes in the various variables that you need to remember, so if the derivation of the case does not go well, I suggest that you should immediately Re-organize the idea, and then deduce it, and so on and so forth (theoretical ability and code ability).

  • Supplement: How to store the coordinates as a one-dimensional array, please refer to the supplementary part of the author's queue BFS

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324164280&siteId=291194637