Here is the question:
Given an integer array
nums
and an integerval
, remove all occurrences ofval
innums
in place. The relative order of the elements may be changed.Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array
nums
.More formally, if there are k elements after removing the duplicates, then the first
k
elements ofnums
should hold the final result. It does not matter what you leave beyond the first k elements.Return
k
after placing the final result in the firstk
slots ofnums
.Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
I've tried to remove the given target val
by shifting the value to the end of the array index by iteration of nums.length-1
every time the val
is found in the given array. I just want to know what's wrong with my approach.
Below is the code I've tried:
class Solution {
public int removeElement(int[] nums, int val) {
for (int i = 0; i < nums.length; i ) {
if (val == nums[i]) {
for (int j = i; j < nums.length - 1; j ) {
nums[j 1] = nums[j];
}
break;
}
}
return nums;
}
}
CodePudding user response:
Your algorithm correctly would be the following. The error was returning the array, but that was changed in-situ. You should have returned the new reduced length.
public int removeElement(int[] nums, int val) {
int k = nums.length;
for (int i = 0; i < k; i ) {
if (val == nums[i]) {
--k;
//for (int j = i; i < k; j ) {
// nums[j] = nums[j 1];
//}
System.arraycopy(nums, i 1, nums, i, k-i);
--i; // Check the new nums[i] too
}
}
return k;
}
The for-j loop can be replaced with System.arraycopy (which handles overlapping of the same array too).
Or:
public int removeElement(int[] nums, int val) {
int k = 0;
for (int i = 0; i < n; i ) {
if (val != nums[i]) {
nums[k] = nums[i];
k;
}
}
return k;
}
CodePudding user response:
This is my code in leetcode. Hope will help you
class Solution {
public int removeElement(int[] nums, int val) {
ArrayList<Integer> list = new ArrayList<>();
for(int i=0;i<nums.length;i ){
if(nums[i]!=val){
list.add(nums[i]);
}
}
for(int i=0;i<list.size();i ){
nums[i]= list.get(i);
}
return list.size();
}
}