Skip to content

双指针问题 #7

@littlemoon-zh

Description

@littlemoon-zh

双指针问题有很多变种,这里的双指针可以是从两边向中间压缩;也可以是同一侧出发,快慢指针;或者是同一侧出发,逻辑不同,导致前进速度不同;或者是从中间向两边扩散;

双指针问题一般而言,出现在有序的序列中比较多;

LeetCode 16 3Sum Closest

这里需要三个数的和,为了使用双指针,需要首先固定一个位置,然后剩下的两个数的位置使用双指针来找;此外,预处理是对数组进行排序;

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int min = Integer.MAX_VALUE;
        int res = 0;
        
        for (int i = 0; i < nums.length - 2; i++) {
            int start = i + 1;
            int end = nums.length - 1;
            int s = nums[i] - target;
            
            while (start < end) {
                int three = s + nums[start] + nums[end];
                if (three < 0) {
                    start++;
                }else if(three > 0) {
                    end--;
                }else {
                    return target;                    
                }
                
                if (Math.abs(three) < min) {
                    min = Math.abs(three);
                    res = three + target;
                }
            }
        }
        
        return res;
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions