Sunday, September 3, 2017

27. Remove Element

https://leetcode.com/problems/remove-element/description/
Solution 1. Move nums[i] to nums[j] if it does not equal val. Index 0~j-1 contains all the numbers that are different from index 0~i-1. (3ms)
    int removeElement(vector<int>& nums, int val) {
        int i, j;
        for(i=0, j=0; i<nums.size(); i++) {
            if(nums[i] != val) {
                nums[j++] = nums[i];
            }
        }
        return j;      
    }
Solution 2. Move the numbers equal to val to the end of array.
Swap nums[i] with the  nums[j] if it equals val and decrease j. Numbers with index>j are then equal to val. (6ms)
    int removeElement(vector<int>& nums, int val) {
        int i, j;
        for(i=0, j=nums.size()-1; i<=j; i++) {
            if(nums[i] == val) {
                swap(nums[i], nums[j]);
                i--;
                j--;
            }
        }
        return i;      
    }

No comments:

Post a Comment