京东Java后端开发面试算法题(实习)
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||head.next==null){
// return false;
// }
// ListNode slow = head;
// ListNode fast = head.next;
// while(slow!=fast){
// if(fast==null||fast.next==null){
// return false;
// }
// slow = slow.next;
// fast = fast.next.next;
// }
// return true;
// }
//方法二:哈希表
public boolean hasCycle(ListNode head){
Set<ListNode> nodesSeen = new HashSet<>();
while (head != null) {
if (nodesSeen.contains(head)) {
return true;
} else {
nodesSeen.add(head);
}
head = head.next;
}
return false;
}
}
2.环形链表II
返回链表开始入环的第一个节点
public class Solution {
// public ListNode detectCycle(ListNode head) {
// Set<ListNode> visted = new HashSet<ListNode>();
// ListNode node = head;
// while(node!=null){
// if(visted.contains(node)){
// return node;
// }
// visted.add(node);
// node = node.next;
// }
// return null;
// }
//https://leetcode-cn.com/problems/linked-list-cycle-ii/solution/linked-list-cycle-ii-kuai-man-zhi-zhen-shuang-zhi-/
//双指针解决思路
public ListNode detectCycle(ListNode head){
ListNode fast = head,slow = head;
while(true){
if(fast==null||fast.next==null)
return null;
fast = fast.next.next;
slow = slow.next;
if(fast==slow)
break;
}
fast = head;
while(slow!=fast){
slow=slow.next;
fast=fast.next;
}
return slow;
}
}