Showing posts with label in place. Show all posts
Showing posts with label in place. Show all posts

Saturday, September 19, 2015

[LeetCode] Move Zeroes

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Note:
  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.
class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int size = nums.size();
        if(size<=1) return;
        int s = 0, e = 0;
        
        while(s<size) {
            while( s < size && nums[s] == 0) {
                s++;
            }
            if(s == size) break;
            
            swap(nums[s], nums[e]);
            e++;
            s++;
        }
        return;
    }
};

Monday, April 27, 2015

[LeetCode] Sort Colors

Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

class Solution {
public:
    void sortColors(int A[], int n) {
        int r = 0, w = 0;
        for(int i=0;i<n;i++)
        {
            if(A[i] == 0)
            {
                A[r++] = A[i];
            }
            else if(A[i] == 1)
            {
                w++;
            }
        }
        for(int i=r;i<r+w;i++)
        {
            A[i] = 1;
        }
        for(int i=r+w;i<n;i++)
        {
            A[i] = 2;
        }
    }
};
Another in-place solution:
class Solution{
public:
    void sortColors(vector<int> &nums) {
        int red = 0;
        int blue = nums.size() - 1;
        int p = red;

        while(p<=blue)
        {
            if(nums[p] == 0)
            {
                if(p != red) swap(nums[red], nums[p]);
                else p++;
                red ++;
            }
            else if(nums[p] == 2)
            {
                if(p!=blue) swap(nums[blue], nums[p]);
                else p++;
                blue --;
            }
            else p++;
        }
    }
};

Sunday, April 26, 2015

[LeetCode] Remove Element

Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
class Solution {
public:
    int removeElement(int A[], int n, int elem) {
        int s=0;
        int i=0;
        while(i<n)
        {
            if(A[i] != elem)
            {
                A[s++] = A[i];
            }
            i++;
        }
        return s;
    }
};