LeetCode刷题日记(Day1)

Problem 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.

  • 解题思路:

  1. 定义map<int, int>变量m,对传入的nums进行遍历,并将遍历过的nums[i]存入到m当中。
  2. 定义变量temp,对nums再进行一次遍历,将target - nums[i]赋值给temp,并判断temp是否在m中已有。如果有,则找到解。
  • 时间复杂度分析:
    由于对nums进行一次遍历的代价为O(n),且每个nums[i]在m中是hash储存,故在判断temp是否在m中已有的代价为O(1),即总的时间复杂度为O(n)。

  • 代码实现

class Solution{
public:
	vector<int> twoSum(vector<int>& nums, int target){
		map<int, int> m;
		vector<int> res;
		for (int i = 0; i < nums.size(); ++i)
			m[nums[i]] = i;
		for (int i = 0; i < nums.size(); ++i){
			int temp = target - nums[i];
			if (m.count(temp) && m[temp] != i){
				res.push_back(i);
				res.push_back(m[temp]);
				break;
			}
		}
		return res;
	}
};

Problem 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.

  • 解题思路

  1. 定义int变量carry,将其初始化为0,表示进位。
  2. 定义ListNode* 变量l3,将其初始化为节点ListNode(0),用于存储结果。
  3. 对l1和l2进行遍历,将它们相同位置节点的val(节点不存在则val当作0)与carry求和,并为l3创建下一个节点用来存储计算结果,同时更新carry。
  4. 当l1和l2都遍历完毕后,若carry为1,则为l3创建下一个节点,其val为1。
  • 代码实现
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int carry = 0;
        ListNode *l3 = new ListNode(0);
        ListNode *p1 = l1, *p2 = l2, *p3 = l3;
        while(p1 != NULL && p2 != NULL){
            carry = p1->val + p2->val + carry;
            p3->next = new ListNode(carry % 10);
            carry /= 10;
            p1 = p1->next;
            p2 = p2->next;
            p3 = p3->next;
        }
        while(p1 != NULL){
            carry += p1->val;
            p3->next = new ListNode(carry % 10);
            carry /= 10;
            p1 = p1->next;
            p3 = p3->next;
        }
        while(p2 != NULL){
            carry += p2->val;
            p3->next = new ListNode(carry % 10);
            carry /= 10;
            p2 = p2->next;
            p3 = p3->next;
        }
        if (carry != 0){
            p3->next = new ListNode(1);
        }
        l3 = l3->next;

        return l3;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_36348299/article/details/88259189