1:两数之和
解法一:暴力求解,两次循环
解法二:改进的哈希算法,用map容器,在遍历nums数组的同时就检查是否有符合题意的解
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int,int> a;
vector<int> b(2,-1);
for(int i=0;i<nums.size();i++)
{
if(a.count(target-nums[i])>0)
{
b[0] = a[target-nums[i]];
b[1] = i;
break;
}
a[nums[i]] = i;
}
return b;
}
};
解法三:在解法二的基础上引入左右指针,缩短查找时间
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int,int> a;
vector<int> b(2,-1);
int left = 0;
int right = nums.size()-1;
while(left<=right)
{
int ln0 = nums[left];
int rn0 = nums[right];
int ln1 = target - ln0;
int rn1 = target - rn0;
if(a.count(ln1)>0)
{
b[0] = a[ln1];
b[1] = left;
break;
}
else
{
a[ln0] = left++;
}
if(a.count(rn1)>0)
{
b[0] = a[rn1];
b[1] = right;
break;
}
else
{
a[rn0] = right--;
}
}
return b;
}
};
运行时间:
2:两数相加
回忆了一下链表的用法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* prev = nullptr;
int carry = 0;
ListNode* cur = nullptr;
while(l1||l2)
{
int x1 = l1 ? l1->val : 0;
int x2 = l2 ? l2->val : 0;
int sum = x1 + x2 + carry;
carry = sum/10;
sum = sum%10;
if(!prev)
{
prev = cur = new ListNode(sum);
}
else
{
cur->next = new ListNode(sum);
cur = cur->next;
}
if(l1)
{
l1 = l1->next;
}
if(l2)
{
l2 = l2->next;
}
}
if(carry==1)
{
cur->next = new ListNode(carry);
}
return prev;
}
};