标签 Easy 下的文章

题目链接:反转链表

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

方法一:反转链表
/**

  • 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* reverseList(ListNode* head) {
    if (head == NULL || head->next == NULL) return head;
    ListNode* ans;
    ans = nullptr;
    while (head) {
        ListNode* t = head->next;
        head->next = ans;
        ans = head;
        head = t;
    }
    return ans;
}

};

题目链接:相交链表

给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。

方法一:哈希表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        unordered_set<ListNode *> m;
        while (headA) {
            m.insert(headA);
            headA = headA->next;
        }
        while (headB) {
            if (m.count(headB)) {
                return headB;
            }
            headB = headB->next;
        }
        return NULL;
    }
};

题目链接:搜索插入位置

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。

方法:二分查找

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int l = -1,r = nums.size();
        while (l+1 < r) {
            int mid = (l+r)/2;
            if (nums[mid] == target) return mid;
            else if(nums[mid] < target) l = mid;
            else r = mid;
        }
        return r;
    }
};

题目链接:两数之和

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案,并且你不能使用两次相同的元素。

你可以按任意顺序返回答案。

方法一:暴力枚举

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> ans;
        for (int i = 0;i < nums.size();i++) {
            for (int j = i+1;j < nums.size();j++) {
                if (nums[i] + nums[j] == target) {
                    ans.push_back(i);
                    ans.push_back(j);
                    return ans;
                }
            }
        }
        return ans;
    }
};

方法二:哈希表

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int,int> hashtable;
        for (int i = 0;i < nums.size();i++) {
            auto t = hashtable.find(target-nums[i]);
            if (t != hashtable.end()) {
                return {t->second,i};
            }
            hashtable[nums[i]] = i;
        }
        return {};
    }
};