Untitled
unknown
plain_text
10 months ago
831 B
4
Indexable
public class RemoveElement {
public static int removeElement(int[] nums, int val) {
int j = 0; // Pointer for placing valid elements
for (int i = 0; i < nums.length; i++) {
if (nums[i] != val) { // Keep only elements not equal to val
nums[j] = nums[i];
j++;
}
}
return j; // `j` is the new length of the modified array
}
public static void main(String[] args) {
int[] nums = {0,1,2,2,3,0,4,2};
int val = 2;
int k = removeElement(nums, val);
// Printing the result
System.out.println("Output Length: " + k);
System.out.print("Modified Array: ");
for (int i = 0; i < k; i++) {
System.out.print(nums[i] + " ");
}
}
}
Editor is loading...
Leave a Comment