Programming

Leetcode-27. Remove Element

Leetcode-27. Remove Element

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:

int[] nums = […]; // Input array int val = …; // Value to remove int[] expectedNums = […]; // The expected answer with correct length. // It is sorted with no values equaling val.

int k = removeElement(nums, val); // Calls your implementation

assert k == expectedNums.length; sort(nums, 0, k); // Sort the first k elements of nums for (int i = 0; i < actualLength; i++) { assert nums[i] == expectedNums[i]; } If all assertions pass, then your solution will be accepted.

Example 1:

Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]

Explanation: Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores).

->對於返回的結果中的五個元素,它們的順序並不重要,可以以任意順序返回這五個元素,並且不需要對返回的 k 之後的元素做任何處理(可以用底線表示)

<解題>

  1. 給一個數組nums和一個值val,需要移除所有數值等於val的元素,返回移除後數組的新長度。
  2. 建一個迴圈,開始跑每個數值,當數值和val不同,就存在本來的數列(數值相同的不存入)

class Solution {
    public int removeElement(int[] nums, int val) {
        int returnValue = 0;
        if (nums != null && nums.length > 0) {
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] != val) {
                    nums[returnValue] = nums[i];
                    returnValue++;
                }
            }
        }
        return returnValue;
    }
}