Leetcode 1387. Sort Integers by The Power Value
题目链接: Sort Integers by The Power Value
难度:Medium
题目大意:
给出一组整数,按照题目要求每个数对应一个权值,将这些数按照权值进行升序排序,如果权值一样则按原来的数值进行升序排列。返回排序后的第k个数。
思路:
写一个函数来计算数的权值。用优先队列来进行排序,优先队列中保留题目要求的优先级前k的数,最后弹出优先队列中的元素即可。
代码
class Solution {
public int getKth(int lo, int hi, int k) {
Queue<int[]> queue=new PriorityQueue<>((o1,o2)->o1[1]!=o2[1]?o2[1]-o1[1]:o2[0]-o1[0]);//注意这里的优先级与题目相反,才能弹出不符合题意的元素
for(int i=lo;i<=hi;i++){
queue.offer(new int[]{i,step(i)});
if(i-lo+1>k){
queue.poll();
}//保留题目中优先级前k小的元素
}
return queue.poll()[0];
}
private int step(int x){
int count=0;
while(x!=1){
if(x%2==0){
x/=2;
count++;
}
else{
x=3*x+1;
count++;
}
}
return count;
}
}