[日常刷题]leetcode第二十天

本文介绍了如何使用C++实现链表的迭代和递归反转,以及通过map检测数组中是否存在重复元素的方法。详细解析了链表反转的算法思路和关键点,并提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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使用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值