题解 | #继续xxx定律#

继续xxx定律

https://www.nowcoder.com/practice/9cc1055241c547269f58fa8b009e335d




import java.util.HashSet;
import java.util.LinkedList;
import java.util.Scanner;

public class Main {

    static LinkedList<Integer> f(int [] nums) {
        HashSet<Integer> set = new HashSet<>();
        for (int x : nums) {
            if (!set.contains(x)) {
                while (x != 1) {
                    if (x % 2 == 0) {
                        x >>= 1;
                    } else {
                        x = (3 * x + 1) >> 1;
                    }
                    set.add(x);
                }
            }
        }

        LinkedList<Integer> ans = new LinkedList<>();

        for (int x : nums) {
            if (!set.contains(x))
                ans.addFirst(x);
        }
        return ans;
    }
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            int n = scanner.nextInt();
            int[] nums = new int[n];

            for (int i = 0; i < n; i++) {
                nums[i] = scanner.nextInt();
            }

            f(nums).forEach(x-> System.out.print(x + " "));
            System.out.println();
        }
    }
}

全部评论

相关推荐

03-15 10:59
已编辑
美团_后端开发(实习员工)
爱写代码的菜code...:哎,自己当时拿到字节offer的时候也在感叹终于拿到了,自己当时最想去的企业就是字节,结果还是阴差阳错去了鹅厂。祝uu一切顺利!!!
点赞 评论 收藏
分享
03-02 08:18
集美大学 Java
钱嘛数字而已:没有赛事奖项么?另外,项目经历字有点多哈,建议突出一下重点:用的什么技术,解决什么问题,达到什么效果。
大家都开始春招面试了吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务