根据最右边的设置位和最小设置位对数组进行排序
给定一个由N个整数组成的数组arr[] ,任务是根据最右设置位(Rightmost-Set Bit,RSB)以降序的方式将数组中的每个元素替换为它们的秩,如果两个数字的 RSB 相同,则选择具有如果两个数字的设置位相同,则设置位的最少数量,然后选择数组中第一个出现的数字。
例子:
Input: arr[] = {4, 5, 6, 7, 8}
Output: 2 4 3 5 1
Explanation: Then rank of elements is given by sorted descending of RSB.
Rank(8) = 1 as Rsb of 8(1000) is 8 and setbit count is 1.
Rank(4) = 2 as RSB of 4(0100) is 4 and setbit count is 1.
Rank(6) = 3 as RSB of 6(0110) is 2 and setbit count is 2.
Rank(5) = 4 as RSB of 5(0101) is 1 and setbit count is 2.
Rank(7) = 5 as Rsb of 7(0111) is 1 and setbit count is 3.
So, the answer will be { 2, 4, 3, 5, 1 }.
Input: arr[] = {5, 10, 15, 32}
Output: 3 2 4 1
朴素方法:朴素方法是通过比较该元素的 RSB 与其他元素并在遇到较大的 RSB 值时将排名增加 1 来找到每个元素的排名。
时间复杂度: O(N*N)。
辅助空间: 在)。
有效方法:为了优化上述简单方法,找到元素的等级,然后使用比较器将等级分配给元素。使用比较器,可以根据数据成员对元素进行排序。例如,这里的元素将根据 RSB 和设置位数进行排序。
下面是上述方法的实现。
Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
// Class for pair
class Pair {
int index;
int rsb;
int setbit;
// Constructor
Pair(int index, int rsb, int setbit)
{
this.index = index;
this.rsb = rsb;
this.setbit = setbit;
}
}
// Comparator for sorting based on RSB
class pair_sort implements Comparator {
// Used for sorting in descending order
// of rightmost set bit
public int compare(Pair a, Pair b)
{
if (a.rsb > b.rsb)
return -1;
else if (a.rsb < b.rsb)
return 1;
else if (a.setbit < b.setbit)
return -1;
else if (b.setbit < a.setbit)
return 1;
else if (a.index < b.index)
return -1;
else
return 1;
}
}
// Class to implement the solution logic
class GFG {
// Function to rearrange the elements
// according to Rightmpost set bits
void rearrange(int ar[], int n)
{
// Creating priority queue from
// sorting according to
// rightmost set bit.
PriorityQueue pq
= new PriorityQueue(new pair_sort());
// For creating object of each element
// so that it can be sorted
for (int i = 0; i < n; i++) {
// To calculate the rightmost
// set bit in O(1)
int k = (ar[i] & -ar[i]);
// Creating a pair object
// with rsb and index
int setbit
= Integer.bitCount(ar[i]);
Pair p = new Pair(i, k, setbit);
// Inserting the element
// in priorityqueue
pq.add(p);
}
int rank = 1;
// Popping the element of queue
// to get respective rank.
while (!pq.isEmpty()) {
Pair p = pq.poll();
ar[p.index] = rank++;
}
}
// Driver code
public static void main(String[] args)
throws java.lang.Exception
{
int arr[] = { 4, 5, 6, 7, 8 };
// Creating an object of class
GFG ob = new GFG();
// To store the length of array
int N = arr.length;
// To call the rearrange function
ob.rearrange(arr, N);
for (int i = 0; i < N; i++)
System.out.print(arr[i] + " ");
}
}
2 4 3 5 1
时间复杂度: O(N*log(N))
辅助空间: O(N)。