链表有环判断,快慢指针两种方法/合并链表/删除重复元素/二分递归和while
2017-06-08 12:31
381 查看
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; }
相关文章推荐
- LintCode刷题阶段性总结---链表容易篇(翻转链表,删除链表重复元素,合并两个排序链表等)
- 两种方法删除ArrayList里重复元素
- 程序员面试题目总结--数组(一)【递归求数组所有元素和、用一个for循环打印出一个二维数组、用递归判断数组是否是递增、有序数组中删除重复元素】
- 两种方法删除ArrayList里重复元素
- 删除链表中的元素//p=pre;//重复的1-1,要判断重复判读。hh->next=head;//头上加头,不用考虑链表换头
- 集合ArrayList中删除重复元素两种方法
- 两种方法删除ArrayList里重复元素
- 删除一堆数据中重复数据的两种方法(单链表与线性表)c++
- [LeetCode]Merge Two Sorted Lists & Remove Duplicates from Sorted List 两个有序链表合并为一个&删除链表重复元素
- 两种方法删除ArrayList里重复元素
- 两种方法删除ArrayList里重复元素
- 山东理工OJ【2122】数据结构实验之链表七:单链表中重复元素的删除(两种思想)
- 两种方法删除ArrayList里重复元素
- 用索引删除数组元素,防止删除元素对索引造成干扰的两种解决方法
- 字符串的转换、逆置、删除重复元素及判断是否为邮件格式
- oracle中判断某列是否为数字,删除重复数据的方法
- Javascript数组删除重复元素的方法
- 链表表示删除重复元素
- 用Linq快速删除重复的元素的方法
- Map遍历的两种方式(首推entrySet())--遍历Map时删除元素的方法