public static boolean hasCycle(ListNode head) { if (head == null || head.next == null) { return false; } ListNode slow = head; ListNode fast = head.next; while (slow != fast) { if (slow.next == null) return false; slow = slow.next; if (fast.next == null) return false; if (fast.next.next == null) return false; fast = fast.next.next; } return true; } public static boolean hasCycle1(ListNode head) { if (head == null || head.next == null) { return false; } ListNode slow = head; ListNode fast = head.next; while (fast.next != null) { if (slow == fast) { return true; } slow = slow.next; if (fast.next.next == null){ return false; } fast = fast.next.next; } return false; }
public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode result = new ListNode(0); ListNode head1 = l1; ListNode head2 = l2; ListNode resultPoint = result; while (head1 != null && head2 != null) { if (head1.val <= head2.val) { ListNode currNode1 = new ListNode(head1.val); resultPoint.next = currNode1; resultPoint = resultPoint.next; head1 = head1.next; } else { ListNode currNode2 = new ListNode(head2.val); resultPoint.next = currNode2; resultPoint = resultPoint.next; head2 = head2.next; } } if (head1 != null) { resultPoint.next = head1; } if (head2 != null) { resultPoint.next = head2; } return result.next; } }
public static ListNode deleteDuplicates(ListNode head) { if (head == null || head.next == null) { return head; } ListNode pre = head; ListNode curr = head.next; while (curr != null) { if (curr.val == pre.val) { pre.next = curr.next; } else { pre = pre.next; } curr = curr.next; } return head; }
public static boolean binarySearchDigui(int[] array, int start, int end, int val){ if (start >= end) { return false; } int mid = start + (end - start) / 2; if (val < array[mid]) { return binarySearchDigui(array, start, mid, val); } else if (val > array[mid]){ return binarySearchDigui(array, mid + 1, end, val); } else { return true; } } public static boolean binarySearchWhile(int[] array, int start, int end, int val){ while (start < end) { int mid = start + (end - start) / 2; if (val < array[mid]) { end = mid; } else if (val > array[mid]){ start = mid + 1; } else { return true; } } return false; }
时间: 2024-10-14 22:15:50