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;
    }

 

posted @ 2019-05-19 00:34  Jenna777  阅读(104)  评论(0编辑  收藏  举报