Title: Remove Element Source: leetcode.com
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.
Java solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
/* https://leetcode.com/problems/remove-element/ */ class RemoveElement { public int removeElement(int[] nums, int val) { int leftPtr = 0; int rightPtr = nums.length-1; while(leftPtr <= rightPtr) { while(leftPtr < nums.length && nums[leftPtr] != val ) leftPtr++; while(rightPtr > -1 && nums[rightPtr] == val) rightPtr--; if(leftPtr < nums.length && rightPtr > -1 && leftPtr < rightPtr) { //System.out.println("before: rightPtr: "+rightPtr+" leftPtr: "+ leftPtr); //print(nums); int temp = nums[leftPtr]; nums[leftPtr] = nums[rightPtr]; nums[rightPtr] = temp; leftPtr++; rightPtr--; //System.out.println("after: rightPtr: "+rightPtr+" leftPtr: "+ leftPtr); print(nums); } } return rightPtr>-1 ? (rightPtr+1) : 0; } void print(int[] nums) { for(int i : nums) System.out.print(i+"\t"); System.out.println(); } public static void main(String args[]) { RemoveElement re = new RemoveElement(); int[] nums = {4}; System.out.println(re.removeElement(nums, 4)); } } |