Double pointer to solve the sorting in the array

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.

Instead of using extra array space, you have to use only O(1) extra space and modify the input array in place.

 public static int removeElement(int[] nums, int val) {
    
    
        //首先理清思路,采用双指针的方法在原有的数组上进行重新排序
        int pre=0; //前指针进行排序,始终是正确队列的尾指针
        //后指针需要进行遍历来对比判断
        for (int i = 0; i <nums.length ; i++) {
    
    
            if(nums[i]!=val)//后指针与替换对象对比
            {
    
    
                nums[pre]=nums[i];//后指针对比后,不相等就代表要提前,赋值给前指针
                pre++;//前指针后移,因为已经被赋值
            }
        }
        return pre;
    }

The double pointer is used to operate the array, the front pointer is sorted, it is the tail pointer of the correct sequence, and the back pointer is the traversal pointer, which traverses the array to compare each number of the array;

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324106154&siteId=291194637