Link: https://leetcode.com/problems/sort-array-by-parity/
Solution:
The evenIndex variable literally keeps track of where the next even number should be. We know that all the even numbers should be moved to the left so the default value of evenIndex is 0.
In an iteration when we get an even number we check if the number is located at the correct index and if not we swap it’s current location with the correct location. If the even number’s index matches the correct index A[i] % 2 == 0 && i == evenIndex it means that we don’t need to perform a swap so we just increment the evenIndex.
/**
* @param {number[]} A
* @return {number[]}
*/
var sortArrayByParity = function(A) {
var evenIndex = 0;
for (var i = 0; i < A.length; i++)
{
if (A[i] % 2 == 0 && i != evenIndex)
{
var tmp = A[evenIndex];
A[evenIndex++] = A[i];
A[i] = tmp;
} else if (A[i] % 2 == 0 && i == evenIndex)
evenCount++;
}
return A;
};
Time Complexity: O(n)
Leave a Reply