LeetCode Algorithms Easy: Squares of a Sorted Array

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

My name is Michael Lin and this is my programming youtube channel. I like C++ and please message me or comment on what I should program next. It really helps out a lot.

Rate, Comment, Subscribe

Subscribe to my singing channel:

#mergeSort #Sorting #Algorithms #dataStructures

Personal Accounts:
Instagram: @michaellin250
Twitter: @Michaellin250
Рекомендации по теме
Комментарии
Автор

Hi, Nice video. I would like to ask. You already have the size of the current array. you can create an array of the same size. Have your pointers loop until you find a negative number while merging. This will help you avoid having the first loop to check the index of the positive number. Here is the code in java.

private static int[] solution(int[] a) {
if (a.length < 1){
return a;
}

int negativePointer = 0;
int positivePointer = a.length -1;
int[] results = new int[a.length];
int insertIndex = results.length-1;

while (negativePointer < positivePointer){
int positiveSquared = a[positivePointer] * a[positivePointer];
int negativeSquared = a[negativePointer] * a[negativePointer];

if(negativeSquared > positiveSquared){
results[insertIndex] = negativeSquared;
negativePointer++;
} else if(negativeSquared < positiveSquared){
results[insertIndex] = positiveSquared;
positivePointer --;
} else if(negativeSquared == positiveSquared) {
results[insertIndex] = positiveSquared;
insertIndex--;
results[insertIndex] = negativeSquared;
negativePointer++;
positivePointer--;
}
insertIndex--;
}

return results;
}

bryankituyi