905. Sort Array By Parity
EasyView on LeetCode
Time: O(n)
Space: O(1)
Advertisement
Intuition
Two pointers: move evens to front, odds to back.
Algorithm
- 1lo=0, hi=n-1. While lo<hi: if A[lo] is even, lo++. If A[hi] is odd, hi--. Else swap.
Common Pitfalls
- •In-place O(1) space solution.
905.cs
C#
// Approach: In-place two-pointer partition; move even numbers to the front by swapping with a write pointer.
// Time: O(n) Space: O(1)
public class Solution
{
public int[] SortArrayByParity(int[] nums)
{
int n = nums.Length;
int k = 0;
for (int i = 0; i < n; i++)
{
if (nums[i] % 2 == 0)
{
int temp = nums[k];
nums[k++] = nums[i];
nums[i] = temp;
}
}
return nums;
}
}Advertisement
Was this solution helpful?