Algorithm: common array routine 1 --- double pointer, modulo, and ring method

1. Merging of arrays – double pointers [fast and slow pointers]

1. Topic:

You are given two arrays of integers nums1 and nums2 arranged in non-decreasing order, and two integers m and n denoting the number of elements in nums1 and nums2 respectively.
Please merge nums2 into nums1 so that the merged array is also arranged in non-decreasing order.

  • Note: Ultimately, the merged array should not be returned by the function, but stored in the array nums1. To cope with this situation, the initial length of nums1 is m + n, where the first m elements represent elements that should be merged, and the last n elements are 0 and should be ignored. The length of nums2 is n.

2. Analysis features:

两个数组已经被排序, which is equivalent to two ordered queues, non-decreasing, queued from small to large, each time the smallest number is taken from the two queues and put into the result.

3. Code:

   public void merge(int[] nums1, int m, int[] nums2, int n) {
    
    
        int p1 = 0, p2 = 0;
        int[] sorted = new int[m + n];
        int cur;
        while (p1 < m || p2 < n) {
    
    
            if (p1 == m) {
    
    
                cur = nums2[p2++];
            } else if (p2 == n) {
    
    
                cur = nums1[p1++];
            } else if (nums1[p1] < nums2[p2]) {
    
    
                cur = nums1[p1++];
            } else {
    
    
                cur = nums2[p2++];
            }
            sorted[p1 + p2 - 1] = cur;
        }
        for (int i = 0; i != m + n; ++i) {
    
    
            nums1[i] = sorted[i];
        }
    }

4. Complexity analysis:

  • Time complexity: O(m+n)O(m+n)O(m+n). The pointer movement increases monotonically, up to m+nm+nm+n times, so the time complexity is O(m+n)O(m+n)O(m+n).

  • Space complexity: O(m+n)O(m+n)O(m+n). It is necessary to create an intermediate array sorted with a length of m+nm+nm+n.

5. Summary:

This question is relatively simple. You only need to grab the two arrays that increase in order, directly use them as queues, and grab the smallest one. Of course, it is easier to directly store all the elements of one array into the space behind the other array, and then use the encapsulated method to sort, that is, the Arrays.sort() method

2. Deletion of arrays – double pointers [fast and slow pointers]

1. Topic:

Given an array nums and a value val, you need to remove all elements whose value is equal to val in place, and return the new length of the removed array.

Don't use extra array space, you have to use only 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.

2. Analysis features:

  • Question requirement: Remove in situ
  • Remove all elements of val, then 结果数组一定比原数组的长度更短. Request to remove in situ> 我们可以把结果数组直接写在原数组上, and the result array is composed of those elements that are not equal to val, starting from position 0 and going to a certain position as the result array, and the original array needs to be traversed from 0 to the length of the entire array> Use double pointers.
  • The pointer of the result array: [0, left]. The purpose of the result array is to collect the results. It is added step by step by left.
  • Pointer of the original array: [0, right], right <= the length of the original array, right is used to point to whether the current element of the original array is not equal to val and can be collected.

3. Code:

       public int removeElement(int[] nums, int val) {
    
    
        int n = nums.length;
        int left = 0;
        for (int right = 0; right < n; right++) {
    
    
            if (nums[right] != val) {
    
    
                nums[left] = nums[right];
                left++;
            }
        }
        return left;
    }

4. Complexity analysis:

  • Time complexity: O(n)O(n)O(n), where nnn is the length of the sequence. We only need to iterate through the sequence at most twice.

  • Space complexity: O(1)O(1)O(1). We only need constant space to store several variables.

5. Summary:

This question is relatively simple, you just need to catch it. The meaning of the question requires: remove in place, in place ==> the result can only be output to the original array, if removed, the length of the result array will be shorter than the original array. Use left++ to start collection from 0 in the result array, and use the right pointer to traverse the original array from 0 to determine whether the current element can be collected.

==> The purpose is to collect all elements that meet the conditions.

3. Array polling – modulo

1. Topic:

Given an integer array nums, rotate the elements in the array k positions to the right, where k is a non-negative number.

2. Analysis features:

  • 轮转 ==> 取模运算

  • We can use additional arrays to put each element in the correct position. Let n represent the length of the array. We traverse the original array, put the element whose index is i in the original array to the position of the new array whose index is (i+k) mod n, and finally copy the new array to the original array.

3. Code:

    public void rotate(int[] nums, int k) {
    
    
        int n = nums.length;
        int[] newArr = new int[n];
        for (int i = 0; i < n; ++i) {
    
    
            newArr[(i + k) % n] = nums[i];
        }
        System.arraycopy(newArr, 0, nums, 0, n);
    }

4. Complexity analysis:

  • Time complexity: O(n), where n is the length of the array.
  • Space complexity: O(n).

5. Summary:

Rotate and loop k steps. To think of the modulo operation, a new array is needed as the result array because if we do not use an additional array, we directly put each number to its last position, so that the element at the placed position will be It is overwritten and lost, so a new array is needed as the result array, and finally the original array is copied back.

4. The maximum difference between arrays – the ring method

1. Topic:

Given an integer array nums, find the maximum difference between two numbers in the given array. Requirements, the second number must be greater than the first number.

2. Analysis features:

  • 求最大差值 ==> 最大值 - 最小值
  • It only needs to traverse the price array once, record the historical minimum value, and consider the non-minimum value as the maximum value.

3. Code:

    public int maxProfit(int nums[]) {
    
    
        int minNum = Integer.MAX_VALUE;
        int maxNum = 0;
        for (int i = 0; i < nums.length; i++) {
    
    
            if (nums[i] < minNum) {
    
    
                minNum = nums[i];
            } else if (nums[i] - minNum > maxNum) {
    
    
                maxNum = nums[i] - minNum;
            }
        }
        return maxNum;
    }

4. Complexity analysis:

  • Time complexity: O(n), only need to traverse once.
  • Space complexity: O(1), only constant variables are used.

5. Summary:

Using the idea of ​​​​fighting, when traversing, consider the current value to be the minimum value, then record the minimum value, otherwise consider the current value to be the maximum value, and update.




If this article is helpful to you, please remember to give Yile a like, thank you!

Guess you like

Origin blog.csdn.net/weixin_45630258/article/details/132738318