Relative Sort Array | LeetCode | JAVA

preview_player
Показать описание
Code is given in the comment section.
Check more videos for placement process:
Рекомендации по теме
Комментарии
Автор

Code:


class Solution {
public int[] relativeSortArray(int[] arr1, int[] arr2) {
int output[]=new int[arr1.length];
int temp=0;
for(int i=0;i<arr2.length;i++)
{
int tg=arr2[i];
for(int j=0;j<arr1.length;j++)
{
if(tg==arr1[j])
{
output[temp++]=tg;
}
}
}
int gh=0;
ArrayList<Integer> gm=new ArrayList<Integer>();
for(int i=0;i<arr1.length;i++)
{
int tg=arr1[i];
for(int j=0;j<arr2.length;j++)
{
if(tg==arr2[j])
{
gh=1;
break;
}
}
if(gh==0)
{
gm.add(tg);
}
gh=0;
}
Collections.sort(gm);
for(int i=0;i<gm.size();i++)
{
output[temp++]=gm.get(i);
}
return output;
}
}

KnowledgeAmplifier
Автор

Sir, where is code in comment section?

anupshaw
Автор

this is inefficient solution and the running time is O(n^2) which will be very slow, if you would have used a hashtable to store the element indices then it would have been much efficient and linear time O(n), any ways nice effort!!!

praveenchouhan