leetcode算法刷题记录---5

二叉树的右视图(leetcode199)

C++

#include <vector>
#include <queue>
using namespace std;
// 二叉树的右视图
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;

    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    vector<int> rightSideView(TreeNode *root) {
        vector<int> ans;
        if(root== nullptr) return ans;
        queue<TreeNode*>q;
        q.push(root);
        while (!q.empty()){
            int layer_len = q.size();
            for(int i=0;i<layer_len;i++){
                TreeNode *data = q.front();
                if(data->left) q.push(data->left);
                if(data->right) q.push(data->right);
                if(i==layer_len-1) ans.push_back(data->val);
                q.pop();
            }
        }
        return ans;
    }
};

Python

from typing import Optional,List
# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution:
    def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
        if not root:
            return []
        ans = []
        # 定义一个队列,进行层序遍历
        item = [root]
        while item:
            layer_length= len(item)
            for i in range(layer_length):
                data = item.pop(0)
                if data.left:
                    item.append(data.left)
                if data.right:
                    item.append(data.right)
                if i==layer_length-1:
                    ans.append(data.val)
        return ans

反转链表||(leetcode92)

C++

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 *reverseBetween(ListNode *head, int left, int right) {
        if (right == left) return head;
        // 设置虚拟头节点
        ListNode *dummy = new ListNode(0, head);
        ListNode *p = dummy;
        // 寻找到left
        while(left>1){
            head = head->next;
            p = p->next;
            left--;
            right--;
        }
        // 头插法反转链表,执行right-left次结束
        ListNode * r;
        while (right>left){
            r = head->next;
            head->next = r->next;
            r->next = p->next;
            p->next=r;
            right--;
        }
        r = dummy->next;
        delete dummy;
        return r;
    }
};

Python

from typing import Optional
# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
        if right==left:
            return head
        # 思路:找到left,使用头插法反转链表,直到right-left次后结束
        # 定义一个虚拟头节点
        dummy = ListNode(0,head)
        # 指针p指向left的上一个节点,head指向需要反转的节点,r指向待反转节点
        p = dummy
        while left>1:
            head = head.next
            p = p.next
            left-=1
            right-=1
        # 头插法反转链表
        while right>left:
            r = head.next
            head.next = r.next
            r.next = p.next
            p.next = r
            right-=1
        return dummy.next

if __name__ == '__main__':
    # head = ListNode(3,ListNode(5,None))
    head = ListNode(1,ListNode(2,ListNode(3,ListNode(4,ListNode(5,None)))))
    left = 2
    right = 4
    s = Solution()
    res = s.reverseBetween(head,left,right)
    while res:
        print(res.val)
        res = res.next

复原IP地址(leetcode93)

C++

#include <vector>
#include <string>
#include <iostream>
using namespace std;

class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        vector<string> ans;
        if (s.length()>12 || s.length()<4) return ans;
        string ip; // 记录正确的ip
        int i = 1; // 用于表示当前正在处理第i个整数
        processIpAddresses(s,i,ip,ans);
        return ans;
    }
    void processIpAddresses(string subs, int i, string ip, vector<string> &ans){
        // 检查空串和长度是否符合
        if(subs.empty() || subs.length()>(5-i)*3)
            return;
        // 是否为最后一个
        if(i==4 && stoi(subs)<=255){
            if(subs.length()>1 && subs[0]=='0') return;
            ans.push_back(ip+subs);
            return;
        }

        // 切分1至3个字符进行判断
        for(int j=1;j<4 && j<subs.length();j++){
            string tmp = subs.substr(0,j);
            // 不能是0开头的非零整数,不能大于255
            if(tmp.length()>1 && tmp[0]=='0')
                return;
            if (stoi(tmp)>255)
                return;
            // 符合要求进入下一轮
            processIpAddresses(subs.substr(j),i+1,ip+tmp+".",ans);
        }

    }
};

int main(){
    string s = "25525511135";
    //string s = "0000";
    //string s = "101023";
    Solution solution;
    vector<string> ans=solution.restoreIpAddresses(s);
    for (auto it : ans) {
        cout << it << " ";
    }
    cout << endl;
    return 0;
}

Python

from typing import List
# 复原ip
class Solution:
    def restoreIpAddresses(self, s: str) -> List[str]:
        if len(s)>12 or len(s)<4:
            return []
        ip =''
        ans = []
        # 处理
        self.processIpAddresses(s,1,ip,ans)
        return ans

    def processIpAddresses(self,subs,i,ip,ans):    # subs为第i个整数往后子字符串,i为第i个整数,ans储存结果
        if len(subs)==0:
            return
        if i == 4 and int(subs)<=255:
            # 去除0开头的非0整数
            if len(subs)>1 and subs[0]=="0":
                return
            ans.append(ip+subs)
            return
        # 长度不符合
        if len(subs)>(5-i)*3:
            return
        # 切分1到3个字符作为第i个整数
        for j in range(1,4):
            tmp = subs[:j]
            # 去除0开头的非0整数
            if j>1 and tmp[0]=='0':
                return
            # 判断范围
            if int(tmp)>255:
                return
            # 都满足则进入下一个阶段
            self.processIpAddresses(subs[j:],i+1,ip+tmp+".",ans)

if __name__ == '__main__':
    # s = "25525511135"
    s = "0000"
    # s = "101023"
    sulution = Solution()
    ans = sulution.restoreIpAddresses(s)
    print(ans)

环形链表(leetcode141)

C++

using namespace std;
struct ListNode {
        int val;
        ListNode *next;
        ListNode(int x) : val(x), next(nullptr) {}
     };

class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head== nullptr) return false;
        // 定义快慢指针
        ListNode *fast = head;
        ListNode *slow = head;
        while(fast && fast->next){
            fast = fast->next->next;
            slow = slow->next;
            if(fast==slow) return true;
        }
        return false;
    }
};

Python

from typing import Optional
# 环形链表
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        if not head:
            return False
        # 定义快慢指针
        fast = head
        slow = head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
            if slow==fast:
                return True
        return False

环形链表||(leetcode142)

C++

// 环形链表||
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(nullptr) {}
};

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if (head == nullptr) return nullptr;
        // 定义快慢指针
        ListNode *fast = head;
        ListNode *slow = head;
        while (fast && fast->next){
            fast = fast->next->next;
            slow = slow->next;
            if(fast==slow){
                while(head != slow){
                    slow = slow->next;
                    head = head->next;
                }
                return slow;
            }
        }
        return nullptr;
    }
};

Python

from typing import Optional
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head:
            return None
        # 定义快慢指针
        fast = head
        slow = head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
            if fast==slow:
                while head != slow:
                    head = head.next
                    slow = slow.next
                return slow
        return None

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值