题解 | #牛牛的冒险旅程#

牛牛的冒险旅程

https://www.nowcoder.com/practice/79f7bf3d985c4b33af6d048ab53848d6

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @return int整型
     */
    public int gcdInCycle (ListNode head) {
        // write code here
        ArrayList<Integer> nums = new ArrayList<>();
        HashMap<Integer, Integer> map = new HashMap<>();
        ListNode cur=head;
        while(cur != null){
            if(map.containsKey(cur.val)){
                // System.out.println(cur.val);
                nums.add(cur.val);
                map.compute(cur.val, (key, value) -> value + 1);
                if(map.get(cur.val) == 3){
                    return ListGcd(nums);
                }
            }else{
                map.put(cur.val,1);
            }
            cur=cur.next;
        }


        return -1;

    }
    public int gcd(int x,int y){
        while(y !=0){
            int tmp=x;
            x=y;
            y=tmp%y;
        }
        return x;
    }

    public int ListGcd(ArrayList<Integer> nums){
        int result = nums.get(0);
        for (int i = 1; i < nums.size(); i++) {
            result = gcd(result, nums.get(i));
            if (result == 1) {
                // 如果在过程中GCD变为1,那么最终的GCD就是1
                return 1;
            }
        }
        return result;
    }
}

全部评论

相关推荐

Beeee0927:是缅甸园区吗
点赞 评论 收藏
分享
fRank1e:吓得我不敢去外包了,但是目前也只有外包这一个实习,我还要继续去吗
点赞 评论 收藏
分享
门口唉提是地铁杀:之前b站被一个游戏demo深深的吸引了。看up主页发现是个初创公司,而且还在招人,也是一天60。二面的时候要我做一个登录验证和传输文件两个微服务,做完要我推到github仓库,还要我加上jaeger和一堆运维工具做性能测试并且面试的时候投屏演示。我傻乎乎的做完以后人家跟我说一句现在暂时不招人,1分钱没拿到全是白干
你的秋招第一场笔试是哪家
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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