题目一
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> a;
for(int i=0;i<nums.size();i++)
{
for(int j=i+1;j<nums.size();j++)
{
if(nums[i]+nums[j]==target)
{
a.push_back(i);
a.push_back(j);
}
}
}
return a;
}
};
题目二
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* dummyHead=new ListNode(0);
ListNode* p=l1;
ListNode* q=l2;
ListNode* curr=dummyHead;
int carry=0;
while(p||q)
{
int x=p?p->val:0;
int y=q?q->val:0;
int sum=carry+x+y;
carry=sum/10;
curr->next=new ListNode(sum%10);
curr=curr->next;
if(p)p=p->next;
if(q)q=q->next;
}
if(carry>0)
curr->next=new ListNode(carry);
return dummyHead->next;
}
};
这次偷懒就写了两题。。。。
END