Less movement, although the code is a little long, 3ms in c++


  • 0
    S

    The solution is different to most of the solution in disscussion, I think there are too much movements. So I write the solution here. Some numbers can stay as it is.

    class Solution {
    public:
        int removeElement(vector<int>& nums, int val) {
            if(nums.empty()) return 0;
            int result = 0;
            int i = 0, j = nums.size() -1; 
    
            while(i < j){
                while(i < j && nums[i] != val) {  //find the first number equal to val from the begining
                    i++;
                    result++;
                }
                while(i < j && nums[j] == val) {  //find the first number not equal to val from the end
                    j--;
                }
                    
                if(i < j){  //if the two numbers are found, replace the first with the second number
                    result++;
                    nums[i] = nums[j];
                    i++;
                    j--;                    
                }
    
            }
            if(i == j && nums[i] != val) result++;
            return result;
        }
    };
    

Log in to reply
 

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