第一周作业:
1 Two Sum2 Add Two Numbers 解题思路:
1. Two SumGiven an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
for(int i=0;i<nums.size();i++){
for(int j=0;j<i;j++){
if(nums[i]+nums[j]==target){
result.push_back(j);
result.push_back(i);
return result;
}
}
}
}
};
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
思路:此题题意比较简单,就是大数的加法。使用链表实现,当做复习链表的使用。先贴出代码:
/**
* 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 *head= new ListNode(0);
ListNode *res=head;
ListNode *t1=l1,*t2=l2;
int up = 0;
while(t1!=NULL || t2!=NULL||up>0){
ListNode *temp = new ListNode(0);
int val1 = t1?t1->val:0;
int val2 = t2?t2->val:0;
temp->val=(val1+val2+up)%10;
up=(val1+val2+up)>=10?1:0;
if(t1!=NULL)
t1=t1->next;
if(t2!=NULL)
t2=t2->next;
res->next=temp;
res=res->next;
}
return head->next;
}
};