Clear and fast Java solution (fast for rare removements)


  • 0
    J
    public class Solution {
        public int removeElement(int[] nums, int val) {
            if(nums.length==0){ return 0;}
            int ptr1 = 0, ptr2 = nums.length-1;
            while(ptr1 < ptr2){
                if(nums[ptr1]==val){
                    nums[ptr1] = nums[ptr2];
                    ptr2--;
                }else{
                    ptr1++;
                }
            }   
            return nums[ptr2]==val?ptr2:ptr2+1;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.