922. Sort Array By Parity II(Solution || Leetcode easy || Java)
Given an array of integers nums
, half of the integers in nums
are odd, and the other half are even.
Sort the array so that whenever nums[i]
is odd, i
is odd, and whenever nums[i]
is even, i
is even.
Return any answer array that satisfies this condition.
Example 1:
Input: nums = [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.
Example 2:
Input: nums = [2,3]
Output: [2,3]
Constraints:
2 <= nums.length <= 2 * 104
nums.length
is even.- Half of the integers in
nums
are even. 0 <= nums[i] <= 1000
Follow Up: Could you solve it in-place?
SOLUTION(1):
class Solution {
public int[] sortArrayByParityII(int[] nums) {
//first we will seperate even and odd numbers and store them in a temporary array
int i = 0;
int j = nums.length — 1;
int[] temp = new int[nums.length];
for(int k = 0; k < nums.length; k++){
if(nums[k]%2 == 0){
temp[i] = nums[k];
i++;
}
else{
temp[j] = nums[k];
j — ;
}
}
//now we are arranging even num at even index and odd at odd index
int[] ans = new int[nums.length];
int even = 0;
int odd = j + 1;
for(int k = 0; k < nums.length; k++){
if(k%2 == 0){
ans[k] = temp[even];
even++;
}
else{
ans[k] = temp[odd];
odd++;
}
}
return ans;
}
}
SOLUTION(2):
class Solution {
public int[] sortArrayByParityII(int[] nums) {
//Initilaise varibale for even index
int i = 0;
//Initialise variable for odd index
int j = 1;
//Intialise array to return
int[] ans = new int[nums.length];
for(int k = 0; k < nums.length; k++){
//if element is even, add it in ans array at the even index
if(nums[k]%2 == 0){
ans[i] = nums[k];
i += 2;
}
//if element is odd, add that element in the ans array at odd index
else{
ans[j] = nums[k];
j += 2;
}
}
return ans;
}
}
Runtime: 2 ms, faster than 99.88% of Java online submissions for Sort Array By Parity II.
Memory Usage: 43.9 MB, less than 96.22% of Java online submissions for Sort Array By Parity II.
Thank you for reading. If you have any queries then, plese let me know in the comment section. I will surely be responsive toward it.