简单介绍
双指针法是一种常用的算法技巧,通常用于数组或链表等数据结构的问题求解。它使用两个指针在数据结构中移动,根据问题的要求调整指针的移动方式和位置,以达到高效解决问题的目的。
应用示例
下面是双指针法的两种常见应用场景及示例:
快慢指针
- 场景:用于解决链表中的问题,如判断链表是否存在环、找到环的起始位置、找到链表的中间节点等。
- 示例:判断链表是否存在环。给定一个链表,判断链表中是否存在环。例如,对于链表:1 -> 2 -> 3 -> 4 -> 2,可以使用快慢指针的方法来解决。
#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 && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
return true;
}
return false;
}
// 示例链表
// 1 -> 2 -> 3 -> 4 -> 2
int main() {
ListNode* node1 = new ListNode(1);
ListNode* node2 = new ListNode(2);
ListNode* node3 = new ListNode(3);
ListNode* node4 = new ListNode(4);
node1->next = node2;
node2->next = node3;
node3->next = node4;
node4->next = node2;
bool hasCycleResult = hasCycle(node1);
std::cout << std::boolalpha << hasCycleResult << std::endl; // 输出:true
delete node1;
delete node2;
delete node3;
delete node4;
return 0;
}
左右指针
- 场景:用于解决数组或字符串中的问题,如在有序数组中查找目标元素、求解两数之和等。
- 示例:在有序数组中查找目标元素。给定一个有序数组和目标元素,要求在数组中找到目标元素的位置(若存在)。
#include <iostream>
#include <vector>
int binarySearch(std::vector<int>& nums, int target) {
int left = 0;
int right = nums.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target)
return mid;
else if (nums[mid] < target)
left = mid + 1;
else
right = mid - 1;
}
return -1;
}
// 示例有序数组
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
int main() {
std::vector<int> nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int target = 7;
int searchResult = binarySearch(nums, target);
std::cout << searchResult << std::endl; // 输出:6
return 0;
}
文章小结
以上示例展示了双指针法在解决链表和数组问题时的应用。具体问题和使用方式可能因情况而异,但双指针法的思想是通过两个指针在数据结构中移动,以高效地解决问题。