In Case of Duplicate elements present in the array, it will not work also not given int the question that elements will be distinct only, This solution will work in case of duplicates also: class Pair{ int first; int second; Pair(int first, int second){ this.first = first; this.second = second; } } class Solution { void convert(int[] arr, int n) { HashMap map = new HashMap(); Pair[] nums = new Pair[n]; for(int i = 0; i < n; i++){ nums[i] = new Pair(arr[i], i); } Arrays.sort(nums, (a, b)->{ return a.first - b.first; }); for(int i = 0; i < n; i++){ arr[nums[i].second] = i; } } } by the way nice explanation.
Appreciate your efforts :) Since it was mentioned array with n distinct elements in the first line. So i ignored the duplicate factor. Thanks for your solution too 🙌
#for python people def convert(self,arr, n): # code here x=[None] * n#created temp array and copied values into it for i in range(0, n): x[i] = arr[i]; x.sort()#sorted the temp array dic={} y=[] for i in range(n): dic[x[i]]=i#used dictionary to store key value for i in range(n): arr[i]=dic.get(arr[i]) #replaced values of original array with index #thank you sir ji
In Case of Duplicate elements present in the array, it will not work also not given int the question that elements will be distinct only,
This solution will work in case of duplicates also:
class Pair{
int first;
int second;
Pair(int first, int second){
this.first = first;
this.second = second;
}
}
class Solution {
void convert(int[] arr, int n) {
HashMap map = new HashMap();
Pair[] nums = new Pair[n];
for(int i = 0; i < n; i++){
nums[i] = new Pair(arr[i], i);
}
Arrays.sort(nums, (a, b)->{
return a.first - b.first;
});
for(int i = 0; i < n; i++){
arr[nums[i].second] = i;
}
}
}
by the way nice explanation.
Appreciate your efforts :)
Since it was mentioned array with n distinct elements in the first line. So i ignored the duplicate factor.
Thanks for your solution too 🙌
#for python people
def convert(self,arr, n):
# code here
x=[None] * n#created temp array and copied values into it
for i in range(0, n):
x[i] = arr[i];
x.sort()#sorted the temp array
dic={}
y=[]
for i in range(n):
dic[x[i]]=i#used dictionary to store key value
for i in range(n):
arr[i]=dic.get(arr[i]) #replaced values of original array with index
#thank you sir ji
Great, i encourage your participation.
Thanks 🙌
Keep solving
@@AkshayAnil0-1 yes...