Leetcode: Sort Array By Parity II

Sort Array By Parity II



Similar Problems:


Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even.

Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even.

You may return any answer array that satisfies this condition.

Example 1:

Input: [4,2,5,7]
Output: [4,5,2,7]
Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.

Note:

  1. 2 <= A.length <= 20000
  2. A.length % 2 == 0
  3. 0 <= A[i] <= 1000

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


  • Solution: array
// Blog link: https://code.dennyzhang.com/sort-array-by-parity-ii
// Basic Ideas: two pointer
// Move even to the first half, the odd to the second half
// Then swap items
// Complexity: Time O(n), Space O(1)
func sortArrayByParityII(A []int) []int {
    l, r := 0, len(A)-1
    for l<r {
        if A[l] % 2 == 0 {
            l++
            continue
        }
        if A[r] % 2 == 1 {
            r--
            continue
        }
        A[l], A[r]= A[r], A[l]
        l, r = l+1, r-1
    }

    for i:=1; 2*i<len(A); i+=2 {
        j := len(A)-1-i
        A[i], A[j] = A[j], A[i]
    }
    return A
}
linkedin
github
slack

Share It, If You Like It.

Leave a Reply

Your email address will not be published.