Rrui的Leetcode算法刷题笔记(五)

注:本页有大量的锁定题,由于本人非常穷,所以本页的题非常少。

217. Contains Duplicate

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        
        map<int,int>a;
            
        for(int i=0;i<nums.size();i++)
        {
            if(a.find(nums[i])==a.end())
                a.insert(pair<int,int>(nums[i],1));
            else return true; 
        }
        return false;
    }
};

注:简单题,想法就是用map做,线性时间复杂度,可是比我快的都是先排序再判断相邻,那就是O(nlog(n))了,真奇了怪了。faster than 17.97%。

218. The Skyline Problem

注:困难题,。faster than XX%。

219. Contains Duplicate II

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        
        map<int,int>a;
            
        for(int i=0;i<nums.size();i++)
        {
            if(a.find(nums[i])==a.end())
                a.insert(pair<int,int>(nums[i],i));
            else
            {
                if(abs(a.find(nums[i])->second-i)<=k)
                    return true;
                else
                    a.find(nums[i])->second=i;                   
            }   
        }
        return false;
    }
};
        

注:简单题,跟217没啥区别。faster than 18.30%。

220. Contains Duplicate III

class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
        map<long long, int> m;
        int j = 0;
        for (int i = 0; i < nums.size(); ++i) {
            if (i - j > k) m.erase(nums[j++]);
            auto a = m.lower_bound((long long)nums[i] - t);
            if (a != m.end() && abs(a->first - nums[i]) <= t) return true;
            m[nums[i]] = i;
        }
        return false;
    }
};

https://blog.csdn.net/qq508618087/article/details/50610584

注:中等题,利用map的二叉树结构查找。faster than XX%。

221. Maximal Square

https://blog.csdn.net/xudli/article/details/46371673

注:中等题,。faster than XX%。

222. Count Complete Tree Nodes

/**
 * 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 countNodes(TreeNode* root) {
        
        int k,p=0;
        if(!root)
            return 0;
        queue<TreeNode*> q;
        q.push(root);
        
        while(!q.empty())
        {
            k=q.size();
            while(k--)
            {
                p++;
                if(q.front()->left)
                    q.push(q.front()->left);
                if(q.front()->right)
                    q.push(q.front()->right);
                q.pop();
            }
        }
        return p;
    }
};



注:中等题,考察层序遍历。faster than 97.63%。

223. Rectangle Area

class Solution {
public:
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        
        long a=max(B,F);
        long b=max(A,E);
        long c=min(D,H);
        long d=min(C,G);
        
        long long square_1=abs(A-C)*abs(B-D);
        long long square_2=abs(E-G)*abs(F-H);
        
        int w = max(d-b,long(0));
        int h = max(c-a,long(0));

        int area=w*h;
        
        return square_1+square_2-area;
    }
};

注:中等题,这题冷不丁一瞅不会,但仔细一想不就是NMS嘛。。。faster than 16.56%。

224. Basic Calculator

class Solution {
public:
    int calculate(string s) {

        int res = 0, sign = 1, n = s.size();
        stack<int> st;
        for (int i = 0; i < n; ++i) {
            char c = s[i];
            if (c >= '0') {
                int num = 0;
                while (i < n && s[i] >= '0') {
                    num = 10 * num + s[i++] - '0';
                }
                res += sign * num;
                --i;
            } else if (c == '+') {
                sign = 1;
            } else if (c == '-') {
                sign = -1;
            } else if (c == '(') {
                st.push(res);
                st.push(sign);
                res = 0;
                sign = 1;
            } else if (c == ')') {
                res *= st.top(); st.pop();
                res += st.top(); st.pop();
            }
        }
        return res;
    }
};

注:困难题,。faster than XX%。

225. Implement Stack using Queues

class MyStack {
public:
    
    queue<int> a,b;
    /** Initialize your data structure here. */
    MyStack() {
    }
    
    /** Push element x onto stack. */
    void push(int x) {
        a.push(x);
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int k;
        while(!a.empty())
        {
            b.push(a.front());
            k=a.front();
            a.pop();
        }
        a.pop();
        while(!b.empty())
        {
            a.push(b.front());
            b.pop();
        }
        return k;
    }
    
    /** Get the top element. */
    int top() {
        int k;
        while(!a.empty())
        {
            b.push(a.front());
            k=a.front();
            a.pop();
        }
        while(!b.empty())
        {
            a.push(b.front());
            b.pop();
        }
        return k;
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return a.empty();
    }
};

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * bool param_4 = obj.empty();
 */

注:简单题,跟232没啥区别,俩来回倒腾。faster than 100.00%。

226. Invert 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:
    TreeNode* invertTree(TreeNode* root) {
        
        if(!root)
            return NULL;
        
        root->left=invertTree(root->left);
        root->right=invertTree(root->right);
        
        TreeNode* m=root->right;
        root->right=root->left;
        root->left=m;
        return root;
    }
};

注:简单题,典型的递归题,没啥好说的。faster than 100.00%。

227. Basic Calculator II

别人的:

class Solution {
public:
    int calculate(string s) {
        int res = 0, d = 0;
        char sign = '+';
        stack<int> nums;
        for (int i = 0; i < s.size(); ++i) {
            if (s[i] >= '0') {
                d = d * 10 + s[i] - '0';
            }
            if ((s[i] < '0' && s[i] != ' ') || i == s.size() - 1) {
                if (sign == '+') nums.push(d);
                if (sign == '-') nums.push(-d);
                if (sign == '*' || sign == '/') {
                    int tmp = sign == '*' ? nums.top() * d : nums.top() / d;
                    nums.pop();
                    nums.push(tmp);
                }
                sign = s[i];
                d = 0;
            }
        }
        while (!nums.empty()) {
            res += nums.top();
            nums.pop();
        }
        return res;
    }
};

自己的:

class Solution {
public:
    int calculate(string s) {
        
        stack<int> p;
        stack<char> c;
        int m=0,n;
        for(int i=0;i<s.size();i++)
        {
            if(s[i]==' ')
                continue;
            if(s[i]>'9'||s[i]<'0')
            {
                int k=atoi(s.substr(m).c_str());
                if(c.empty())
                {
                    p.push(k);
                    c.push(s[i]);
                }
                else
                {
                    if((c.top()=='*'||c.top()=='/')||(s[i]=='+'||s[i]=='-'))
                    {
                        int q=p.top();
                        p.pop();
                        
                        int d=jisuan(q,k,c.top());
                        c.pop();
                        while(!c.empty()&&((c.top()=='+'||c.top()=='-')&&(s[i]=='+'||s[i]=='-')))
                        {
                            int a=p.top();
                            p.pop();  
                            d=jisuan(a,d,c.top());
                            c.pop();
                        }
                        p.push(d);
                        c.push(s[i]);
                    }
                    else 
                    {
                        p.push(k);
                        c.push(s[i]);
                    }
                }
                m=i+1;
            }
            n=atoi(s.substr(m).c_str());
        }
        p.push(n);
        while(!c.empty())
        {
            int a=p.top();
            p.pop();
            int b=p.top();
            p.pop();
            p.push(jisuan(b,a,c.top()));
            c.pop();
        }
        
        return p.top();
    }
    int jisuan(int a,int b,char c)
    {
        if(c=='+')
            return a+b;
        if(c=='-')
            return a-b;
        if(c=='*')
            return a*b;
        if(c=='/')
            return a/b;
    }
};

注:中等题,哔了狗这么慢。。从别人的代码可以看出,如果有负号完全可以把数变为负数省去负号。faster than 0.98%。

228. Summary Ranges

class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        
        if(nums.size()==0)
            return {};
        
        vector<string> a;
        string s;
           
        for(int i=0;i<nums.size();i++)
        {
            if(s.empty())
            {
                s+=to_string(nums[i]);
                if(i+1>=nums.size()||nums[i]+1!=nums[i+1])
                {
                    a.push_back(s);
                    s.clear();
                    continue;
                }
            }
            if(nums[i]+1!=nums[i+1])
            {
                s+="->";
                s+=to_string(nums[i]);
                a.push_back(s);
                s.clear();
            }
        }
        return a;
    }
};

注:中等题,没啥说的。faster than 100%。

229. Majority Element II

class Solution {
public:
    vector<int> majorityElement(vector<int>& nums) {
        vector<int> res;
        int m = 0, n = 0, cm = 0, cn = 0;
        for (auto &a : nums) {
            if (a == m) ++cm;
            else if (a ==n) ++cn;
            else if (cm == 0) m = a, cm = 1;
            else if (cn == 0) n = a, cn = 1;
            else --cm, --cn;
        }
        cm = cn = 0;
        for (auto &a : nums) {
            if (a == m) ++cm;
            else if (a == n) ++cn;
        }
        if (cm > nums.size() / 3) res.push_back(m);
        if (cn > nums.size() / 3) res.push_back(n);
        return res;
    }
};

http://www.cnblogs.com/lightwindy/p/9736278.html

注:中等题,限制了空间复杂度我就不会了,从题意了解,满足条件的数最多为两个需要用摩尔投票法。faster than XX%。

230. Kth Smallest Element in a BST

/**
 * 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 kthSmallest(TreeNode* root, int k) {
        
        vector<int> a;
        stack<TreeNode*> s;
        
        while(!s.empty()||root)
        {
            while(root)
            {
                s.push(root);
                root=root->left;
            }
            root=s.top();
            a.push_back(root->val);
            if(a.size()==k)
                return a.back();
            s.pop();
            root=root->right;
        }
    }
};

注:中等题,考察中序遍历的。faster than 66.34%。

231. Power of Two

class Solution {
public:
    bool isPowerOfTwo(int n) {
        
        if(!n)
            return false;
        
        while(n)
        {
            if(n==1)
                return true;
            if(n%2)
                return false;
            n/=2;
        }
        return true;
    }
};

注:简单题,没啥说的。faster than 99.00%。

232. Implement Queue using Stacks

class MyQueue {
public:
    
    stack<int> a,b;
    /** Initialize your data structure here. */
    MyQueue() {
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        a.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        while(!a.empty())
        {
            b.push(a.top());
            a.pop();
        }
        int k=b.top();
        b.pop();
        while(!b.empty())
        {
            a.push(b.top());
            b.pop();
        }  
        return k;
    }
    
    /** Get the front element. */
    int peek() {
        while(!a.empty())
        {
            b.push(a.top());
            a.pop();
        }
        int k=b.top();
        while(!b.empty())
        {
            a.push(b.top());
            b.pop();
        }  
        return k;
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return a.empty();
    }
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * bool param_4 = obj.empty();
 */

注:简单题,用俩stack来回倒腾就行了。faster than 100.00%。

233. Number of Digit One

class Solution {
public:
    int countDigitOne(int n) {
        
        int count=0;
        int high=n;
        int cur=0,b=1;
        while(high>0)
        {
            cur=high%10;
            high/=10;
            count+=high*b;
            if(cur==1){
                count+=n%b+1;
            }else if(cur>1){
                count+=b;
            }
            b*=10;
        }
        return count;
    }
};

注:困难题,。faster than 43.93%。

234. Palindrome Linked List

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool isPalindrome(ListNode* head) {

        if(!head||!head->next)
            return true;
        
        ListNode* slow=head;
        ListNode* fast=head;
        while(fast->next&&fast->next->next)
        {
            slow=slow->next;
            fast=fast->next->next;
        }

        ListNode* mid=reverse(slow->next);
        
        while(mid)
        {
            if(mid->val!=head->val)
                return false;
            mid=mid->next;
            head=head->next;
        }
        return true;
    }
    
    ListNode* reverse(ListNode* head){

        if(!head->next)
            return head;
        ListNode* p=NULL;
        ListNode* q=head;
        ListNode* r=q->next;
        
        while(1)
        {
            q->next=p;
            p=q;
            q=r;
            r=r->next;
            if(!r)
            {
                q->next=p;
                return q;
            }
        }
    } 
};

注:简单题,我的想法是用快慢指针找到中点,然后把中点后的链表反转,然后头指针和此时的慢指针的下一个节点挨个比较是否相等。faster than 53.03%。

235. Lowest Common Ancestor of a Binary Search 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:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        
        if(!root)
            return NULL;
        if(p->val<root->val&&q->val<root->val)
            return lowestCommonAncestor(root->left,p,q);
        else if(p->val>root->val&&q->val>root->val)
            return lowestCommonAncestor(root->right,p,q);
        else if(p->val>=root->val&&q->val<=root->val||p->val<=root->val&&q->val>=root->val)
            return root;
    }
};

注:简单题,因为是二叉搜索树,所以判断pq和root的大小关系就可以了。faster than 52.95%。

236. Lowest Common Ancestor of 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:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root==p||root==q||root==NULL)
            return root;
        TreeNode* left=lowestCommonAncestor(root->left, p, q);
        TreeNode* right=lowestCommonAncestor(root->right, p, q);
        if(left&&right)
            return root;
        return left==NULL?right:left;
    }
};

注:中等题,递归条件弄不明白,这个人的思路是不等于qp的节点都设为NULL。faster than XX%。

237. Delete Node in a Linked List

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:

	void deleteNode(ListNode* node) {
		if (!node || !node->next)
			return;
		node->val = node->next->val;
		node->next = node->next->next;
 
	}
};

注:智障题,能不能挑点有意义的题来出?!faster than XX%。

238. Product of Array Except Self

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        int len = nums.size();
        if(0 == len || 1 == len){
            vector<int> ret = nums;
            return ret;
        }
        
        vector<int> ins(len, nums[0]);
        vector<int> ret(len, nums[len-1]);
        
        int mul1 = nums[0], mul2 = nums[len-1];
        for(int i = 1; i < len; ++i){
            mul1 *= nums[i];
            mul2 *= nums[len-i-1];
            ins[i] = mul1;
            ret[len-i-1] = mul2;
        }
        
        ret[0] = ret[1];
        for(int i = 1; i < len-1; ++i){
            ret[i] = ins[i-1] * ret[i + 1];
        }
        ret[len-1] = ins[len-2];
 
        return ret;
    }
};

https://blog.csdn.net/sinat_15723179/article/details/81297382

注:中等题,利用正序和逆序辅助数组来做。faster than XX%。

239. Sliding Window Maximum

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        
        vector<int> a;
        int maximum=INT_MIN;
        if(nums.size()==0)
            return a;
        
        for(int i=0;i<=nums.size()-k;i++)
        {
            if(i!=0&&nums[i+k-1]>=maximum)
                maximum=nums[i+k-1];
            else if(i!=0&&nums[i-1]!=maximum);
            else
            {          
                maximum=INT_MIN;
                for(int j=i;j<i+k;j++)
                    maximum=max(maximum,nums[j]);               
            }
            a.push_back(maximum);
        }
        return a;
    }
};

注:困难题,本应该是困难题里少有的简单题了,滑窗法,判断最大值的位置即可。faster than 43.93%。

240. Search a 2D Matrix II

别人的:

​
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        if(matrix.empty()||matrix[0].empty()) return false;
        int m=matrix.size(),n=matrix[0].size();
        int r=0,c=n-1;
        while(r<m&&c>=0){
            if(matrix[r][c]==target) return true;
            else if(matrix[r][c]<target) r++;
            else c--;
        }
        return false;
    }
};

自己的代码:

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        
        if(matrix.size()==0||matrix[0].size()==0)
            return false;
        int low=matrix[0].size(),high,mid,hang,lie;

        int p=1,q=2;
        while(p!=q)
        {
            lie=low-1;
            
            low=0,high=matrix.size()-1;
            while(low<=high)
            {
                mid=(high+low)/2;
                if(matrix[mid][lie]<target)
                    low=mid+1;
                else if(matrix[mid][lie]>target)
                    high=mid-1;
                else return true;
            }
            if(low>matrix.size()-1)
                break;
            q=matrix[low][lie];
            hang=low;
            
            low=0,high=matrix[0].size()-1;
            while(low<=high)
            {
                mid=(high+low)/2;
                if(matrix[hang][mid]>target)
                    high=mid-1;
                else if(matrix[hang][mid]<target)
                    low=mid+1;
                else return true;
            } 
            if(low-1>matrix[0].size()-1||low==0)
                break;
            p=matrix[hang][low-1];
        }
        return false;
    }
};

注:中等题,我的想法是从最后一列开始,二分法判断,找到了就找到了,没找到的判断条件是会停留在同一个数上不变。faster than 24.75%。

241. Different Ways to Add Parentheses

class Solution {
public:
    vector<int> diffWaysToCompute(string input) {
        vector<int> res;
        //边界条件是如果找不到运算符,说明只有
        for(int i=0;i<input.size();i++)
        {
            char c = input[i];
            if(c=='+'||c=='-'||c=='*')
            {
                auto res1 = diffWaysToCompute(input.substr(0,i));
                auto res2 = diffWaysToCompute(input.substr(i+1));
                for(int r1:res1)
                    for(int r2:res2)
                    {
                        if(c=='+')
                            res.push_back(r1+r2);
                        if(c=='-')
                            res.push_back(r1-r2);  
                        if(c=='*')
                            res.push_back(r1*r2);                        
                    }
            }
        }
        if(res.empty())
            res.push_back(stoi(input));
            
        return res;
    }
};

注:中等题,不会不会。faster than XX%。

242. Valid Anagram

class Solution {
public:
    bool isAnagram(string s, string t) {
        
        sort(s.begin(),s.end());
        sort(t.begin(),t.end());
        return s==t;
    }
};

注:简单题,可以遍历可以排序,排序的肯定慢,但我当然挑字少的写了。faster than 14.51%。

257. Binary Tree Paths

/**
 * 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<string> binaryTreePaths(TreeNode* root) {
        
        vector<string> a;
        string s;
        if(!root)
            return a;
        digui(root,a,s);
        return a;
    }
    
    void digui(TreeNode* root,vector<string>& a,string s){
        
        if((!root->left)&&(!root->right))
        {
            s+=to_string(root->val);
            a.push_back(s);
            return ;
        }
        
        s+=to_string(root->val);
        
        if(root->left)
            digui(root->left,a,s+"->");
        if(root->right)
            digui(root->right,a,s+"->");
    }
};

注:简单题,相当于按子树遍历。faster than 33.10%。

258. Add Digits

class Solution {
public:
    int addDigits(int num) {
        
        while(num/10)
        {
            int a=0;
            while(num)
            {
                a=a+num%10;
                num/=10;
            }
            num=a;
        }
        return num;
    }
};

注:简单题,没啥说的。faster than 99.29%。

260. Single Number III

class Solution {
public:
    vector<int> singleNumber(vector<int>& nums) {
        
        map<int, int> m;
        vector<int> a;
        for (int i = 0; i < nums.size(); i++) {
            // key 为数组中的值  value为数组中的值出现的次数
            if (!m.count(nums[i])) {
                m[nums[i]] = 1;
            }else {
                m[nums[i]] += 1;
            }
        }
        for (int i = 0; i < nums.size(); i++) {
            if (m[nums[i]] ==  1) {
                a.push_back(nums[i]);
            }        
        }
        return a;
    }
};

注:中等题,只会哈希表法,位运算是真的弄不明白。faster than 2.64%。

263. Ugly Number

class Solution {
public:
    bool isUgly(int num) {
        
        if(!num)
            return false;
        
        while(num!=1)
        {
            if(!(num%2))
                num/=2;
            else if(!(num%3))
                num/=3;
            else if(!(num%5))
                num/=5;    
            else return false;
        }
        return true;
    }
};

注:简单题,按题意正常做就好了。faster than 97.91%。

264. Ugly Number II

超时代码:

class Solution {
public:
    int nthUglyNumber(int n) {
        
        map<int,int> a;
        a[1]=1;
        int sum=1,k=2;
        
        while(sum!=n)
        {
            int num=k;
            while(num!=1)
            {
                if(!(num%2))
                    num/=2;
                else if(!(num%3))
                    num/=3;
                else if(!(num%5))
                    num/=5;    
                else
                    break;
                if(a.find(num)!=a.end())
                {
                    a[k]=1;
                    sum++;
                    break;
                }
                break;
            }
            k++;
        }
        return --k;
    }
};

别人AC代码:

class Solution {
public:
  int nthUglyNumber(int n) {
  static int arr[1691] = {[0]= 1},
  i  = 1, i2 = 0, i3 = 0, i5 = 0,
  n2 = 2, n3 = 3, n5 = 5;
  
  for (; i < n; i++) {
    arr[i] = min(min(n2, n3), n5);
    if (arr[i] == n2) n2 = 2 * arr[++i2];
    if (arr[i] == n3) n3 = 3 * arr[++i3];
    if (arr[i] == n5) n5 = 5 * arr[++i5];
  }

  return arr[n-1];
}
};

注:中等题,如果不限制内存的话完全可以弄,但是限制了之后这代码还限时,我死也编不出来了。。。faster than XX%。

Rrui的Leetcode算法刷题笔记(六)链接如下:

https://blog.csdn.net/Rrui7739/article/details/83785403

猜你喜欢

转载自blog.csdn.net/Rrui7739/article/details/83540288