The title

LeetCode 27, remove element association type: array

Given an array of nums and a value of val, you remove all elements equal to val in place and return the new length of the array. Instead of using extra array space, you must only use O(1) extra space and modify the input array in place. The order of elements can be changed. You don't need to worry about the element after the new length in the array. Explanation: Why is the return value an integer, but the output answer is an array? Note that the input array is passed "by reference," which means that modifying the input array in a function is visible to the caller. You can imagine the internal operation as follows: // NUMs is passed "by reference". Int len = removeElement(nums, val); // Modifying the input array in a function is visible to the caller. // Depending on the length returned by your function, it prints out all elements in the array within that length. for (int i = 0; i < len; i++) { print(nums[i]); } Example 1: 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 worry about the element after the new length in the array. For example, the function returns a new length of 2, and nums = [2,2,3,3] or nums = [2,2,0,0] will also be considered the correct answer. Example 2: Input: nums = [0,1,2,2,3,0,4,2], val = 2 Output: 5, nums = [0,1,4,0,3] Explanation: The function should return a new length of 5, and the first five elements in nums are 0,1, 3,0,4. Notice that these five elements can be in any order. You don't need to worry about the element after the new length in the array. 0 <= nums.length <= 100 0 <= nums[I] <= 50 0 <= val <= 100Copy the code

Time to solve the problem.

class Solution {
    public int removeElement(int[] nums, int val) {



    }
}

Copy the code

The method input parameters are given above to complete the answer.

Subject analysis

  1. If you read the article “Removing duplicates from sorted Arrays” carefully, you will be able to solve this problem in no time
  2. You can use two Pointers, one for pin-comparison and one for recording insertion positions, assigning them to insertion positions when two different cases are encountered, and finally returning the array length.

Answers to analysis

This article only analysis I do the idea, only for reference, to understand a solution to the idea, other kinds of ideas to do the problem please access the Internet.

Answer successful: Execution time :0 ms, beat 100.00% Java user memory consumption :37 MB, beat 69.48% Java users

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;
    }
}
Copy the code