Description

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.

Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:

Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums. Return k.

Custom Judge:

The judge will test your solution with the following code:

 1int[] nums = [...]; // Input array
 2int val = ...; // Value to remove
 3int[] expectedNums = [...]; // The expected answer with correct length.
 4                            // It is sorted with no values equaling val.
 5
 6int k = removeElement(nums, val); // Calls your implementation
 7
 8assert k == expectedNums.length;
 9sort(nums, 0, k); // Sort the first k elements of nums
10for (int i = 0; i < actualLength; i++) {
11    assert nums[i] == expectedNums[i];
12}

If all assertions pass, then your solution will be accepted.

Example 1:

1Input: nums = [3,2,2,3], val = 3
2Output: 2, nums = [2,2,_,_]
3Explanation: Your function should return k = 2, with the first two elements of nums being 2.
4It does not matter what you leave beyond the returned k (hence they are underscores).

Example 2:

1Input: nums = [0,1,2,2,3,0,4,2], val = 2
2Output: 5, nums = [0,1,4,0,3,_,_,_]
3Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
4Note that the five elements can be returned in any order.
5It does not matter what you leave beyond the returned k (hence they are underscores).

Constraints:

  • 0 <= nums.length <= 100
  • 0 <= nums[i] <= 50
  • 0 <= val <= 100

Solution

The idea here is to move forward from the beginning and everytime we find a number which is not matching val, insert it at the first position. The position is tracked using i - count. Here count is the number of elements which matched val. This way at the end we can return elements which did not match nums.length - count.

 1class Solution {
 2    public int removeElement(int[] nums, int val) {
 3        int count = 0;
 4        for (int i = 0; i < nums.length; ++i) {
 5            if (nums[i] == val)
 6                ++count;
 7            else
 8                nums[i - count] = nums[i];
 9        }
10        System.out.println(Arrays.toString(nums));
11        return nums.length - count;
12    }
13}