LeetCode 题解

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;

    }
};

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值