蓝桥杯刷题JAVA(8)

昨天重点在改论文因此鸽了,今天继续

1.环形链表

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head == null)
            return false;
        ListNode fast = head.next;
        if(fast == null)
            return false;
        ListNode slow = head;
        while(fast.next != null && fast != slow){
            fast = fast.next;
            if(fast == null)
                return false;
            fast = fast.next;
            if(fast == null)
                return false;
            slow = slow.next;
        }
        if(fast == slow)
            return true;
        else
            return false;
    }
}

经验:
(1)快慢链表,利用两个步进速度不一样的指针,通过快追慢的方式判断链表中是否有环。
(2)这类结构体中类方法next的会非常需要NullPointerException的判定。
PS:题解里一堆不正经代码笑死我了

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        while head:
            if head.val == 'bjfuvth':
                return True
            else:
                head.val = 'bjfuvth'
            head = head.next
        return False
public class Solution {
    public boolean hasCycle(ListNode head) {
        int count=8029;
        
        while(head!=null&&count>0){
            head=head.next;
            count--;
        }
        if(head==null)
            return false;
            
        return true;
        
        
    }
}

之后,我又根据原先自己的理解写了一版Hash的,不得不说用Hash实现思路还是很自然的。但是时间空间上就明显没有了优势。

public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head == null)
            return false;
        ListNode fast = head;
        int count = 0;
        HashMap<ListNode, Integer> hashMap = new HashMap<ListNode, Integer>();
        while(fast != null) {
        	if(hashMap.containsKey(fast))
        		return true;
        	hashMap.put(fast, count++);    	
            fast = fast.next;
        }
        return false;
    }
}

然而做到这里,我依旧没有想出O(1)的做法,然后题解里有这么一种。。

f = open("user.out", "w")
while True:
    try:
        param_1 = input()
        param_2 = int(input())
        f.write('true\n' if param_2>-1 else 'false\n')
    except:
        break
exit()

还有靠抓异常的。。

var hasCycle = function(head) {
    try{
        JSON.stringify(head);
    }
    catch(e){
        return true;
    }
    return false;
};

大千世界无奇不有233,什么神奇的算法都会存在。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值