[日常刷题]leetcode第二十天

版权声明:希望各位多提意见多多互相交流哦~ https://blog.csdn.net/wait_for_taht_day5/article/details/82905614

206. Reverse Linked List

Reverse a singly linked list.
Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?

Solution in C++:

关键点:

  • 返回new head && old head->next = nullptr

思路:

  • 因为是单链表所以除了需要当前位置的指针外还需要想指向的结点以及当前结点下个结点的指针,这样只要遍历修改结点的next指针指向即可。
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        
        if (head == nullptr)
            return head;
        
        ListNode *cur = head;
        ListNode *pre = nullptr;
        
        while(cur != nullptr)
        {
            ListNode *next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
};

217. Contains Duplicate

Given an array of integers, find if the array contains any duplicates.

Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

Example 1:

Input: [1,2,3,1]
Output: true

Example 2:

Input: [1,2,3,4]
Output: false

Example 3:

Input: [1,1,1,3,3,4,3,2,4,2]
Output: true

Solution in C++:

关键点:

  • integer not digit

思路:

  • 和上次字母映射差不多,这次使用map,如果没有就添加,有就说明有重复。不要问我为什么不使用set,因为我CPPP还没看到那里。并且map里面还可以记次数,方便以后扩展。哈哈。(全都是借口)
bool containsDuplicate(vector<int>& nums) {
        map<int,int> maps;
        map<int,int>::iterator it;
        
        for(auto num : nums)
        {
            it = maps.find(num);
            if(it != maps.end())
                return true;
            else
                maps[num] = 0;
        }
        
        return false;
    }

小结

今天是补的昨天的,所以可能有些草率了,做题也不打算多做,毕竟晚上还要做(可能不是晚上)。今天主要收获就是对链表的操作又熟悉了一点。

知识点

  • 链表操作
  • map使用

猜你喜欢

转载自blog.csdn.net/wait_for_taht_day5/article/details/82905614