3 - Two Pointers Algorithm
Posted jenna
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了3 - Two Pointers Algorithm相关的知识,希望对你有一定的参考价值。
380. Intersection of Two Linked Lists
https://www.lintcode.com/problem/intersection-of-two-linked-lists/description?_from=ladder&&fromId=1
public ListNode getIntersectionNode(ListNode headA, ListNode headB) { // write your code here if(headA == null || headB == null) { return null; } ListNode a = headA; ListNode b = headB; while(a != b) { a = a == null ? headB : a.next; b = b == null ? headA : b.next; } return a; }
102. Linked List Cycle
https://www.lintcode.com/problem/linked-list-cycle/description?_from=ladder&&fromId=1
public boolean hasCycle(ListNode head) { // write your code here if(head == null || head.next == null) { return false; } ListNode slow = head, fast = head.next; while(slow != fast) { if(fast == null || fast.next == null) { return false; } slow = slow.next; fast = fast.next.next; } return true; }
58. 4Sum
https://www.lintcode.com/problem/4sum/description?_from=ladder&&fromId=1
public List<List<Integer>> fourSum(int[] numbers, int target) { // write your code here List<List<Integer>> result = new ArrayList<>(); if(numbers == null) { return result; } Arrays.sort(numbers); for(int i = 0; i < numbers.length - 3; i++) { if(i != 0 && numbers[i] == numbers[i - 1]) { continue; } for(int j = i + 1; j < numbers.length - 2; j++) { if(j != i + 1 && numbers[j] == numbers[j - 1]) { continue; } int left = j + 1, right = numbers.length - 1; while(left < right) { if(numbers[i] + numbers[j] + numbers[left] + numbers[right] < target) { left++; } else if(numbers[i] + numbers[j] + numbers[left] + numbers[right] > target) { right--; } else { List<Integer> curr = new ArrayList<>(); curr.add(numbers[i]); curr.add(numbers[j]); curr.add(numbers[left]); curr.add(numbers[right]); result.add(new ArrayList<>(curr)); left++; right--; while(numbers[left] == numbers[left - 1]) { left++; } while(numbers[right] == numbers[right + 1]) { right--; } } } } } return result; }
以上是关于3 - Two Pointers Algorithm的主要内容,如果未能解决你的问题,请参考以下文章