LeetCode: 13

Second Minimum Node In a Binary Tree

/**
 * 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:
    void helper(TreeNode*node, int& first, int& second){
        if(!node)
            return;
        if(node->val!=first && node->val<second)
            second = node->val;
        helper(node->left, first, second);
        helper(node->right, first, second);
    }

    int findSecondMinimumValue(TreeNode* root) {
        if(!root)
            return -1;
        int first = root->val;
        int second = INT_MAX;
        helper(root, first, second);
        return second!=INT_MAX?second:-1;
    }
};

Longest Continuous Increasing Subsequence

class Solution {
public:
    int findLengthOfLCIS(vector<int>& nums) {
        if(nums.size()==0)
            return 0;
        int res = 1;
        int temp = 1;
        int ref = nums[0];
        for(int n:nums){
            if(n>ref){
                temp ++;
            }
            else{
                res = max(res,temp);
                temp = 1;
            }
            ref = n;
        }

        return max(res,temp);
    }
};

Valid Palindrome II

class Solution {
public:
    bool helper(string& s, int start, int end){
        for(int i=start;i<(start+end)/2.0;i++){
            if(s[i]!=s[end-i+start])
                return false;
        }
        return true;
    }
    bool validPalindrome(string s) {
        for(int i=0;i<s.size()/2.0;i++){
            if(s[i]!=s[s.size()-i-1])
                return helper(s,i,s.size()-i-2) || helper(s, i+1,s.size()-i-1);
        }
        return true;
    }
};

Baseball Game

class Solution {
public:
    int calPoints(vector<string>& ops) {
        vector<int> v;

        for(string s:ops){
            if(s == "+")
                v.push_back(v.back()+v[v.size()-2]);
            else if(s == "D")
                v.push_back(2*v.back());
            else if(s == "C")
                v.pop_back();
            else
                v.push_back(stoi(s));
        }

        return accumulate(v.begin(), v.end(), 0);
    }
};

Repeated String Match

class Solution {
public:

    int repeatedStringMatch(string A, string B) {
        int max_res = B.size()/A.size() + 2;
        int min_res = B.size()/(A.size()+0.1) +1;
        string t = A;

        for(int i=1;i<min_res;i++)
            t += A;
        for(int i=min_res;i<=max_res;i++){
            if(t.find(B) != string::npos)
                return i;
            t += A;
        }
        return -1;
    }
};

Add Two Numbers

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* res = new ListNode(0);
        ListNode* cur = res;
        int carry = 0;
        while(l1||l2){
            int n1 = l1?l1->val:0;
            int n2 = l2?l2->val:0;
            int s = n1+n2+carry;

            carry = s/10;
            cur->next = new ListNode(s%10);
            cur = cur->next;
            if(l1) l1=l1->next;
            if(l2) l2=l2->next;
        }
        if(carry)
            cur->next = new ListNode(1);
        return res->next;
    }
};

Min Cost Climbing Stairs

class Solution {
public:

    int minCostClimbingStairs(vector<int>& cost) {
        int n = cost.size();
        vector<int> dp(n, 0);
        dp[0] = cost[0];
        dp[1] = cost[1];
        for(int i=2;i<n;i++){
            dp[i] = cost[i] + min(dp[i-1],dp[i-2]);
        }
        return min(dp[n-1],dp[n-2]);
    }
};

Maximum Subarray

"""动态规划视角
"""
class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        //sum_i=max(nums[i], sum_(i-1)+nums[i]) : 恰好包含到i处的最大和
        int a=0,b=0,res=INT_MIN;
        for(int n:nums){
            b = max(n,a+n);
            a = b;
            res = max(res,b);
        }
        return res;
    }
};

Max Area of Island

"""递归
"""
class Solution {
public:
    vector<pair<int,int>> dirs = {{0,1},{0,-1},{-1,0},{1,0}};

    void helper(vector<vector<int>>& grid, int i, int j, int& temp){
        int m = grid.size(), n = grid[0].size();
        for(pair<int,int> d:dirs){
            int x = i+d.first;
            int y = j+d.second;
            if(x<0||y<0||x>=m||y>=n)
                continue;
            else if(grid[x][y]==1){
                grid[x][y] = -1;
                temp += 1;
                helper(grid, x,y,temp);
            }
        }
    }
    int maxAreaOfIsland(vector<vector<int>>& grid) {
        int m = grid.size(), n = grid[0].size();
        int res = 0, temp = 0;
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++){
                if(grid[i][j]<=0)
                    continue;
                else{
                    temp = 1;
                    grid[i][j] = -1;
                    helper(grid, i, j, temp);
                    res = max(res, temp);
                }
            }
        return res;
    }
};
"""迭代BFS
"""
class Solution {
public:
    vector<pair<int,int>> dirs = {{0,1},{0,-1},{-1,0},{1,0}};

    int maxAreaOfIsland(vector<vector<int>>& grid) {
        int m = grid.size(), n = grid[0].size();
        int res = 0, temp = 0;
        queue<pair<int,int>> q;
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++){
                if(grid[i][j]<=0)
                    continue;
                else{
                    q.push({i,j});
                    temp = 1;
                    grid[i][j] = -1;
                    while(!q.empty()){
                        for(pair<int,int> d:dirs){
                            int x = q.front().first+d.first;
                            int y = q.front().second+d.second;
                            if(x< 0 || x >= m || y < 0 || y >= n)
                                continue;
                            else if(grid[x][y]==1){
                                temp++;
                                grid[x][y] = -1;
                                q.push({x,y});
                            }
                        }
                        q.pop();
                    }
                    res = max(res, temp);
                }
            }

        return res;
    }
};

Longest Palindromic Substring

"""动态规划, O(n^2)
"""
class Solution {
public:
    string longestPalindrome(string s) {
        int dp[s.size()][s.size()]={0}, left=0, temp=0, len=0;
        for(int i=0;i<s.size();i++){
            for(int j=0;j<=i;j++){
                dp[j][i] = s[j]==s[i]&&(i-j<=1 || dp[j+1][i-1]);
                if(dp[j][i]==1){
                    temp = i-j+1;
                    if(len<temp){
                        len = temp;
                        left = j;
                    }
                }
            }
        }
        return s.substr(left,len);
    }
};

Unique Paths

"""O(m*n) for both time and space
"""
class Solution {
public:
    int uniquePaths(int m, int n) {
        vector<vector<int>> dp={m,vector<int>(n,1)};
        for(int i=1;i<m;i++)
            for(int j=1;j<n;j++){
                dp[i][j] = dp[i-1][j] + dp[i][j-1];
            }
        return dp[m-1][n-1];
    }
};

Unique Paths II

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        int m = obstacleGrid.size();
        int n = obstacleGrid[0].size();
        if(m==1 && n==1)
            return 1-obstacleGrid[0][0];

        vector<int> dp(n, 1);
        if(obstacleGrid[0][0] == 1)
            dp[0] = 0;
        for(int j=1;j<n;j++)
            if(obstacleGrid[0][j] == 1 || dp[j-1] == 0)
                dp[j] = 0;

        for(int i=1;i<m;i++){
            if(obstacleGrid[i][0] == 1 || dp[0] == 0)
                dp[0] = 0;
            for(int j=1;j<n;j++){
                if(obstacleGrid[i][j] == 1)
                    dp[j] = 0;
                else
                    dp[j] += dp[j-1];
            }
        }
        return dp[n-1];
    }
};

Minimum Path Sum

class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        int m = grid.size();
        int n = grid[0].size();
        vector<int> dp(n,0);
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(j==0)
                    dp[j] += grid[i][j];
                else if(i==0)
                    dp[j] = dp[j-1] + grid[i][j];
                else
                    dp[j] = min(dp[j], dp[j-1]) + grid[i][j];
            }
        }
        return dp[n-1];
    }
};

Longest Univalue Path

"""不好写
"""
/**
 * 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 helper(TreeNode* node, TreeNode*parent, int& res){
        if(!node)            
            return 0;

        int left = helper(node->left, node, res);
        int right = helper(node->right, node, res);

        left = (node->left && node->val == node->left->val) ? left + 1 : 0;
        right = (node->right && node->val == node->right->val) ? right + 1 : 0;

        res = max(res, left+right);
        return max(left, right);
    }

    int longestUnivaluePath(TreeNode* root) {
        if(!root)
            return 0;
        int res = 0;
        helper(root, root, res);
        return res;
    }
};

Employee Importance

class Solution {
public:
    int helper(unordered_map<int, Employee*>& m, unordered_set<int>& s, int id){
        if(s.count(id))
            return 0;

        s.insert(id);
        int res = m[id]->importance;
        for(int i: m[id]->subordinates){
            res += helper(m,s,i);
        }
        return res;
    }
    int getImportance(vector<Employee*> employees, int id) {
        unordered_map<int, Employee*> m;
        unordered_set<int> s;

        for(Employee* e : employees){
            m[e->id] = e;
        }

        return helper(m, s, id);
    }
};

Binary Number with Alternating Bits

class Solution {
public:
    bool hasAlternatingBits(int n) {
        int temp = 1-n%2;
        while(n){
            if(n%2 == temp)
                return false;
            temp = n%2;
            n /=2;
        }
        return true;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值