Java O(n) solution beats 97% easy to understand


  • 0
    D

    Here is a solution that beat 97% of the solutions
    The code is pretty simple uses a while loop and 2 pointers.

    public class Solution {
        public int removeElement(int[] nums, int val) {
            if (nums == null || nums.length == 0) {
                return 0;
            }
            
            int i=0; 
            int j=0;
            
            while(i<nums.length && j<nums.length) {
                if(nums[i] != val) {
                    nums[j] = nums[i];
                    i++;
                    j++;
                    continue;
                }
                i++;
            }
            return j;
        }
    }
    

Log in to reply
 

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