[GeeksForGeeks] Convert an array to reduced form

本文介绍了一种将数组元素转换为从0到n-1范围内的算法,保持原有顺序不变。提供了两种解决方案:一种O(n^2)时间复杂度的简单方法,另一种O(n*logn)时间复杂度的方法,后者使用了映射表来提高效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 }

 


转载于:https://www.cnblogs.com/lz87/p/7376792.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值