Head&Tail searching, O(n), Least element moving


  • 0
    A
    public class Solution {
        public int removeElement(int[] nums, int val) {
            int head = 0;
            int tail = nums.length-1;
            while (head <= tail){
                if(nums[head] == val){
                    while(head<tail && nums[tail]== val){
                        tail--;
                    }
                    if(tail != head){
                        nums[head] = nums[tail];
                        head++;
                    }
                    tail--;
                }else{
                    head++;
                }
            }
    
            return tail+1;
        }
    }
    

Log in to reply
 

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