LeetCode:922. Sort Array By Parity II

題目:
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.

範例:

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.

解法:
這題還算簡單,簡單的排列,用雙數與單數的位置計數放值

func sortArrayByParityII(A []int) []int {
    var odd, even = 1, 0
	resultData := make([]int, len(A))
	for _, data := range A {
		if data%2 == 0 {
			resultData[even] = data
			even += 2
		} else {
			resultData[odd] = data
			odd += 2
		}
	}
    return resultData
}
Next PostRead more articles

發佈留言