[GeeksForGeeks] Convert an array to reduced form

Posted Push your limit!

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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 }

 

以上是关于[GeeksForGeeks] Convert an array to reduced form的主要内容,如果未能解决你的问题,请参考以下文章

[GeeksForGeeks] Diameter of a Binary Tree

[GeeksForGeeks] Write a program to delete a tree

平摊分析 Amortized Analysis ------geeksforgeeks翻译

geeksforgeeks@ Maximum Index (Dynamic Programming)

[GeeksForGeeks] Multiply a given integer by 3.5

分析循环 Analysis of Loops-------geeksforgeeks 翻译