Java clean solution O(n) time with 2 pointers

  • 0

    Basic idea: move all values not equal to val to the front of the array, move all values equal to val to the back of the array. Pointer 'tail' represents the desire array's tail position, pointer 'waste' represents the position that the most front val in the back of the array.

    public class Solution {
        public int removeElement(int[] nums, int val) {
            int tail = 0;
            int waste = nums.length;
            while (tail != waste) {
                if (nums[tail] != val) {
                    tail ++;
                } else {
                    waste --;
                    int temp = nums[waste];
                    nums[waste] = nums[tail];
                    nums[tail] = temp;
            return tail;

Log in to reply

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