问题描述
小蓝对一个数的数位之和很感兴趣, 今天他要按照数位之和给数排序。当 两个数各个数位之和不同时, 将数位和较小的排在前面, 当数位之和相等时, 将数值小的排在前面。
例如, 2022 排在 409 前面, 因为 2022 的数位之和是 6, 小于 409 的数位 之和 13 。
又如, 6 排在 2022 前面, 因为它们的数位之和相同, 而 6 小于 2022 。
给定正整数 n,m, 请问对 1 到 n 采用这种方法排序时, 排在第 m 个的元 素是多少?
输入格式
输入第一行包含一个正整数 n 。
第二行包含一个正整数 m 。
输出格式
输出一行包含一个整数, 表示答案。
样例输入
13
5
样例输出
3
样例说明
![](https://i-blog.csdnimg.cn/blog_migrate/ea53c97939ab601d34fb0e59c1a4953e.png)
评测用例规模与约定
![](https://i-blog.csdnimg.cn/blog_migrate/0b3cd30b38bcf6d025d932246e75783e.png)
运行限制
最大运行时间:3s
最大运行内存: 512M
源码:
第一种方法:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class 数位排序 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n=scanner.nextInt();
int m=scanner.nextInt();
List<Integer> list=new ArrayList<Integer>();
for (int i = 1; i <= n; i++) {
list.add(i);
}
Collections.sort(list, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if (check(o1)!=check(o2)) {
return check(o1)-check(o2);
}else {
return o1-o2;
}
}
});
System.out.println(list.get(m-1));
}
protected static int check(Integer n) {
int sum=0;
while(n>0) {
sum+=n%10;
n=n/10;
}
return sum;
}
}
第二种方法:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
public class 数位排序2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n=scanner.nextInt();
int m=scanner.nextInt();
HashMap<Integer, List<Integer>> hashMap=new HashMap<Integer, List<Integer>>();
//分块 根据数位和去分块
for (int i = 1; i <= n; i++) {
int num=check(i);
if (hashMap.containsKey(num)) {
hashMap.get(num).add(i);
}else {
List<Integer> temp=new ArrayList<Integer>();
temp.add(i);
hashMap.put(num, temp);
}
}
List<Integer> list=new ArrayList<Integer>(hashMap.keySet());
for(Integer e:list) {
if (m>hashMap.get(e).size()) {
m-=hashMap.get(e).size();
}else {
System.out.println(hashMap.get(e).get(m-1));
return;
}
}
}
private static int check(int n) {
int sum=0;
while(n>0) {
sum+=n%10;
n=n/10;
}
return sum;
}
}