160.相交链表
题目链接
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ios::sync_with_stdio(false);
if(!(headA&&headB))return NULL;
ListNode *p1 = headA,*p2 = headB;
while(p1 != p2){
p1 = p1->next;
p2 = p2->next;
if(p1==NULL && p2 == NULL)return NULL;
if(p1 == NULL) p1 = headB;
if(p2 == NULL) p2 = headA;
}
return p1;
}
};
167.两数之和 II - 输入有序数组
题目链接
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int l=0,r=numbers.size()-1,sum;
while(l < r){
sum = numbers[l] + numbers[r];
if(sum == target)break;
if(sum < target)l++;
else if(sum >target)r--;
}
return {l+1,r+1};
}
};

本文解析了两个经典算法问题:寻找两链表相交节点及在有序数组中寻找两个数使它们的和为目标值。通过巧妙的双指针技巧,解决了链表相交问题;利用双指针法,在O(n)时间内找到了有序数组中的目标和。文章深入浅出,适合算法初学者。
1516

被折叠的 条评论
为什么被折叠?



