1. 程式人生 > >C++學習筆記(一)——leetcode記錄

C++學習筆記(一)——leetcode記錄

C++學習筆記(一)——leetcode記錄

Leetcode
最近學cpp,就寫題練練手,個人學習筆記,如存在問題,歡迎指出

944. Delete Columns to Make Sorted [Easy]

944. Delete Columns to Make Sorted [Easy]

class Solution {
public
: int minDeletionSize(vector<string>& A) { int count = 0; for(int i = 0; i < A[0].size(); i++){ for(int j = 1; j < A.size(); j ++){ if(A[j][i] < A[j-1][i] ){ count++; break; } } } return count; } };

C++ vector的用法(整理)

852. Peak Index in a Mountain Array [Easy]

852. Peak Index in a Mountain Array [Easy]

class Solution {
public:
    int peakIndexInMountainArray(vector<int>& A) {
        int index = 0;
        for(int i = 1; i < A.size(); i++){
            if(A[i]>A[i-1]) index = i;    
        }
        return index;
    }
};

942. DI String Match [Easy]

942. DI String Match [Easy]

class Solution {
public:
    vector<int> diStringMatch(string S) {
        vector<int> A;
        for (int l = 0, h = S.size(), i = 0; i <= S.size(); i++) {
            A.push_back(S[i] == 'I' ? l++ : h--);
        }
        return A;
    }
};

922. Sort Array By Parity II [Easy]

922. Sort Array By Parity II [Easy]

class Solution {
public:
    vector<int> sortArrayByParityII(vector<int>& A) {
        vector<int> odd, even;
        for(int i = 0; i < A.size(); i++) {
            if(A[i]%2 == 0) even.push_back(A[i]);
            else odd.push_back(A[i]);
        }
        for(int i = 0; i < A.size()-1; i+=2) {
            A[i] = even[i/2];
            A[i+1] = odd[i/2];
        }
        return A;
    }
};

933. Number of Recent Calls [Easy]

933. Number of Recent Calls [Easy]

題目大意:
找出最近的3000毫秒內有多少個呼叫請求。每個呼叫請求是ping(t)函式,其中t是請求的時間,可以保證每次ping的引數t是大於前面的。
reference


queue用法參考

class RecentCounter {
public:
    queue<int> q;
    RecentCounter() {
        
    }
    
    int ping(int t) {
        while(!q.empty() && t-q.front()>3000) q.pop();
        q.push(t);
        return q.size();
    }
};

/**
 * Your RecentCounter object will be instantiated and called as such:
 * RecentCounter* obj = new RecentCounter();
 * int param_1 = obj->ping(t);
 */

883. Projection Area of 3D Shapes [Easy]

883. Projection Area of 3D Shapes [Easy]

class Solution {
public:
    int projectionArea(vector<vector<int>>& grid) {
        int res = 0, n = grid.size(), m = grid[0].size();
        
        for (int i = 0, v = 0; i < n; ++i, res += v, v = 0)
            for (int j = 0; j < m; ++j)
                v = max(v, grid[i][j]);
        
        for (int j = 0, v = 0; j < m; ++j, res += v, v = 0)
            for (int i = 0; i < n; ++i)
                v = max(v, grid[i][j]);
        
        for (int i = 0; i < n; ++i)
            for (int j = 0; j < m; ++j)
                if (grid[i][j]) res++;
        return res;
    }
};
int projectionArea(const vector<vector<int>>& grid) {
        int res = 0, n = grid.size(), x, y;
        for (int i = 0; i < n; ++i) {
            x = 0, y = 0;
            for (int j = 0; j < n; ++j) {
                x = max(x, grid[i][j]);
                y = max(y, grid[j][i]);
                if (grid[i][j]) ++res;
            }
            res += x + y;
        }
        return res;
    }

590. N-ary Tree Postorder Traversal [Easy]

590. N-ary Tree Postorder Traversal [Easy]

Reference

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

    Node() {}

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
public:
    vector<int> postorder(Node* root) {
        if(root==NULL) return {};
        vector<int> res;
        stack<Node*> stk;
        stk.push(root);
        while(!stk.empty())
        {
            Node* temp = stk.top();
            stk.pop();
            for(int i = 0; i < temp->children.size(); i++) stk.push(temp->children[i]);
            res.push_back(temp->val);
        }
        reverse(res.begin(), res.end());
        return res;
    }
};

stack的定義:C++stack(堆疊)是一個容器的改編,它實現了一個先進後出的資料結構(FILO),不允許被遍歷,沒有迭代器。 使用該容器時需要包含#include標頭檔案.
**top()**是取棧頂元素
**pop()**是彈出棧頂元素

167. Two Sum II - Input array is sorted [Easy]

167. Two Sum II - Input array is sorted [Easy]

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        vector<int> res;
        int end   = numbers.size()-1;
        int i = 0;
        int j = end;
        
        for(int i = 0; i < j; i++){
            for(int j = end; j > i; j--){
                if(numbers[i] + numbers[j] == target) {
                    res.push_back(i+1);
                    res.push_back(j+1);
                    return res;
                }else if(numbers[i] + numbers[j] < target){
                    end = j;
                    break;
                }else continue;
            }
        }
    }
};

其他簡單方法:

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        int start = 0, end = numbers.size()-1;
        while(start < end) {
            if(numbers[start] + numbers[end] == target) {
                return {start+1, end+1};
            }
            
            if(numbers[start] + numbers[end] > target) {
                end--;
            }
            
            else {
                start++;
            }
        }
    }
};
vector<int> twoSum(vector<int>& numbers, int target) {
        
        int l = 0;
        int r = numbers.size() -1;
        while(l < r){
            if(numbers[l] + numbers[r] == target){
                vector<int> res{l+1,r+1};
                return res;
            }
            else if(numbers[l] + numbers[r] > target){
                r--;
            }
            else{
                l++;
            }
        }
    }

860. Lemonade Change [Easy]

860. Lemonade Change [Easy]

class Solution {
public:
    bool lemonadeChange(vector<int>& bills) {
        int five = 0, ten = 0;
        for(int i = 0; i < bills.size(); i++){
            if(bills[i] == 5) five++;
            else if(bills[i] == 10){
                if(five == 0) return 0;
                five--;
                ten++;
            }else{
                if(five>0 && ten>0){
                    ten--;
                    five--;
                }else if(five > 2) five -= 3;
                else return 0;
            }
        }
        return 1;
        }
};

697. Degree of an Array [Easy]

697. Degree of an Array [Easy]

reference

class Solution {
public:
    int findShortestSubArray(vector<int>& nums) {
        unordered_map<int,vector<int>> mp;
        for(int i=0;i<nums.size();i++) mp[nums[i]].push_back(i);
        
        int degree=0;
        for(auto it=mp.begin();it!=mp.end();it++) degree=max(degree,int(it->second.size()));
        
        int shortest=nums.size();
        for(auto it=mp.begin();it!=mp.end();it++){
            if(it->second.size()==degree){
                shortest=min(shortest,it->second.back()-it->second[0]+1);
            }
        }
        return shortest;
    }
};

unordered_map

Reference

template < class Key,                                    // unordered_map::key_type
           class T,                                      // unordered_map::mapped_type
           class Hash = hash<Key>,                       // unordered_map::hasher
           class Pred = equal_to<Key>,                   // unordered_map::key_equal
           class Alloc = allocator< pair<const Key,T> >  // unordered_map::allocator_type
           > class unordered_map;

In the reference for the unordered_map member functions, these same names (Key, T, Hash, Pred and Alloc) are assumed for the template parameters.

Iterators to elements of unordered_map containers access to both the key and the mapped value. For this, the class defines what is called its value_type, which is a pair class with its first value corresponding to the const version of the key type (template parameter Key) and its second value corresponding to the mapped value (template parameter T):

typedef pair<const Key, T> value_type;

Iterators of a unordered_map container point to elements of this value_type. Thus, for an iterator called it that points to an element of a map, its key and mapped value can be accessed respectively with:

unordered_map<Key,T>::iterator it;
(*it).first;             // the key value (of type Key)
(*it).second;            // the mapped value (of type T)
(*it);                   // the "element value" (of type pair<const Key,T>) 

Naturally, any other direct access operator, such as -> or [] can be used, for example:

it->first;               // same as (*it).first   (the key value)
it->second;              // same as (*it).second  (the mapped value) 

300. Longest Increasing Subsequence [Medium]

300. Longest Increasing Subsequence [Medium]

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        if(nums.size() == 0) return 0;
        vector<int> length(nums.size());
        
        int longest = 1;
        length[0] = 1;
        
        for(int i = 1; i < nums.size(); i++){
            length[i] = 1;
            for(int j = 0; j < i; j++){ 
                if(nums[j] < nums[i]) length[i] = max(length<