Leetcode - Duplicate Zeros
Leetcode - Height Checker

Leetcode - Sort Array By Parity

violet posted @ Jul 14, 2020 06:06:00 AM in 算法 with tags Algorithm Golang array , 209 阅读

https://leetcode.com/problems/sort-array-by-parity/

Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.

You may return any answer array that satisfies this condition.

 

Example 1:

Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.

 

func sortArrayByParity(A []int) []int {
    var i, j int
    for {
        for i < len(A) && A[i] % 2 == 0 {
            i++
        }
        if i >= len(A) {
            break
        }
        j = i + 1
        for j < len(A) && A[j] % 2 != 0 {
            j++
        }
        if j >= len(A) {
            break
        }
        A[i], A[j] = A[j], A[i]
        i++
    }
    return A
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter