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 }
    
    
  • 相关阅读:
    LeetCode Best Time to Buy and Sell Stock
    LeetCode Scramble String
    LeetCode Search in Rotated Sorted Array II
    LeetCode Gas Station
    LeetCode Insertion Sort List
    LeetCode Maximal Rectangle
    Oracle procedure
    浏览器下载代码
    Shell check IP
    KVM- 存储池配置
  • 原文地址:https://www.cnblogs.com/lz87/p/7376792.html
Copyright © 2011-2022 走看看