LeetCode Sort Array By Parity II Solution Explained - Java

preview_player
Показать описание


Preparing For Your Coding Interviews? Use These Resources
————————————————————

Other Social Media
----------------------------------------------

Show Support
------------------------------------------------------------------------------

#coding #programming #softwareengineering
Рекомендации по теме
Комментарии
Автор

Solved this one pretty quickly with the first n space solution, your solution was far better, I didn't even think about optimizing it as you did.

noctua
Автор

Hey I feel pretty lucky to have found you mid series. I guess we're grinding these bad boys out together my man. Good luck to you, I'll be following along and solving and the same ones.

atamidnight
Автор

You are the guru, making problem look very simple....

SK-luci
Автор

That's definitely a good example of two pointer approach

兴宣大院君-hs
Автор

Why did he put a if (i<n && j<n ) before swapping

manojpatil
Автор

class Solution {
public int[] sortArrayByParityII(int[] nums) {
//Inplace solution O(n)
int n = nums.length;
int i = 0; //i stands for even
int j = n-1; //j stands for odd
while(i < n && j >= 0) {
if (nums[i]%2 == 0) i += 2;
else if (nums[j] %2 == 1) j -= 2;
else swap(nums, i, j);
}
return nums;
}
void swap(int[] arr, int i, int j){
int temp = arr[i];
arr[i]=arr[j];
arr[j]=temp;
}

}

yashvardhan