首页 > 其他分享 >LeetCode

LeetCode

时间:2023-08-19 23:12:28浏览次数:35  
标签:head return int next ans ListNode LeetCode

字符串

左旋转字符串

剑指 Offer 58 - II. 左旋转字符串

  • 申请空间,取模运算
class Solution {
public:
    string reverseLeftWords(string s, int n) {
        string ans=s;
        for(int i=0;i!=s.size();++i)
        {
            ans[(i-n+s.size())%s.size()]=s[i];
        }
        return ans;
    }
};
  • 子串合并
class Solution {
public:
    string reverseLeftWords(string s, int n) {
        return s.substr(n,s.size()-n)+s.substr(0,n);
    }
};

状态机

剑指 Offer 20. 表示数值的字符串
剑指 Offer 67. 把字符串转换成整数

链表

反转

剑指 Offer 06. 从尾到头打印链表

  • 头插法
class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        ListNode* h = new ListNode;
        while(head)
        {
            auto temp = h->next;
            h->next=head;

            auto next = head->next;
            head->next=temp;

            head=next;
        }

        vector<int>ans;
        h=h->next;
        while(h)
        {
            ans.push_back(h->val);
            h=h->next;
        }
        return ans;
    }
};
class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        deque<ListNode*>que;
        while(head) 
        {
            que.push_back(head);
            head=head->next;
        }
        vector<int> ans;
        while(!que.empty())
        {
            ans.push_back(que.back()->val);
            que.pop_back();
        }
        return ans;
    }
};
  • 递归
class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        if(!head) return {};
        auto temp = reversePrint(head->next);
        temp.push_back(head->val);
        return temp;
    }
};

剑指 Offer 24. 反转链表

  • 头插法
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* h = new ListNode;
        while(head)
        {
            auto hnext = h->next;
            auto headnext = head->next;
            h->next=head;
            head->next=hnext;
            head=headnext;
        }
        return h->next;
    }
};
  • 递归
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(!head || !head->next) return head;

        auto h = reverseList(head->next);
        head->next->next=head;
        head->next=nullptr;
        return h;
    }
};
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(!head)return head;

        deque<ListNode*>que;
        while(head)
        {
            que.push_back(head);
            head=head->next;
        }

        ListNode* ans = nullptr;
        ans = que.back();
        que.pop_back();
        auto p =ans;
        while(!que.empty())
        {
            p->next=que.back();
            p=p->next;
            que.pop_back();
        }
        p->next = nullptr;
        return ans;
    }
};

复杂链表复制

剑指 Offer 35. 复杂链表的复制

  • 拼接拆分
class Solution {
public:
    Node* copyRandomList(Node* head) {
        if(!head)
            return nullptr;
        for(Node* i=head;i!=nullptr;i=i->next->next)
        {
            Node* newNode = new Node(i->val);
            newNode->next=i->next;
            i->next=newNode;
        }
        for(Node*i=head;i!=nullptr;i=i->next->next)
        {
            i->next->random=(i->random==nullptr)?nullptr:i->random->next;
        }
        Node* outNode = head->next;
        for(Node*i=head;i!=nullptr;i=i->next)
        {
            Node* newNode = i->next;
            i->next=newNode->next;
            newNode->next=(newNode->next==nullptr)?nullptr:newNode->next->next; 
        }
        return outNode;
    }
};

双指针

删除链表节点

剑指 Offer 18. 删除链表的节点

class Solution {
public:
    ListNode* deleteNode(ListNode* head, int val) {
        ListNode* h = new ListNode;
        h->next = head;
        auto pre = h;
        while(head)
        {
            if(head->val == val)
            {
                pre->next=head->next;
                return h->next;
            }
            pre=pre->next;
            head=head->next;
        }
        return h->next;
    }
};

链表中倒数第k个节点

剑指 Offer 22. 链表中倒数第k个节点

class Solution {
public:
    ListNode* getKthFromEnd(ListNode* head, int k) {
        auto p1=head;
        for(int i=0;i!=k;++i) p1=p1->next;
        auto p2 = head;
        while(p1)
        {
            p1=p1->next;
            p2=p2->next;
        }
        return p2;
    }
};

合并有序链表

剑指 Offer 25. 合并两个排序的链表

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode* head = new ListNode;
        auto p =head;
        while(l1 && l2)
        {
            if(l1->val<l2->val)
            {
                p->next = l1;
                p=p->next;
                l1=l1->next;
            }
            else
            {
                p->next = l2;
                p=p->next;
                l2=l2->next;
            }
        }
        if(l1)
        {
            p->next = l1;
        }
        if(l2)
        {
            p->next = l2;
        }
        return head->next;
    }
};

两个链表的第一个公共节点

剑指 Offer 52. 两个链表的第一个公共节点

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        auto p1=headA;
        auto p2=headB;
        while(p1!=p2)
        {
            p1=p1?p1->next:headA;
            p2=p2?p2->next:headB;
        }
        return p1;
    }
};

调整数组顺序使奇数位于偶数前面

剑指 Offer 21. 调整数组顺序使奇数位于偶数前面

class Solution {
public:
    vector<int> exchange(vector<int>& nums) {
        int l=0;
        int r=nums.size()-1;
        while(l<r)
        {
            while(l<r && nums[l]%2==1) ++l;
            while(l<r && nums[r]%2==0) --r;
            swap(nums[l],nums[r]);
        }
        return nums;
    }
};

和为s的两个数字

剑指 Offer 57. 和为s的两个数字

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

翻转单词顺序

剑指 Offer 58 - I. 翻转单词顺序

class Solution {
public:
    string reverseWords(string s) {
        if(s.empty()) return s;
        int i=s.size()-1;
        int j=s.size()-1;
        while(i>=0 && s[i]==' ') 
        {
            --i;--j;
        }
        string ans;
        while(j>=0)
        {
            while(i>=0 && s[i]!=' ') --i;
            ans+=s.substr(i+1,j-i);
            ans+=" ";
            while(i>=0 && s[i]==' ') --i;
            j=i;
        }
        if(!ans.empty()) ans.pop_back();
        return ans;
    }
};

栈与队列

辅助栈

剑指 Offer 09. 用两个栈实现队列

class CQueue {
public:
    stack<int>q1;
    stack<int>q2;
    CQueue() {

    }
    
    void appendTail(int value) {
        q2.push(value);
    }
    
    int deleteHead() {
        if(!q1.empty()) 
        {
            auto ans = q1.top();
            q1.pop();
            return ans;
        }
        while(!q2.empty())
        {
            q1.push(q2.top());
            q2.pop();
            
        }
        if(!q1.empty()) 
        {
            auto ans = q1.top();
            q1.pop();
            return ans;
        }
        else
        {
            return -1;
        }
    }
};

剑指 Offer 30. 包含min函数的栈

class MinStack {
public:
    /** initialize your data structure here. */
    stack<int>que;
    stack<int>minque;
    MinStack() {
        minque.push(INT_MAX);
    }
    
    void push(int x) {
        que.push(x);
        minque.push(minque.top()<x?minque.top():x);
    }
    
    void pop() {
        que.pop();
        minque.pop();
    }
    
    int top() {
        return que.top();
    }
    
    int min() {
        return minque.top();
    }
};

剑指 Offer 59 - I. 滑动窗口的最大值

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        deque<int>que;
        vector<int> ans;
        for(int i=0;i!=nums.size();++i)
        {
            while(!que.empty() && que.back()<nums[i]) que.pop_back();
            que.push_back(nums[i]);

            if(i>=k && que.front()==nums[i-k]) que.pop_front();
            if(i>=k-1) ans.push_back(que.front());
        }
        return ans;

    }
};

剑指 Offer 59 - II. 队列的最大值

class MaxQueue {
public:
    deque<int>que;
    deque<int>maxque;
    MaxQueue() {
    }
    
    int max_value() {
        if(que.empty())return -1;
        return maxque.front();
    }
    
    void push_back(int value) {
        while(!maxque.empty() && maxque.back()<value) maxque.pop_back();
        maxque.push_back(value);
        que.push_back(value);
    }
    
    int pop_front() {
        if(que.empty()) return -1;
        if(maxque.front()==que.front()) maxque.pop_front();
        auto ans = que.front();
        que.pop_front();
        return ans;
    }
};

模拟

顺时针打印矩阵

剑指 Offer 29. 顺时针打印矩阵

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        if(matrix.empty())return {};
        int l=0,r=matrix[0].size()-1,up=0,down=matrix.size()-1;
        vector<int>ans;
        while(l<=r && up<=down)
        {
            for(int i=l;i<=r;++i)
            {
                ans.push_back(matrix[up][i]);
            }
            if(++up>down) break;
            for(int i=up;i<=down;++i)
            {
                ans.push_back(matrix[i][r]);
            }
            if(--r<l)break;
            for(int i=r;i>=l;--i)
            {
                ans.push_back(matrix[down][i]);
            }
            if(--down<up)break;
            for(int i=down;i>=up;--i)
            {
                ans.push_back(matrix[i][l]);
            }
            if(++l>r)break;
        }
        return ans;
    }
};

栈的压入、弹出序列

剑指 Offer 31. 栈的压入、弹出序列

class Solution {
public:
    bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
        stack<int>que;
        int i=0;
        for(auto num:pushed)
        {
            que.push(num);
            while(i<popped.size() && !que.empty() && popped[i]==que.top())
            {
                ++i;
                que.pop();
            }
        }
        return que.empty();
    }
};

查找

标签:head,return,int,next,ans,ListNode,LeetCode
From: https://www.cnblogs.com/etherovo/p/17643049.html

相关文章

  • leetcode: TC of top-down memorization
    exampletoexplainhowtocalculateTimeComplexitythememosizemeanseachstatewillbecalculatedonlyoncehowabouttheTCineachstate? classSolution{publicbooleanwordBreak(Strings,List<String>wordDict){returndfs(s,w......
  • #yyds干货盘点# LeetCode程序员面试金典:是子序列
    1.简述:给定字符串s 和t,判断 s 是否为 t 的子 序列。字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,是的一个子序列,而不是)。"ace""abcde""aec"进阶:如果有大量输入的S,称作S1,S2,...,Sk其中k>=10亿,你需要依次......
  • #yyds干货盘点# LeetCode程序员面试金典:最大正方形
    题目:在一个由 '0' 和 '1' 组成的二维矩阵内,找到只包含 '1' 的最大正方形,并返回其面积。 示例1:输入:matrix=[["1","0","1","0","0"],["1","0","1","1","1"],["1&qu......
  • leetcode2235 两整数相加
    题目描述:(这第一种方法我就不多说了,肯定是有手就行)给你两个整数num1和num2,返回这两个整数的和。示例1:输入:num1=12,num2=5输出:17解释:num1是12,num2是5,它们的和是12+5=17,因此返回17。示例2:输入:num1=-10,num2=4输出:-6解释:num1+num2=-6,因此返......
  • Leetcode 146 LRUCache
    /***Copyright(C)2023-08-1813:51zxinlog<[email protected]>**/#include<func.h>#defineN1000//普通NodetypedefstructNode{intkey;intvalue;structNode*prev;structNode*next;}Node;//定义HashNodetyped......
  • LeetCode 1020.飞地的数量
    1.题目:给你一个大小为 mxn 的二进制矩阵 grid ,其中 0 表示一个海洋单元格、1 表示一个陆地单元格。一次 移动 是指从一个陆地单元格走到另一个相邻(上、下、左、右)的陆地单元格或跨过 grid 的边界。返回网格中 无法 在任意次数的移动中离开网格边界的陆地单元格的数......
  • 【LeetCode1384. 按年度列出销售总额】MySQL使用with recursive根据开始日期和结束日
    题目地址https://leetcode.cn/problems/total-sales-amount-by-year/description/代码WITHRECURSIVEDateSeriesAS(SELECTproduct_id,period_startASsale_date,period_end,average_daily_salesFROMSales--Assumingyourtablenameissales_dataUN......
  • 【LeetCode2199. 找到每篇文章的主题】字符串处理题,使用MySQL里的group_concat和LOCAT
    题目地址https://leetcode.cn/problems/finding-the-topic-of-each-post/description/代码witht1as(selectp.*,k.*fromPostspleftjoinKeywordskonLOCATE(LOWER(CONCAT('',word,'')),LOWER(CONCAT('',conte......
  • Leetcode 142. 环形链表II(Linked list cycle ii)
    题目链接给定一个链表的头节点head,返回链表开始入环的第一个节点。.如果链表无环,则返回null.如果链表中有某个节点,可以通过连续跟踪next指针再次到达,则链表中存在环.为了表示给定链表中的环,评测系统内部使用整数pos来表示链表尾连接到链表中的位置(索引从0开始).......
  • 【LeetCode2118. 建立方程】 group_concat指定分隔符,指定排序顺序
    目录题目地址题目描述代码题目地址https://leetcode.cn/problems/build-the-equation/description/题目描述Example2:输入:Terms表:+-------+--------+|power|factor|+-------+--------+|4|-4||2|1||1|-1|+-------+---......