Sort Array By Parity LeetCode Solution - The Coding Shala
Home >> LeetCode >> Sort Array By Parity
Other Posts You May Like
In this post, we will learn how to solve LeetCode's Sort Array By Parity Problem and will implement its solution in Java.
Sort Array By Parity Problem
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.
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.
Practice this problem on LeetCode(Click Here).
Sort Array By Parity Java Solution
Approach 1
Java Program:
class Solution { public int[] sortArrayByParity(int[] A) { int i = 0, j=A.length-1; while(i<j){ if(A[i]%2==1){ int tmp = A[i]; A[i] = A[j]; A[j] = tmp; } if(A[i]%2==0) i++; if(A[j]%2==1) j--; } return A; } }
- LeetCode - Detect Capital
- LeetCode - To Lower Case
- LeetCode - Destination City
- LeetCode - Word Subsets
- LeetCode - Shifting Letters
Comments
Post a Comment