利用map存取数字变到1过程中经历的数字,又因为要倒序输出,所以先对整个数组做一次倒序排序,然后再把map中无法获取到的数输出即为答案
import java.io.IOException; import java.util.*; public class Main { public static void main(String[] args) throws IOException { Scanner in=new Scanner(System.in); int num=in.nextInt(); int[] a=new int[num]; List<Integer> list=new ArrayList<>(); Map<Integer,Integer> map=new HashMap<>(); map.put(1,0); for(int i=0;i<num;i++){ a[i]=in.nextInt(); getMap(map,a[i]); } Arrays.sort(a); for(int i=a.length-1;i>=0;i--){ if(map.get(a[i])==null){ list.add(a[i]); } } for(int i=0;i<list.size();i++) { if (i == list.size() - 1) { System.out.print(list.get(i)); } else { System.out.print(list.get(i) + " "); } } } public static void getMap(Map map, int element) { while (element != 1) { if (element % 2 == 0) { element = element / 2; } else { element = (3 * element + 1) / 2; } map.put(element, 0); } } }