Skip to content

Instantly share code, notes, and snippets.

@eduzol
Created March 20, 2017 01:55
Show Gist options
  • Save eduzol/26b5f20399d11b90e56bf00fe5c75aeb to your computer and use it in GitHub Desktop.
Save eduzol/26b5f20399d11b90e56bf00fe5c75aeb to your computer and use it in GitHub Desktop.
// Class name must be "Main"
import java.util.Arrays;
class Main {
/**
Given an array and a value, remove all instances of that value in place and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example:
Given input array nums = [3,2,2,3], val = 3
Your function should return length = 2, with the first two elements of nums being 2.
*/
public static void main(String[] args) {
int[] nums = new int[]{3,2,2,3};
int val = 3;
Main main = new Main();
int newLength = main.removeElement(nums, val);
System.out.println("newLength " + newLength );
System.out.println("Array=> " + Arrays.toString(nums));
}
//Complexity O(n)
public int removeElement(int[] nums, int val) {
int newLength = 0;
for ( int i = 0 ; i < nums.length ; i++ ){
int value = nums[i];
if ( value != val ){
nums[newLength] = value;
newLength++;
}
}
return newLength;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment