Sort Array By Parity II LeetCode Solution - The Coding Shala
Home >> LeetCode >> Sort Array By Parity 2
Other Posts You May Like
In this post, we will learn how to solve LeetCode's Sort Array By Parity 2 Problem and will implement its solution in Java.
Sort Array By Parity 2 Problem
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.
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.
Practice this Problem on LeetCode(Click Here).
Sort Array By Parity 2 Java Solution
Approach 1
This problem can be solved by using two pointers.
Java Program:
class Solution { public int[] sortArrayByParityII(int[] A) { int even = 0, odd = 1; while(even < A.length && odd < A.length){ if(A[even]%2==1){ int tmp = A[even]; A[even] = A[odd]; A[odd] = tmp; odd += 2; }else{ even += 2; } } return A; } }
- LeetCode - Sort Array By Parity
- LeetCode - Valid Square
- LeetCode - Flipping an Image
- LeetCode - Crawler Log Folder
- LeetCode - Buddy Strings
Comments
Post a Comment