DAY 95 Convert an array to reduced form | Sorting | GFG POTD 24 Jan

Поделиться
HTML-код
  • Опубликовано: 27 янв 2025

Комментарии • 5

  • @ManishKumar-zm9rj
    @ManishKumar-zm9rj 2 года назад +1

    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.

    • @AkshayAnil0-1
      @AkshayAnil0-1  2 года назад

      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 🙌

  • @chandrashekharpatil6332
    @chandrashekharpatil6332 2 года назад +1

    #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