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

牛牛的冒险旅程

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;
    }
}

全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务