算法设计作业1

第一周作业:

1 Two Sum
2 Add Two Numbers 

解题思路:

1. Two Sum

Given 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].

思路:由于输入数组是无序的,所以只有按一定顺序来进行遍历。想到了两种方法,其一是首先将第一个数与其余的每个数相加判断是否等于target,再从第二个数开始,与剩余的数相加来判断,另一种是将第一个数拿出来,再将第2个数拿出来,再将第3个数拿出来与前两个中的每个分别相加,再将第4个数拿出来与前3个中的每个分别相加。但实际上这两种的复杂度是一样的。考虑如下几种情况:
[a b c d e f g],target是c和d的和。对于这种情况,第2种方法明显会比较次数更少;
[a b c d e f g],target是a和g的和。对于这种情况,第1种方法比较次数更少;
[a b c d e f g],target是 f和g的和。对于这种情况,两种方法比较次数相同。

现在给出第2种方法的代码:

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;
                }
            }
        }
    }
};

2. Add Two Numbers

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;
    }
};

首先创建一个头节点,用来指向result链表的头。将传入的链表l1和l2 copy为t1和t2。声明进位变量up初始化为0。
循环条件是两个加数链表不都为空,或最高位存在进位。
每次循环时,new一个节点用来存储当前数位的和,并链到result链表上。
使用一个int变量来存储加数链表的值,这样不用频繁地访问链表,并且只用判断一次当前加数链表是否为空。(若为空时,将该值设为0)。
temp的值为两个加数与前一位进位的和对10取余,up的值为判断是否大于10。
最终返回头节点所指向的result链表。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值