[Force Button Brush Questions] (1) Array Topic

Array Topic

1. Array introduction

An array is a data structure whose storage space is contiguous. Therefore, the array is more complicated to delete elements, and it is very convenient to query the elements.

And the logic of deletion is essentially an override.

2. Force button question type

2.1, 704 binary search

Topic description:

Given an n-element sorted (ascending) integer array nums and a target value target, write a function to search for target in nums and return the subscript if the target value exists, and -1 otherwise.

Input: nums = [-1,0,3,5,9,12], target = 9

Output: 4

Explanation: 9 appears in nums with subscript 4

Link: https://leetcode-cn.com/problems/binary-search

Applies to ordered non-repeating arrays. Determines when to exit the while loop.

class Solution {
    
    
    public int search(int[] nums, int target) {
    
         
        int left = 0;
        int right = nums.length -1;
        // 优化,没有的情况下提前结束
        if (target < nums[0] || target > nums[nums.length - 1]) {
    
    
            return -1;
        }
        while(left<=right){
    
    
            // int mid = (right+left)/2;
            // 防止加法溢出,做减法变换
            int mid = left+((right-left)>>1);
            // 第一个判断也会提前结束
            if(nums[mid]==target){
    
    
                return mid;
            }
            else if(nums[mid]<target){
    
    
                left = mid + 1;
            }
            else if(nums[mid]>target){
    
    
                right = mid - 1;
            }
        }
        return -1;
    }
}

2.2, 27 remove elements

Given an array numsand a value val, you need to in- place remove all elements valwhose , and return the new length of the removed array.

Don't use the extra array space, you must only use the O(1)extra space and modify the input array in place .

The order of elements can be changed. You don't need to consider elements in the array beyond the new length.

Input: nums = [3,2,2,3], val = 3

Output: 2, nums = [2,2]

Explanation: The function should return a new length of 2, and the first two elements in nums are both 2. You don't need to consider elements in the array beyond the new length. For example, the new length returned by the function is 2, and nums = [2,2,3,3] or nums = [2,2,0,0] would also be considered the correct answer.
Link: https://leetcode-cn.com/problems/remove-element

At the beginning, I thought it would be enough to output count directly, but the output of the question requires a non-val array, but at the same time, as long as the value of the first count bit is count.

class Solution {
    
    
    public int removeElement(int[] nums, int val) {
    
    
        int count = 0; //快指针
        for(int num : nums){
    
     //慢指针
            if(num!=val){
    
    
                nums[count] = num; //用当前值覆盖掉前面的位置
                count++; //count这里也是新一套数组的下标
            }
        }
        return count;
    }
}

The final new array should be [2, 2, 2, 3]. This method is called the double pointer method , also known as the fast and slow pointer method. The slow pointer is the original for loop index, and the fast pointer is a set of indexes maintained by the new array itself. It is fast because it is maintained by itself and does not have to be moved length times.

Further, it can be seen that the work of two for loops is completed under one for loop through a fast pointer and a slow pointer.

Can that be used in the traversal problem of double for loops? No, because traversal is one that remains stationary first, and the other that moves; for can iteratively increase conditionally, and simple auto-increment has no control conditions.

2.3, 977 squares of ordered arrays

Given an array nums of integers sorted in non-decreasing order, return a new array of squares of each number, requested to also be sorted in non-decreasing order.

Example:

Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Explanation: After squaring, the array becomes [16,1,0,9,100]
After sorting, the array becomes is [0,1,9,16,100]

Link: https://leetcode-cn.com/problems/squares-of-a-sorted-array

Method 1: Square first, then sort

class Solution {
    
    
    public int[] sortedSquares(int[] nums) {
    
    
        for(int m = 0;m<nums.length;m++){
    
    
            nums[m] = nums[m]*nums[m];
        }
        // 冒泡排序
        for(int i =0;i<nums.length-1;i++){
    
    
            for(int j = 0;j<nums.length-1-i;j++){
    
    
                if(nums[j]>nums[j+1]){
    
    
                    nums[j] = nums[j+1] ^ nums[j];
                    nums[j+1] = nums[j+1] ^ nums[j];
                    nums[j] = nums[j+1] ^ nums[j];
                }
            }
        }
        return nums;
    }
}

Method 2: Use double pointers

class Solution {
    
    
    public int[] sortedSquares(int[] nums) {
    
    
        int size = nums.length;
        int[] arr = new int[size];
        int i=0;
        int j=size-1;
        int k=size-1;
        // 双指针法,一个动,一个不动
        while(i<=j){
    
     //结束条件
            if(nums[i]*nums[i]>nums[j]*nums[j]){
    
    
            arr[k--] =  nums[i]*nums[i];
            i++;
        } else{
    
    
            arr[k--] =  nums[j]*nums[j];
            j--;
            }
        }
        return arr;
    }
}

2.4, 209 The smallest subarray of length

Given an array of n positive integers and a positive integer target .

Find the smallest contiguous subarray [numsl, numsl+1, …, numsr-1, numsr] in the array that satisfies its sum ≥ target and return its length. Returns 0 if no matching subarray exists.

Example 1:

输入:target = 7, nums = [2,3,1,2,4,3]
输出:2
解释:子数组 [4,3] 是该条件下的长度最小的子数组。

Link: https://leetcode-cn.com/problems/minimum-size-subarray-sum

Method 1: Brute-force cracking:

class Solution {
    
    
    public int minSubArrayLen(int target, int[] nums) {
    
    
        int sum = 0;
        int subLength = 0;
        int result =  nums.length+1;
        for(int i=0;i<nums.length;i++){
    
    
            sum = 0; //每次需要清零
            for(int j = i;j<nums.length;j++){
    
    
                sum += nums[j];
                if(sum>=target){
    
    
                    subLength = j - i +1;
                    result = result < subLength ? result:subLength; //取最小的sublength
                    break;
                }
            }
        }
        return result==(nums.length+1) ? 0 : result; //返回结果
    }
}

Method 2: Sliding window optimization

The sliding window is also a double pointer, but the difference is that the two pointers remain fixed. When the value exceeds the bounds, the previous one is always removed, and a new element is added from the back. Time complexity changed from O ( n 2 ) to O ( n ) O(n^2) to O(n)O ( n2 )becomesO(n).

class Solution {
    
    
    public int minSubArrayLen(int target, int[] nums) {
    
    
        int sum = 0;
        int subLength = 0;
        int result =  nums.length+1;
        int i = 0;
        for(int j = 0;j<nums.length;j++){
    
    
            sum += nums[j];
            while(sum>=target){
    
    
                subLength = j - i +1;
                result = result < subLength ? result:subLength; //取最小的sublength
                sum -= nums[i++]; //滑动窗口,去掉前面一个,从后面一个算起
            }
        }
        return result==(nums.length+1) ? 0 : result; //返回结果
    }
}

2.5, 59 spiral matrix ||

Given a positive integer n, generate 1a squaren2 matrix containing to all elements with the elements spirally arranged in clockwise order .n x nmatrix

img

输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]

Link: https://leetcode-cn.com/problems/spiral-matrix-ii/

Simulation process: Pay attention to the way the analysis matrix is ​​formed.

class Solution {
    
    
   public int[][] generateMatrix(int n) {
    
    
        int[][] res = new int[n][n];
        int up = 0, down = n - 1, left = 0, right = n - 1, index = 1;
        while(index <= n * n){
    
    
            for(int i = left; i <= right; i++){
    
    
                // up不动,left指针移位
                res[up][i] = index++;
            }
            //下次left起始移位往下靠了一位
            up++; 
            for(int i = up; i <= down; i++){
    
    
                // right不动,up指针移位
                res[i][right] = index++;
            }
            //下次right起始移位往左靠了一位
            right--; 
            for(int i = right; i >= left; i--){
    
    
                // down不动,right指针移位
                res[down][i] = index++;
            }
            // 下次down起始移位往上靠了一位
            down--;
            for(int i = down; i >= up; i--){
    
    
                // left不动,down指针移位
                res[i][left] = index++;
            }
            // 下次left起始位置往右靠了一位
            left++;
        }
        return res;
    }
}

A version written by myself, the idea is not as clear as above, for reference:

class Solution {
    
    
    public int[][] generateMatrix(int n) {
    
    
        // 生成一维数组
        int [][]arr = new int[n][n];
        int i,j,m = 0;
        // 根据奇偶判断循环次数
        if(n%2==0){
    
    
            m = n/2;
        }else{
    
    
           m = n/2+1;
        }
        int index = 1;
        /**
        每圈循环动作:
        每个条件判断肯定与i有关
        **/ 
        for( i=0;i<m;i++){
    
    
            // 向左填充,起始j=0,终止n-i;从i开始向左移位
            for( j = i;j<n-i;j++){
    
    
                arr[i][j] = index++;
            }
            // 向下填充,起始j=i+1;终止n-i,从n-i-1开始向下移位(第一个已经填充过了所以-1)
            for( j = i+1;j<n-i;j++){
    
    
                arr[j][n-i-1] = index++;
            }
            // 向右填充,起始j=n-i-1-1(上一轮的列标即是当前的行标,因为方针;因为已填充再减去1)
            for(j=n-i-2;j>=i;j--){
    
    
                arr[n-i-1][j] = index++;
            }
            // 向上填充,起始为上一轮的终止行标;终止j>=i+1(上移每次都会少一位)
            for(j=n-i-2;j>=i+1;j--){
    
    
                arr[j][i] = index++;
            }
        }
        return arr;
    }
}

3. Summary

An array is a contiguous data structure, and the same is true for multidimensional arrays. At the same time, the element deletion of the array is more complicated. First, find the element to be deleted, and then copy the subsequent elements to the previous position one by one.

Array-related problems usually involve:

  • Dichotomy Traversal
  • double pointer method
  • sliding window
  • behavioral simulation

Guess you like

Origin blog.csdn.net/qq_40589204/article/details/118229343