笔试-双指针算法突破

笔试-双指针算法突破

双指针技术是一种常用的算法技术,用于解决数组或链表中的问题,通常能以较低的时间复杂度解决问题。双指针可以被分为几种类型,包括对撞指针、快慢指针和滑动窗口等。这里,我将解释这些类型并提供一些示例问题及其解决方案。

1. 对撞指针

对撞指针通常用于排序数组或链表,两个指针分别从数组的起点和终点出发,向中间移动,直到它们相遇。这种方法常用于求和、查找或比较问题。

示例问题: 在有序数组中找到两个数,使它们的和为一个特定的数。

C++ 代码示例:

#include <vector>
using namespace std;

vector<int> twoSumSorted(vector<int>& nums, int target) {
    int left = 0, right = nums.size() - 1;
    while (left < right) {
        int currentSum = nums[left] + nums[right];
        if (currentSum == target) {
            return {left, right};
        } else if (currentSum < target) {
            left++;
        } else {
            right--;
        }
    }
    return {-1, -1};
}

Python 代码示例:

def two_sum_sorted(nums, target):
    left, right = 0, len(nums) - 1
    while left < right:
        current_sum = nums[left] + nums[right]
        if current_sum == target:
            return [left, right]
        elif current_sum < target:
            left += 1
        else:
            right -= 1
    return [-1, -1]

2. 快慢指针

快慢指针技术涉及两个指针以不同的速度在数组或链表中移动。这种方法常用于检测循环、找到循环的开始点或者找到中间点。

示例问题: 检测链表中是否存在环。

C++ 代码示例:

#include <iostream>

struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(nullptr) {}
};

bool hasCycle(ListNode* head) {
    ListNode* slow = head;
    ListNode* fast = head;
    while (fast != nullptr && fast->next != nullptr) {
        slow = slow->next;
        fast = fast->next->next;
        if (slow == fast) {
            return true;
        }
    }
    return false;
}

Python 代码示例:

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def has_cycle(head):
    slow, fast = head, head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow == fast:
            return True
    return False

3. 滑动窗口

滑动窗口是一种双指针技术,用于创建一个可以在数组或链表上滑动的窗口。这种方法常用于找到满足特定条件的最长或最短的子数组或子串。

示例问题: 找到含有所有字符的最短子串。

C++ 代码示例:

#include <string>
#include <unordered_map>
#include <climits>
using namespace std;

string minWindow(string s, string t) {
    unordered_map<char, int> t_count;
    for (char c : t) {
        t_count[c]++;
    }

    unordered_map<char, int> window;
    int required = t_count.size();
    int formed = 0;
    int l = 0, r = 0;
    int ans[3] = {INT_MAX, 0, 0}; // length, left, right

    while (r < s.size()) {
        char c = s[r];
        window[c]++;
        if (t_count.count(c) && window[c] == t_count[c]) {
            formed++;
        }

        while (l <= r && formed == required) {
            c = s[l];
            if (r - l + 1 < ans[0]) {
                ans[0] = r - l + 1;
                ans[1] = l;
                ans[2] = r;
            }
            window[c]--;
            if (t_count.count(c) && window[c] < t_count[c]) {
                formed--;
            }
            l++;
        }
        r++;
    }

    return ans[0] == INT_MAX ? "" : s.substr(ans[1], ans[2] - ans[1] + 1);
}

Python 代码示例:

def min_window(s, t):
    from collections import Counter
    t_count = Counter(t)
    current_count = Counter()
    
    begin, end = 0, 0
    min_len = float('inf')
    min_start = 0
    required = len(t_count)
    formed = 0
    
    while end < len(s):
        char = s[end]
        current_count[char] += 1
        
        if char in t_count and current_count[char] == t_count[char]:
            formed += 1
        
        while formed == required:
            if end - begin + 1 < min_len:
                min_len = end - begin + 1
                min_start = begin
            
            current_count[s[begin]] -= 1
            if s[begin] in t_count and current_count[s[begin]] < t_count[s[begin]]:
                formed -= 1
            begin += 1
        
        end += 1
    
    return "" if min_len == float('inf') else s[min_start:min_start + min_len]

这些示例展示了双指针技术的多样性和实用性,可以高效地解决多种类型的问题。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值