[Leetcode problem solution] double pointer problem

Summary of double pointer problems:

  1. Remove element

Given an array of nums and a value of val, you need to remove all the 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 must use only O(1) extra space and modify the input array in-situ.
The order of the elements can be changed. You don't need to consider the elements in the array beyond the new length.

Example 1:

Given nums = [3,2,2,3], val = 3, the
function should return the new length 2, and the first two elements in nums are both 2.
You don't need to consider the elements in the array beyond the new length.

Answer:
Dual pointers:
ideas

Since the problem requires us to delete all elements of a given value in place, we must use O(1)O(1) extra space to deal with it. How to solve? We can keep two pointers i and j, where i is a slow pointer and j is a fast pointer.

algorithm

When nums[j] is equal to the given value, increment j to skip the element. As long as nums[j] is not equal to val, assign nums[j] to nums[i] and increment two indexes at the same time. Repeat this process until j reaches the end of the array, and the new length of the array is i.

class Solution {
    
    
    public int removeElement(int[] nums, int val) {
    
    
        int i=0;
        for (int j=0; j< nums.length; j++) {
    
    
            if (nums[j] != val) {
    
    
                nums[i] = nums[j];
                i++;
            }
        }
        return i;
    }
}
  1. Deleting duplicate items in
    a sorted array Given a sorted array, you need to delete the repeated elements in place, so that each element only appears once, and return the new length of the removed array.
    Don't use extra array space, you must modify the input array in situ and complete with O(1) extra space.
    Example 1:

Given the array nums = [1,1,2], the
function should return the new length 2, and the first two elements of the original array nums are modified to 1, 2.
You don't need to consider the elements in the array beyond the new length.

Answer: After the
array is sorted, we can place two pointers i and j, where i is a slow pointer and j is a fast pointer. As long as nums[i] = nums[j], we increase j to skip duplicates.
When we encounter nums[j] =nums[i], the operation of skipping duplicates has ended, so we must copy the value of it (nums[j]) to nums[i+1]. Then increment i, and then we will repeat the same process again until j reaches the end of the array.

class Solution {
    
    
    public int removeDuplicates(int[] nums) {
    
    
        int i=0;
        for (int j=1; j<nums.length; j++) {
    
    
            if (nums[i] != nums[j]) {
    
    
                nums[i+1] = nums[j];
                i++;
            }
        }
        return i+1;
    }
}

Guess you like

Origin blog.csdn.net/yearningseeker/article/details/108650440