Remove elements

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

Do not use extra array space, you must only use O(1) extra space and modify the input array in place.

The order of the elements can be changed. You don’t have to worry about the elements in the array after the new length.

See the LeetCode website for an example.

Source: LeetCode Link: https://leetcode-cn.com/probl… Copyright belongs to collar network. Commercial reprint please contact the official authorization, non-commercial reprint please indicate the source.

Solution 1: Switch places
  • First, if the array is empty or the length of the array is zero, it returns zero.
  • Then, if the array is not empty, traverse the array, counting the number of entries that differ from val (which is the final return value), index the number of traversals that start at 0, and reverseCount the number of numbers that were exchanged, as follows:

    • When index is not equal to val, count is incremented by 1, and index incremented by 1 is moved one place back.
    • When the corresponding value of index is equal to val, determine whether the number of traversable digits following index is. If so, exchange index with the last traversable digit, and reverseCount+1, then continue traversing; If it is not, there is no swappable position, that is, the traversal has been completed. Returns the value count.
public class LeetCode_027 { public static int removeElement(int[] nums, int val) { if (nums == null || nums.length == 0) { return 0; } int count = 0; int index = 0; int reverseCount = 0; while (index < nums.length - reverseCount) { if (nums[index] ! = val) { index++; count++; } else { if (index < (nums.length - 1 - reverseCount)) { int temp = nums[index]; nums[index] = nums[nums.length - 1 - reverseCount]; nums[nums.length - 1 - reverseCount] = temp; reverseCount++; } else { break; } } } return count; } public static void main(String[] args) { int[] nums = new int[]{1}; System.out.println(removeElement(nums, 1)); System.out.println(); for (int num : nums) { System.out.print(num + " "); }}}

【 Daily Message 】
Yesterday is history, tomorrow is a mystery, but today is a gift.