2021-03-21

LeetCode Easy

两数之和

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int,int> Map;
        for(int i=0;i<nums.size();i++)
        {
            Map[nums[i]]=i;
        }
        vector<int> res;
        for(int j=0;j<nums.size();j++)
        {
            int k=target-nums[j];
            if( (Map.count(k))&&(Map[k]!=j) )//顺序不能颠倒
            {
                res.push_back(j);
                res.push_back(Map[k]);
                break;
            }
        }
        return res;
    }
};

整数反转

在这里插入图片描述

class Solution {
public:
    int reverse(int x) {
        int a=0;
        while(x!=0)
        {
            int pop=x%10;      
            x=x/10;
            if(a>INT_MAX/10||(a==INT_MAX/10&&pop>7))
            {
                //cout<<111;
                return 0;
            }
            if(a<INT_MIN/10||(a==INT_MIN/10&&pop<-8))
            {
                return 0;
            }
            a = a*10+pop;
          
        }
    return a;
    }
};

回文数

给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文,而 123 不是。
思想其实就是反转数,判断反转数和原数相不相等,再对别的情况进行判断,比如超过范围,负数等;

class Solution {
public:
    bool isPalindrome(int x) {
        int temp=x;
        int a=0;
        if(x<0)
        {
            return false;
        }     
        while(x!=0)
        {
            int pop=x%10;
            x/=10;
            if(a>INT_MAX/10 || ((a==INT_MAX/10)&&pop>7))
            {
                return false;
            }
            if(a<INT_MIN/10 || ((a==INT_MIN/10)&&pop<-8))
            {
                return false;
            }
            a=a*10+pop;
        }
        //cout<<a;
        if(a==temp)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
};

罗马数字转整数

在这里插入图片描述

class Solution {
public:
    int romanToInt(string s) {
        unordered_map<string,int> M={{"I",1},{"V",5},{"X",10},{"L",50},{"C",100},{"D",500},{"M",1000}};
        int i=s.size()-1;
        string k=s.substr(i,1);
        int result=M[k];
        
        while(i>0)
        {
            if(M[s.substr(i-1,1)]<M[s.substr(i,1)])
            {
                result-=M[s.substr(i-1,1)];
                //cout<<result<<endl;
            }
            if(M[s.substr(i-1,1)]>=M[s.substr(i,1)])
            {
                result+=M[s.substr(i-1,1)];
                //cout<<result<<endl;
            }
            --i;
        }
        return result;
    }
};

最长公共前缀

在这里插入图片描述

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        if(!strs.size())
            return "";
        int count=strs.size();
        string prefix=strs[0];
        for(int i=1;i<count;i++)
        {
            prefix=longestCommonPrefix(prefix,strs[i]);
            if(!prefix.size())
                return "";
        }
        return prefix;
    }
    string longestCommonPrefix(string& str1,string& str2)
    {
        int length=min(str1.size(),str2.size());
        int index=0;
        //string prefix=str1[0];
        while(index<length)
        {
            if(str1[index]==str2[index])
            {
                //prefix=str1[index];
                index++;
            }
            else
                break;
        }
        return str1.substr(0,index);
    }
};

有效的括号

在这里插入图片描述
其实就是利用栈的思想,先压左括号

class Solution {
public:
    bool isValid(string s) {
        unordered_map<char,char> M={{')','('},{'}','{'},{']','['}};
        int count=s.size();
        stack<char> left;
        //cout<<s[0];
        if(count%2!=0)
            return false;
        else
        {
            for(int i=0;i<count;i++)
            {
                if(M.count(s[i]))
                {
                    if(left.empty()||left.top()!=M[s[i]])
                    {
                        return false;
                    }
                    left.pop();
                }
                else
                    left.push(s[i]);
                
            }
        }
        return left.empty();
    }
};

合并两个有序链表

在这里插入图片描述

/**
 * 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* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if(l1==nullptr)
        {
            return l2;
        }
        else if(l2==nullptr)
        {
            return l1;
        }
        else if(l1->val<l2->val)
        {
            l1->next = mergeTwoLists(l1->next, l2);
            return l1;
        }
        else
        {
            l2->next=mergeTwoLists(l1,l2->next);
            return l2;
        }
    }
};

删除链表的倒数第 N 个结点

在这里插入图片描述

/**
 * 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* removeNthFromEnd(ListNode* head, int n) {
        ListNode* dummy=new ListNode(0,head);//作用在于当删除的是head结点的时候也可以正常操作
        ListNode* first=head;
        ListNode* second=dummy;
        for(int i=0;i<n;i++)
        {
            first=first->next;
        }
        while(first)
        {
            first=first->next;
            second=second->next;
        }
        second->next=second->next->next;
        ListNode* ans=dummy->next;
        delete dummy;
        return ans;
    }
};

反转链表

双指针

/**
 * 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) {
        ListNode* cur=NULL;
        ListNode* pre=head;
        while(pre)
        {
            ListNode* t=pre->next;
            pre->next=cur;
            cur=pre;
            pre=t;
        }
        return cur;
    }
};

删除链表的节点

在这里插入图片描述

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* deleteNode(ListNode* head, int val) {
        ListNode* dummy=new ListNode(0,head);
        ListNode* t=dummy;
        while(t->next->val!=val)
        {
            t=t->next; 
        }
        t->next=t->next->next;
        return dummy->next;
    }
};

反转链表II

在这里插入图片描述

/**
 * 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* reverseBetween(ListNode* head, int left, int right) {
        ListNode* dummy=new ListNode(0,head);
        ListNode* cur=dummy;
        ListNode* pre=head;
        ListNode* back=head;
        ListNode* fore=dummy;
        if(left==right)
        {
            return head;
        }
        else
        {
            for(int i=0;i<left;i++)
            {
                cur=cur->next;
                pre=pre->next;
                //fore=fore->next;
            }
            //cur=cur->next;
           // pre=pre->next;
            ListNode* p=cur;
            for(int i=0;i<left-1;i++)
            {
                fore=fore->next;
            }
            for(int j=0;j<right;j++)
            {
                back=back->next;
            }
            while(pre!=back)
            {
                ListNode* t=pre->next;
                pre->next=cur;
                cur=pre;
                pre=t;
            }
            fore->next=cur;
            p->next=back;
            return dummy->next;
        }
    }
};

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

输入两个链表,找出它们的第一个公共节点。

/**
 * 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) {
        ListNode* nodeA= headA;
        ListNode* nodeB= headB;
        while(nodeA != nodeB)
        {
            nodeA=nodeA==NULL?headB:nodeA->next;
            nodeB=nodeB==NULL?headA:nodeB->next;
        }
        return nodeA;
    }
};

环形链表

在这里插入图片描述

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        
        //bool ans=false;
        if(head==NULL||head->next==NULL)
        {
            return false;
        }
        else
        {
            ListNode* slow=head;       
            ListNode* fast=head->next;
            while(slow!=fast)
            {
                if(fast==NULL||fast->next==NULL)
                {
                    return false;
                }
                slow=slow->next;
                fast=fast->next->next;
            }
        }
        return true;
    }
};

回文链表

请判断一个链表是否为回文链表。`

/**
 * 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:
    bool isPalindrome(ListNode* head) {
        if(head==nullptr)
        {
            return true;
        }
        else
        {
            vector<int> a;
            while(head != nullptr)
            {
                a.push_back(head->val);
                head=head->next;
            }
            int len=a.size();
            for(int i=0,j=len-1;i<j;++i,--j)
            {
                if(a[i]!=a[j])
                {
                    return false;
                }
            }
            return true;
        }
    }
};



快慢指针解法,空间复杂度为o(1)

class Solution {
public:
    bool isPalindrome(ListNode* head) {
        if (head == nullptr) {
            return true;
        }

        // 找到前半部分链表的尾节点并反转后半部分链表
        ListNode* firstHalfEnd = endOfFirstHalf(head);
        ListNode* secondHalfStart = reverseList(firstHalfEnd->next);

        // 判断是否回文
        ListNode* p1 = head;
        ListNode* p2 = secondHalfStart;
        bool result = true;
        while (result && p2 != nullptr) {
            if (p1->val != p2->val) {
                result = false;
            }
            p1 = p1->next;
            p2 = p2->next;
        }        

        // 还原链表并返回结果
        firstHalfEnd->next = reverseList(secondHalfStart);
        return result;
    }

    ListNode* reverseList(ListNode* head) {
        ListNode* prev = nullptr;
        ListNode* curr = head;
        while (curr != nullptr) {
            ListNode* nextTemp = curr->next;
            curr->next = prev;
            prev = curr;
            curr = nextTemp;
        }
        return prev;
    }

    ListNode* endOfFirstHalf(ListNode* head) {
        ListNode* fast = head;
        ListNode* slow = head;
        while (fast->next != nullptr && fast->next->next != nullptr) {
            fast = fast->next->next;
            slow = slow->next;
        }
        return slow;
    }
};

链表的中间结点

在这里插入图片描述

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* middleNode(ListNode* head) {
        ListNode* dummy=new ListNode(0,head);
        ListNode* fast=dummy;
        ListNode* slow=dummy;
        while(fast->next!=NULL && fast->next->next!=NULL)
        {
            slow=slow->next;
            fast=fast->next->next;
        }
        //slow->next=slow->next->next;
        return slow->next;
    }
};

二进制链表转整数

给你一个单链表的引用结点 head。链表中每个结点的值不是 0 就是 1。已知此链表是一个整数数字的二进制表示形式。
请你返回该链表所表示数字的 十进制值 。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    int getDecimalValue(ListNode* head) {
        ListNode* p=head;
        int ans=0;
        while(p !=NULL)
        {
            ans=ans*2+p->val;
            p=p->next;
        }     
        return ans;
    }
};

平衡二叉树

输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isBalanced(TreeNode* root) {
        return dfs(root)!=-1;
    }
    int dfs(TreeNode* root)
    {
        if(root==NULL)
        {
            return 0;
        }
        int left=dfs(root->left);
        if(left==-1)
            return -1;
        int right=dfs(root->right);
        if(right==-1)
            return -1;
        return abs(left-right)<2?max(left,right)+1:-1;
    }
};

对称二叉树

请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        if(root==NULL)
            return true;
        return isequal(root->left,root->right);
    }
    bool isequal(TreeNode* left,TreeNode* right)
    {
        if(left==NULL && right==NULL)
            return true;
        if(left==NULL && right!=NULL)
            return false;
        if(left!=NULL && right==NULL)
            return false;
        if(left->val!=right->val)
            return false;
        bool outside=isequal(left->left,right->right);
        bool inside=isequal(left->right,right->left);
        //bool ans=false;
        //if(left->val==right->val)
        //    ans=true;
        return outside && inside;
    }
};

二叉树的镜像

请完成一个函数,输入一个二叉树,该函数输出它的镜像。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* mirrorTree(TreeNode* root) {
        if(root==NULL)
        {
            return NULL;
        }
        TreeNode* left=mirrorTree(root->left);
        TreeNode* right=mirrorTree(root->right);
        root->right=left;
        root->left=right;
        return root;    
    }   
};

二叉树的最近公共祖先

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* ans;
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
       dfs(root,p,q);
       return ans; 
    }
    bool dfs(TreeNode* root, TreeNode* p, TreeNode* q)
    {
        if(root==NULL)
        {
            return false;
        }
        bool lson=dfs(root->left,p,q);
        bool rson=dfs(root->right,p,q);
        if((lson && rson) || ((root->val == p->val || root->val == q->val) && (lson || rson)))
        {
            ans=root;
        }
        return lson || rson ||(root->val == p->val || root->val == q->val);
    }
};

从上到下打印二叉树II

从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) 
    {
        if (!root)  return {};
        vector<vector<int>> res;    // 结果数组
        queue<TreeNode*> que;       // 辅助队列
        que.push(root);             
        while (!que.empty())
        {
            int cnt = que.size();   // 当前层的节点数
            vector<int> level;      // 保存当前层的元素
            // 处理当前层的元素,每个元素出队前将其左右子节点入队,作为下一层的元素
            while (cnt)
            {
                auto node = que.front();
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
                level.push_back(node->val);
                que.pop();
                cnt--;
            }
            res.push_back(level);   // 得到了一层的元素
        }
        return res;
    }
};

二叉搜索树的第K大节点

给定一棵二叉搜索树,请找出其中第k大的节点。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int n,ans=0;
    int kthLargest(TreeNode* root, int k) {
        n=k;
        dfs(root);
        return ans;
    }
    void dfs(TreeNode* root)
    {
        if(root==NULL||n==0)
        {
            return;
        }
        dfs(root->right);
        if(--n==0)
        {
            ans=root->val;
            return;
        }
        dfs(root->left);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值