How to sort arrays by parity in LeetCode
This article introduces how to sort the array by parity in LeetCode, the content is very detailed, interested friends can refer to, I hope it can be helpful to you.
Train of thought
First declare an array result to store the final result, and then traverse the array twice, the first time the even number into the result, the second time the odd number into the result is mainly traversal operation, when the time complexity is .4. Implement public int [] sortArrayByParity (int [] A) {
/ / store the final result
Int [] result = new int [A.length]
Int index = 0
/ / for the first time, even numbers are stored in the result array.
For (int item: a) {
If (item% 2 = = 0) {
Result [index++] = item
}
}
/ / the second traversal, storing odd numbers in the result array
For (int item: a) {
If (item% 2! = 0) {
Result [index++] = item
}
}
Return result
}
On how to sort the array by parity in LeetCode is shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.