Algorithm: Two pointers

双指针一般用两个用处:

1)在排序的数组中,搜索target答案。或者在不能改变元素位置的追求最大或者最小的情况下,不用排序根据比大小追求答案(LC11)。

2) 在链表当中确定某个元素的位置。


数组搜索:

11. Container With Most Water

15. 3Sum

16. 3Sum Closest

26. Remove Duplicates from Sorted Array(这题的原理就是candy crash中某一列candies根据重力填充空格的做法)


链表确定元素:

19. Remove Nth Node From End of List


11. Container With Most Water

Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

class Solution {
    public int maxArea(int[] height) {
        int left = 0;
        int right = height.length - 1;
        int res = 0;
        while (left < right) {
            int area = Math.min(height[left], height[right]) * (right - left);
            res = area > res ? area : res;
            if (height[left] > height[right]) {
                --right;
            } else {
                ++left;
            }
        }
        return res;
    }
}


15. 3Sum

Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.


思路和下面的题目一样,只是注意去重。同样的去重问题也在4sum出现。


public class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        if(nums.length < 3 || nums == null){
            return new ArrayList<List<Integer>>();
        }
        // before using two pointer, we should sort the array in order to achieve higher efficiency
        Arrays.sort(nums);
        ArrayList<List<Integer>> return_list = new ArrayList<List<Integer>>();
        for(int i=0; i<nums.length-2; i++){
            if(i==0 || (i>0 && nums[i]!=nums[i-1])){
                int lp = i+1;
                int hp = nums.length-1;
                int target = 0 - nums[i];
                while(lp<hp){
                    if(nums[lp]+nums[hp] == target){
                        return_list.add(Arrays.asList(nums[i],nums[lp],nums[hp]));
                        while(lp<hp && nums[lp+1]==nums[lp]){
                            lp++;
                        }
                        while(lp<hp && nums[hp-1]==nums[hp]){
                            hp--;
                        }
                        lp++;
                        hp--;
                    }else if(nums[lp]+nums[hp]<target){
                        lp++;
                    }else{
                        hp--;
                    }
                }
            }
        }
        return return_list;
    }
}


16. 3Sum Closest

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:
Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).


两点:1)距离记得是绝对值;2)two pointers移动标准,必须是先比较大小,要先排序。

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        // 遍历第一个指针,另外两个指针按照一般two pointers原则
        int n = nums.length;
        Arrays.sort(nums);
        int diff = Integer.MAX_VALUE;
        int ans = Integer.MAX_VALUE;
        for (int i = 0; i < n - 2; ++i) {
            int v1 = nums[i];
            int j = i + 1;
            int k = n - 1;
            while (j < k) {
                int sum = v1 + nums[j] + nums[k];
                int curDiff = Math.abs(sum - target);
                if (curDiff < diff) {
                    diff = curDiff;
                    ans = sum;
                }
                if (sum > target) {
                    --k;
                } else if (sum < target) {
                    ++j;
                } else {
                    return ans;
                }
            }
        }
        return ans;
    }
}


26. Remove Duplicates from Sorted Array


class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums == null || nums.length < 2) {
            return (nums == null ? 0 : nums.length);
        }
        
        int n = nums.length;
        int writeIndex = 1;
        
        for (int i = 1; i < n; ++i) {
            if (nums[i] != nums[writeIndex - 1]) {
                nums[writeIndex] = nums[i];
                ++writeIndex;
            }
        }
        return writeIndex;
    }
}


19. Remove Nth Node From End of List

注意:dummy node才能处理[1] 删掉第1个的情况。

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode fast = head;
        ListNode slow = dummy;
        for (int i = 1; i < n; ++i) {
            fast = fast.next;
        }
        
        // let the snow to be the nth's prev
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        
        ListNode target = slow.next;
        slow.next = target.next;
        target.next = null;
        return dummy.next;
    }
}



猜你喜欢

转载自blog.csdn.net/Firehotest/article/details/80036594