[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 }

 


posted @ 2017-08-17 06:05  Review->Improve  阅读(364)  评论(0编辑  收藏  举报