LeetCode刷算法题-简单难度(六)题号501-600

501.二叉搜索树中的众数

/*
*利用中序遍历,因为中序遍历是严格不减序列,便于比较
*/
/**
 * 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<int> findMode(TreeNode* root) {
     
        vector<int> res;
        if(root==NULL)
            return res;
        int curTimes=0,maxTimes=0,preNum=INT_MIN;
        inorder(root,res,curTimes,maxTimes,preNum);
        return res;
    }
    void inorder(TreeNode* root, vector<int>& res, int& curTimes, int& maxTimes, int& preNum){
     
        if(root->left)
            inorder(root->left,res,curTimes,maxTimes,preNum);
        curTimes = preNum==root->val ? curTimes+1:1;
        if(curTimes>maxTimes){
     
            maxTimes = curTimes;
            res.clear();
            res.push_back(root->val);
        }else if(curTimes==maxTimes){
     
            res.push_back(root->val);
        }
        preNum = root->val;
        if(root->right)
            inorder(root->right,res,curTimes,maxTimes,preNum);
    }
};

504.七进制数

class Solution {
     
public:
    string convertToBase7(int num) {
     
        if(num==0)
            return "0";
        string res;
        bool signBit = false;
        signBit = num >= 0 ? false:true;
        num = num >= 0 ? num : -num;
        int tmp;
        while(num){
     
            tmp = num % 7;
            num /= 7;
            res.insert(0,1,'0'+tmp);
        }
        if(signBit)
            res.insert(0,1,'-');
        return res;
    }
};

506.相对名次

/*
*利用map对key值自动排序的特性
*/
class Solution {
     
public:
    vector<string> findRelativeRanks(vector<int>& nums) {
     
        int n = nums.size();
        vector<string> res(n,"");
        map<int,int> myMap;
        for(int i = 0; i < n; ++i){
     
            myMap[nums[i]] = i;
        }
        int rank = 1;
        vector<string> medals{
     "Gold Medal","Silver Medal","Bronze Medal"}; 
        for(auto iter = myMap.rbegin(); iter != myMap.rend(); iter++){
     
            if(rank <= 3){
     
                res[iter->second] = medals[rank-1];
            }else{
     
                res[iter->second] = to_string(rank);
            }
            rank++;
        }
        return res;
    }
};

507.完美数

/*
*每次给sum加上i和num/i,以及在sum>num后直接返回false,可以提高效率
*/
class Solution {
     
public:
    bool checkPerfectNumber(int num) {
     
        if(num == 0 || num == 1)
            return false;
        int sum = 1;
        for(int i = 2; i*i <= num; ++i){
     
            if(num%i==0){
     
                sum = sum + i + num/i;
            }
            if(i*i==num)
                sum -= i;
            if(sum > num)
                return false;
        }
        return sum==num?true:false;
    }
};

509.斐波那契数列

/*
*用循环比递归效率高
*/
class Solution {
     
public:
    int fib(int N) {
     
        if(N==0 || N==1)
            return N;
        int f1 = 0, f2 = 1, res;
        for(int i = 2; i <= N; ++i){
     
            res = f1+f2;
            f1 = f2;
            f2 = res;
        }
        return res;
    }
};

520.检测大写字母

/*
*三种正确的情况,使用三个bool变量对应
*/
class Solution {
     
public:
    bool detectCapitalUse(string word) {
     
        int n = word.length();
        bool case1=true,case2=true,case3=true;
        for(int i = 0; i < n; ++i){
     
            if('A'<=word[i]&&'Z'>=word[i]){
     
                case2 = false;
                if(i>=1) case3=false;
            }
            if('a'<=word[i]&&'z'>=word[i]){
     
                case1 = false;
                if(i==0) case3=false;
            }
        }
        return case1 || case2 || case3;
    }
};

521.最长特殊序列 I

/*
*只要两个字符串不相等,最长特殊序列的长度就是其中较长字符串的长度
*/
class Solution {
     
public:
    int findLUSlength(string a, string b) {
     
        if(a.size()>b.size()) return a.size();
        else if(a.size() < b.size()) return b.size();
        else if(a!=b) return a.size();
        else return -1;
    }
};

530.二叉搜索树的最小绝对差值

/*
*中序遍历为严格不减序列
*/
/**
 * 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 getMinimumDifference(TreeNode* root) {
     
        if(root==NULL) return 0;
        int res = INT_MAX;
        int pre = INT_MAX;
        inOrder(root,pre,res);
        return res;
    }
    void inOrder(TreeNode* root, int& pre, int& res){
     
        if(root){
     
            inOrder(root->left, pre, res);
            res = min(abs(root->val - pre), res);
            pre = root->val;
            inOrder(root->right, pre, res);
        }
    }
};

532.数组中的K-Diff数对

/*
*利用set去重
*/
class Solution {
     
public:
    int findPairs(vector<int>& nums, int k) {
     
        if(nums.empty()) return 0;
        sort(nums.begin(), nums.end());
        set<int> mySet;
        for(int i = 0; i < nums.size()-1; ++i){
     
            int tmp = nums[i]+k;
            for(int j = i+1; j < nums.size(); ++j){
     
                if(tmp == nums[j]){
     
                    mySet.insert(nums[i]);
                }
                else if(tmp < nums[j])
                    break;
            }
        }
        return mySet.size();
    }
};

538.把二叉搜索树转换为累加树

/*
*反向中序遍历
*/
/**
 * 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* convertBST(TreeNode* root) {
     
        if(root == NULL) return root;
        int sum = 0;
        inOrderReverse(root, sum);
        return root;
    }
    void inOrderReverse(TreeNode* root, int& sum){
     
        if(root){
     
            inOrderReverse(root->right,sum);
            int tmp = root->val;
            root->val += sum;
            sum += tmp;
            inOrderReverse(root->left,sum);
        }
    }
};

541.反转字符串II

class Solution {
     
public:
    string reverseStr(string s, int k) {
     
        if(s.size()==0 || s.size() == 1)
            return s;
        int i,n=s.length();
        for(i = 0; i + k <= n; i = i + 2*k){
     
            reverse(s.begin()+i, s.begin()+i+k);
        }
        if(i+k>n && i<n){
     
            reverse(s.begin()+i, s.end());
        }
        return s;
    }
};

543.二叉树的直径

/*
*直径等于左右子树深度之和
*/
/**
 * 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 diameterOfBinaryTree(TreeNode* root) {
     
        int res = 0;
        depth(root,res);
        return res;
    }
    int depth(TreeNode*root, int& res){
     
        if(root==NULL) return 0;
        int lDepth = depth(root->left,res);
        int rDepth = depth(root->right,res);
        res = max(res, lDepth+rDepth);
        return max(lDepth+1,rDepth+1);
    }
};

551.学生出勤记录

class Solution {
     
public:
    bool checkRecord(string s) {
     
        int countA = 0, countLL = 0;
        for(int i = 0; i < s.length(); ++i){
     
            if(s[i]=='A') countA++;
            if(i>1&&(s[i]=='L'&&s[i-1]=='L'&&s[i-2]=='L')) countLL++;
        }
        return countA<2&&countLL<1;
    }
};

557.反转字符串中的单词III

class Solution {
     
public:
    string reverseWords(string s) {
     
        for(int i=0,j=0;j<s.length();i=++j){
     
            while(j<s.length() && s[j]!=' ') ++j;
            reverse(s.begin()+i,s.begin()+j);
        }
        return s;
    }
};

559.N叉树的最大深度

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector children;

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
     
public:
    int maxDepth(Node* root) {
     
        if(root==NULL) return 0;
        int maxDep = 0;
        vector<int> deps;
        for(auto t : root->children){
     
            deps.push_back(maxDepth(t));
        }
        for(auto d : deps){
     
            maxDep = max(maxDep,d);
        }
        return maxDep+1;
    }
};

561.数组拆分I

class Solution {
     
public:
    int arrayPairSum(vector<int>& nums) {
     
        sort(nums.begin(), nums.end());
        int res = 0;
        for(int i = 0; i < nums.size(); i = i+2){
     
            res += nums[i];
        }
        return res;
    }
};

563.二叉树的坡度

/**
 * 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 findTilt(TreeNode* root) {
     
        int res = 0;
        calcSum(root, res);
        return res;
    }
    int calcSum(TreeNode* root, int& res){
     
        if(root==NULL) return 0;
        int leftSum = calcSum(root->left,res);
        int rightSum = calcSum(root->right,res);
        res += abs(leftSum-rightSum);
        return leftSum+rightSum+root->val;
    }
};

566.重塑矩阵

class Solution {
     
public:
    vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
     
        int n = nums.size() * nums[0].size();
        if(n != r*c) return nums;
        vector<vector<int>> res(r, vector<int>(c,0));
        vector<int> tmp;
        for(auto row : nums)
            for(auto elem : row)
                tmp.push_back(elem);
        int index = 0;
        for(auto& row : res)
            for(auto& elem : row)
                elem = tmp[index++];
        return res;
    }
};

572.另一个树的子树

/*
*技巧在于两个函数都做递归
*/
/**
 * Definition for a binary tree node.
 * 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:
    bool isSubtree(TreeNode* s, TreeNode* t) {
     
        if(t==NULL) return true;
        if(s==NULL) return false;
        return isIdentical(s,t) || isSubtree(s->left,t) || isSubtree(s->right,t);
    }
    bool isIdentical(TreeNode*s, TreeNode* t){
     
        if(s==NULL&&t==NULL) return true;
        else if(s==NULL||t==NULL) return false;
        else if(s->val!=t->val) return false;
        else    return isIdentical(s->left,t->left) && isIdentical(s->right,t->right);
    }
};

575.分糖果

class Solution {
     
public:
    int distributeCandies(vector<int>& candies) {
     
        set<int> kinds;
        int n = candies.size()/2;

        for(auto c : candies){
     
            kinds.insert(c);
        }
        int k = kinds.size();
        return k>n?n:k;
    }
};

581.最短无序连续子数组

class Solution {
     
public:
    int findUnsortedSubarray(vector<int>& nums) {
     
        int n = nums.size();
        int begin = -1, end = -2;
        int maxNo = nums[0], minNo = nums[n-1];
        for(int i = 0; i < n; ++i){
     
            maxNo = max(maxNo,nums[i]);
            minNo = min(minNo,nums[n-i-1]);
            if(nums[i]<maxNo) end = i;
            if(nums[n-i-1]>minNo) begin = n-i-1;
        }
        return end + 1 -begin;
    }
};

589.N叉树的前序遍历

/*
*迭代比递归效率高,使用stack数据结构
*/
/*
// Definition for a Node.
class Node {
public:
    int val;
    vector children;

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
     
public:
    vector<int> preorder(Node* root) {
     
        vector<int> res;
        stack<Node*> s;
        if(root==NULL) return res;
        Node* p = root;
        for(int i = p->children.size()-1; i >= 0; --i)
            s.push(p->children[i]);
        res.push_back(p->val);
        while(!s.empty()){
     
            p = s.top();
            s.pop();
            res.push_back(p->val);
            for(int i = p->children.size()-1; i >= 0; --i)
                s.push(p->children[i]);
        }
        return res;   
    }
};

590.N叉树的后序遍历

/*
*后序遍历利用前序遍历方式略作调整,然后reverse
*/
/*
// Definition for a Node.
class Node {
public:
    int val;
    vector children;

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
     
public:
    vector<int> postorder(Node* root) {
     
        vector<int> res;
        if(root==NULL) return res;
        stack<Node*> s;
        Node* p = root;
        s.push(p);
        while(!s.empty()){
     
            p = s.top();
            s.pop();
            res.push_back(p->val);
            for(auto c : p->children)
                s.push(c);
        }
        reverse(res.begin(),res.end());
        return res;
    }
};

594.最长和谐子串

class Solution {
     
public:
    int findLHS(vector<int>& nums) {
     
        if(nums.empty()) return 0;
        map<int,int> myMap;
        int res = 0;
        for(auto c : nums)
            myMap[c]++;
        for(auto iter = myMap.begin(); next(iter)!=myMap.end(); iter++){
     
            if(next(iter)->first == iter->first+1)
                res = max(res, next(iter)->second+iter->second);
        }
        return res;
    }
};

598.范围求和II

/*
*问题的关键在于无需真的去累加,只要计算出有多少元素做了最多次自增
*/
class Solution {
     
public:
    int maxCount(int m, int n, vector<vector<int>>& ops) {
     
        int row = m, col = n;
        for(int i = 0; i < ops.size(); ++i){
     
            row = min(row, ops[i][0]);
            col = min(col, ops[i][1]);
        }
        return row*col;
    }
};

599.两个列表的最小索引和

class Solution {
     
public:
    vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
     
        int len1 = list1.size();
        int len2 = list2.size();
        map<string,int> temp;
        for(int i = 0; i < len1; ++i){
     
            temp[list1[i]] = i+1;
        }
        int totalLen = len1 + len2;
        vector<string> res;
        for(int i = 0; i < len2; ++i){
     
            if(temp[list2[i]] > 0){
     
                int sum = i + temp[list2[i]] - 1;
                if(sum<totalLen){
     
                    res.clear();
                    res.push_back(list2[i]);
                    totalLen = sum;
                }else if(sum==totalLen){
     
                    res.push_back(list2[i]);
                }
            }
            
        }
        return res;
    }
};

你可能感兴趣的:(LeetCode算法简单难度,算法,二叉树,leetcode)