Remove Element
Question:
Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Difficulty: Easy
Similar Problem: Remove Element
Link: https://leetcode.com/problems/remove-element/
Solution:
99% SAME AS "MOVE ZEROES". Actually, it just change the zero to another number.
Scan the arrays and swap the non-target number in the front of array, then do nothing on zero.
Code:
public class Solution {
public int removeElement(int[] nums, int val) {
int scanner = 0;
int marker = 0;
int length = 0;
while(scanner < nums.length){
if(nums[scanner] != val){
int tmp = nums[scanner];
nums[scanner] = nums[marker];
nums[marker] = tmp;
length++;
marker++;
}
scanner++;
}
return length;
}
}