首页 > 其他分享 >leetcode-141-easy

leetcode-141-easy

时间:2022-10-19 07:47:37浏览次数:48  
标签:head set return 141 h2 h1 easy ListNode leetcode

Linked List Cycle
思路一: 用 set 记录每个节点的 hashCode,如果遇到重复,说明是循环

public boolean hasCycle(ListNode head) {
    Set<Integer> set = new HashSet<>();
    while (head != null) {

        if (set.contains(head.hashCode())) {
            return true;
        }
        set.add(head.hashCode());

        head = head.next;
    }

    return false;
}

思路二: 快慢指针,一个每次进一步,一个每次进两步,如果是循环链表,他们一定会相遇

public boolean hasCycle(ListNode head) {
    ListNode h1 = head;
    ListNode h2 = head;

    while (h2 != null) {
        h2 = h2.next;
        if (h2 == null) return false;
        h2 = h2.next;
        h1 = h1.next;

        if (h2 == h1) return true;
    }

    return false;
}

标签:head,set,return,141,h2,h1,easy,ListNode,leetcode
From: https://www.cnblogs.com/iyiluo/p/16804869.html

相关文章

  • leetcode-344-easy
    ReverseString思路一:首尾互换publicvoidreverseString(char[]s){intmid=s.length/2;intbegin=0;intend=s.length-1;while(beg......
  • leetcode-263-easy
    UglyNumber思路一:从数字中依次去除2,3,5,查看剩余的值是否为1publicbooleanisUgly(intn){if(n==0)returnfalse;while(n%2==0){n/......
  • leetcode-217-easy
    ContainsDuplicate思路一:Set检测publicstaticbooleancontainsDuplicate(int[]nums){Set<Integer>set=newHashSet<>();for(intnum:nums){......
  • leetcode-709-easy
    ToLowerCase思路一:遍历,遇到A-Z范围内的char转换到对应a-z范围publicStringtoLowerCase(Strings){if(s==null||s.isEmpty())returns;int......
  • leetcode-415-easy
    AddString思路一:模拟加法运算,字符串前面填零publicStringaddStrings(Stringnum1,Stringnum2){intmax=Math.max(num1.length(),num2.length());nu......
  • leetcode-389-easy
    FindtheDifference思路一:xor两个字符串publiccharfindTheDifference(Strings,Stringt){charresult=0;for(inti=0;i<s.length();i++){......
  • leetcode-226-easy
    InvertBinaryTree思路一:递归,交换左右。这题比较出名,个人感觉面试的题目和实际工作中遇到的问题还是不太一样的,所以一点准备都不做就跑去面试,答不上来很正常。一般能力......
  • leetcode-219-easy
    ContainsDuplicateII思路一:for循环遍历,结果超时publicbooleancontainsNearbyDuplicate(int[]nums,intk){intleft=-1;for(inti=0;i<nums......
  • leetcode-448-easy
    思路一:用数组记录publicList<Integer>findDisappearedNumbers(int[]nums){int[]m=newint[nums.length];for(intnum:nums){if(num-1......
  • leetcode-495-easy
    TeemoAttacking思路一:对两个前后攻击序列,完全分类只可能出现两种情况,只要把重叠的时间都减去,就是所求时间。此分类对三个以上的重叠时间依旧成立没有重叠,攻击时间累......