zoukankan      html  css  js  c++  java
  • [GeeksForGeeks] Convert an array to reduced form

    Given an array with n distinct elements, convert the given array to a form where all elements are in range from 0 to n-1.

    The order of elements is same, i.e., 0 is placed in place of smallest element, 1 is placed for second smallest element, … n-1 is placed for largest element.

    Solution 1. O(n^2) runtime

    Do a linear scan to find the smallest element and replace its value with 0;

    Repeat the same process n - 1 times for the 2nd, 3rd,.....nth smallest elements.

    Solution 2. O(n * log n) runtime, O(n) space 

    1. make a copy of input array and sort this copy.

    2. use the sorted copy to create a mapping between each element and its reduced number .

    3. iterate the input array and replace each element with its reduced number from the mapping.

     1 public void convertToReducedForm(int[] arr) {
     2     if(arr == null || arr.length == 0) {
     3         return;
     4     }
     5     int[] temp = new int[arr.length];
     6     HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
     7     for(int i = 0; i < temp.length; i++) {
     8         temp[i] = arr[i];
     9     }
    10     Arrays.sort(temp);
    11     for(int i = 0; i < temp.length; i++) {
    12         if(!map.containsKey(temp[i])) {
    13             map.put(temp[i], i);
    14         }
    15     }
    16     for(int i = 0; i < arr.length; i++) {
    17         arr[i] = map.get(arr[i]);
    18     }
    19 }
    
    
  • 相关阅读:
    OAuth2.0协议流程
    记多个微服务同时被kill分析
    记一次调用API遇到的问题
    win10安装mysql遇到的坑
    nagios
    rmp安装mysql5.6
    桥接模式-xshell连接虚拟机
    VMWare虚拟机-网络适配器
    ***时间目录***
    docker常用命令
  • 原文地址:https://www.cnblogs.com/lz87/p/7376792.html
Copyright © 2011-2022 走看看