Leetcode 对撞指针

问题特征

该类问题特点为最优解由数组上的两个位置A和B对应的值的某种关系构成(如:和为某值)。这类问题可以首先在数组两端分别设立两个指针,当其中一个满足某种条件的指针(如:A对应的值大于B指针对应值)固定时,另一指针无论如何改变都无法得到更优解,此时只能改变指针A的位置来搜索更优解。

Leetecode 167

167.Two Sum II - Input array is sorted
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
Example 1:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.

  • 思路:
    由于数组已经升序排列,所以当和数较大时,右移left指针;反之,左移right指针。
vector<int> twoSum(vector<int>& numbers, int target) {
    int left = 0;
    int right = numbers.size() - 1;
    while (left < right) {
        int sum = numbers[left] + numbers[right];
        if (sum == target) {
            int res_arr[] = {left + 1, right + 1};
            vector<int> res(res_arr, res_arr + 2);
            return res;
        } else if (sum < target) {
            left++;
        } else {
            right--;
        }
    }
    // no solution
    throw invalid_argument("The input has no solution!");
}

Leetcode 125

125. Valid Palindrome
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: “A man, a plan, a canal: Panama”
Output: true

  • 思路:
    使用对撞指针,注意点为isalnum()函数和toupper()tolower()函数的使用,时问题简化。
bool isPalindrome(string s) {
    int left = 0;
    int right = s.length() - 1;
    while (left < right) {
        if (!isalnum(s.at(left))) {
            left++;
            continue;
        }
        if (!isalnum(s.at(right))) {
            right--;
            continue;
        }
        if (tolower(s.at(left)) != tolower(s.at(right)))
            return false;
        left++;
        right--;
    }
    return true;
}

Leetcode 345

345. Reverse Vowels of a String
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Input: “hello”
Output: “holle”

  • 思路
    使用对撞指针方法,注意set对象的使用。
set<char> vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}; 
string reverseVowels(string s) {
    int low = 0;
    int high = s.length() - 1;
    int start = low;
    int end = high;
    while (true) {
        while (start <= high && vowels.find(s.at(start)) == vowels.end()) start++;
        while (end >= low && vowels.find(s.at(end)) == vowels.end()) end--;
        if (start >= end) break;
        swap(s.at(start++), s.at(end--));
    }
    return s;

Leetcode 11

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 the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.
Notice that you may not slant the container.
Example 1:
在这里插入图片描述
Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

  • 思路
    本题使用对撞指针,当固定最小一条边时,移动另一边并不能增加体积,无法获得更优解,所以符合对撞指针特征。
int area(vector<int>& height, int left_idx, int right_idx) {
    int h = height[left_idx] < height[right_idx] ? height[left_idx] : height[right_idx];
    int area = h * (right_idx - left_idx);
    return area;
}
int maxArea(vector<int>& height) {
    int low = 0;
    int high = height.size() - 1;
    int left = low;
    int right = high;
    int maxArea = area(height, left, right);
    while (left < right) {
        height[left] < height[right] ? left++ : right--;
        int tempArea = area(height, left, right);
        if (tempArea > maxArea)
            maxArea = tempArea;
    }
    return maxArea;

Leetcode 16

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 1:
Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

  • 思路:
  1. 排序,目的是使用对撞指针;
  2. 固定一个数,将该问题转化为2Sum问题,使用对撞指针来解决;
  3. 首先寻找最接近的3数字和,然后根据距离对指针进行移动;
int my_abs(int num) {
    return num < 0 ? -num : num;
}
int threeSumClosest(vector<int>& nums, int target) {
    sort(nums.begin(), nums.end());
    int res = nums[0] + nums[1] + nums[2]; // init
    for (int i = 0; i < nums.size() - 2; ++i) {
        int left = i + 1;
        int right = nums.size() - 1;
        while (left < right) {
            int tmp = nums[i] + nums[left] + nums[right];
            if (my_abs(tmp - target) < my_abs(res - target)) {
                res = tmp;
            }
            if (tmp > target)
                --right;
            else if (tmp < target)
                ++left;
            else
                return tmp;
        }
    }
    return res;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值