1.相交链表
编写一个程序,找到两个单链表相交的起始节点。
注意:如果两个链表没有交点,返回 null.在返回结果后,两个链表仍须保持原有的结构。可假定整个链表结构中没有循环。程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存。
思路:指针 pA 指向 A 链表,指针 pB 指向 B 链表,依次往后遍历,如果 pA 到了末尾,则 pA = headB 继续遍历,如果 pB 到了末尾,则 pB = headA 继续遍历,比较长的链表指针指向较短链表head时,长度差就消除了,如果有交点,那么第二次经过交点时两个指针相遇。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(headB == NULL || headA == NULL)
return NULL;
ListNode *PA = headA;
ListNode *PB = headB;
while(PA!=PB)
{
if(PA == NULL)
PA = headB;
else if(PB == NULL)
PB = headA;
else
{
PA = PA->next;
PB = PB->next;
}
}
return PA;
}
};
参考链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
2. 两数之和 II - 输入有序数组
给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
说明:返回的下标值(index1 和 index2)不是从零开始的。你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
思路:同第一题两数之和,哈希表方法。将数组的值作为键,数组的下标作为值。
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
map<int,int> a;
vector<int> b(2,-1);
for(int i=0;i<numbers.size();i++)
{
if(a.count(target-numbers[i])>0)
{
b[0] = a[target-numbers[i]] + 1;
b[1] = i+1;
break;
}
a[numbers[i]] = i;
}
return b;
}
};
思路2:定义两个指针,一个指向头,一个指向尾,如果当前值小于目标值,那么头指针+1(向右移),如果当前值大于目标值,那么尾指针-1(向左移)。如此迭代即。
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int i = 0, j = numbers.size()-1;
while(i < j)
{
int sum = numbers[i] + numbers[j];
if(sum == target)
return {i+1,j+1};
else if(sum < target)
++i;
else
--j;
}
return {-1,-1};
}
};
参考链接:https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/solution/