A Java Solution by two pointer


  • 0
    C

    public class Solution {
    public int removeElement(int[] nums, int val) {
    //base case
    int length = nums.length;
    if(length==1){
    if(nums[0] == val){return 0;}
    else {return 1;}
    }
    else{
    for(int i=0;i<length;){
    if(nums[i] == val){
    int k=i;
    int j = i+1;
    for(;j<length;j++){
    nums[k]=nums[j];
    k++;
    }
    length--;
    }
    else{
    i++;
    }
    }
    if(length==1){
    if(nums[0] == val){return 0;}
    else {return 1;}
    }
    }
    return length;
    }
    }


Log in to reply
 

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