Leetcode 双指针算法题目详解

167. Two Sum II - Input array is sorted

Easy

1019423FavoriteShare

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.

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.

Note:

  • Your returned answers (both index1 and index2) are not zero-based.
  • You may assume that each input would have exactly one solution and you may not use the same element twice.

Example:

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.

数组已经排序,标准的一首一尾双指针

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        vector<int> res;
        int left=0, right= numbers.size()-1;
        while(left<right){
            if(numbers[left]+numbers[right]>target){
                right--;
            }
            else if(numbers[left]+numbers[right]<target){
                left++;
            }
            else{
                res.push_back(left+1);
                res.push_back(right+1);
                left++;
                right--;
            }
        }
        return res;
    }
};

88. Merge Sorted Array

Easy

12422986FavoriteShare

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:

  • The number of elements initialized in nums1 and nums2 are m and n respectively.
  • You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.

Example:

Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6],       n = 3

Output: [1,2,2,3,5,6]

数组原地归并空间足够,需要从后往前归并

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int i=m-1, j = n-1, k = m+n-1;
        while(k>=0){
            if(i<0){
                nums1[k--] = nums2[j--];
            }
            else if(j<0){
                nums1[k--] = nums1[i--];
            }
            else if(nums1[i]>nums2[j]){
                nums1[k--] = nums1[i--];
            }
            else{
                nums1[k--] = nums2[j--];
            }
        }
    }
}

26. Remove Duplicates from Sorted Array

Easy

Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

标准的双指针算法

func removeDuplicates(nums []int) int {
    j:=0
    for i:=1;i<len(nums);i++{
        if nums[i]!=nums[j]{
            j++
            nums[j]=nums[i]
        }
    }
    return j+1
}

76. Minimum Window Substring

Hard

Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

Example:

Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"

Note:

  • If there is no such window in S that covers all characters in T, return the empty string "".
  • If there is such window, you are guaranteed that there will always be only one unique minimum window in S.

这道题目使用滑动窗口加哈希表,其中判断窗口中是否包含所有字符有一定技巧。

class Solution {
public:
    string minWindow(string s, string t) {
        string res = "";
        int len = s.size();
        int num = 0;
        unordered_map<char,int> mp;
        for(auto c:t) mp[c]++;
        for(int i=0,j=0;i<s.size();i++){
            while(j<s.size()&&num<t.size()){
                mp[s[j]]--;
                if(mp[s[j]]>=0){
                    num++;
                }
                j++;
            }
            if(num == t.size() && j-i<=len){
                len = j-i;
                res = s.substr(i,j-i);
            }
            mp[s[i]]++;
            if(mp[s[i]]>0){
                num--;
            }
        }
        return res;
    }
};

239. Sliding Window Maximum

Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.

Example:

Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7] 
Explanation: 

Window position                Max
---------------               -----
[1  3  -1] -3  5  3  6  7       3
 1 [3  -1  -3] 5  3  6  7       3
 1  3 [-1  -3  5] 3  6  7       5
 1  3  -1 [-3  5  3] 6  7       5
 1  3  -1  -3 [5  3  6] 7       6
 1  3  -1  -3  5 [3  6  7]      7

Note: 
You may assume k is always valid, 1 ≤ k ≤ input array's size for non-empty array.

 

这道题使用一个双端队列deque,为了出队方便,里面存储的下标。

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        deque<int> q;
        vector<int> res;
        //int n = nums.size();
        for(int i=0;i<nums.size();i++){
            while(!q.empty() && i-k>=q.front()){
                q.pop_front();
            }
            while(!q.empty() && nums[i]>=nums[q.back()]){
                q.pop_back();
            }
            q.push_back(i);
            if(i>=k-1){
                res.push_back(nums[q.front()]);
            }
        }
        return res;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值