Wednesday, July 29, 2020

290. Word Pattern ---E

Q:

Given a pattern and a string str, find if str follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.

Example 1:

Input: pattern = "abba", str = "dog cat cat dog"
Output: true

Example 2:

Input:pattern = "abba", str = "dog cat cat fish"
Output: false

Example 3:

Input: pattern = "aaaa", str = "dog cat cat dog"
Output: false

Example 4:

Input: pattern = "abba", str = "dog dog dog dog"
Output: false

Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters that may be separated by a single space.



A:

Two hashMap


学到的: split string into words
        string str
        vector<string> vec;
        istringstream iss(str);
        for(string s; iss >> s; )
            vec.push_back(s);



class Solution {
public:
    bool wordPattern(string pattern, string str) {
        vector<string> vec;
        istringstream iss(str);
        for(string s; iss >> s; )
            vec.push_back(s);
        
        unordered_map<char,string> map1;
        unordered_map<string,char> map2;
        if(pattern.length() != vec.size())
            return false;
        for(int i = 0;i<pattern.length();++i){
            char ch = pattern[i];
            string word = vec[i];
            if(map1.find(ch) == map1.end()){
                map1[ch] = word;
            }else{
                if(map1[ch] != word)
                    return false;
            }
            if(map2.find(word) == map2.end()){
                map2[word] = ch;
            }else{
                if(map2[word] != ch)
                    return false;
            }
        }
        return true;
    }
};





----------

653. Two Sum IV - Input is a BST ---------E

Q:

Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.

Example 1:

Input: 
    5
   / \
  3   6
 / \   \
2   4   7

Target = 9

Output: True

 

Example 2:

Input: 
    5
   / \
  3   6
 / \   \
2   4   7

Target = 28

Output: False

 

A:
/**
 * 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 findTarget(TreeNode* root, int k) {
        unordered_set<int> S;
        return helper(S, root, k);
    }
private:
    bool helper(unordered_set<int> &S, TreeNode* root, int k) {
        if(root == nullptr){
            return false;
        }
        if(S.find(k-root->val) != S.end())
            return true;
        S.insert(root->val);
        return helper(S, root->left, k) || helper(S, root->right, k);
    }
};




643. Maximum Average Subarray I -E

Q:

Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value.

Example 1:

Input: [1,12,-5,-6,50,3], k = 4
Output: 12.75
Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75

 

Note:

  1. 1 <= k <= n <= 30,000.
  2. Elements of the given array will be in the range [-10,000, 10,000].

 

A:
class Solution {
public:
    double findMaxAverage(vector<int>& nums, int k) {
        double sum = 0, maxSum =0;
        for(int i =0;i<k; ++i)
            sum += nums[i];
        maxSum= sum;
        for(int i =k;i<nums.size(); ++i){
            sum += nums[i]  - nums[i-k];
            maxSum = max(maxSum, sum);
        }
        return maxSum / k;
    }
};







633. Sum of Square Numbers --E

Q:

Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a2 + b2 = c.

Example 1:

Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5

 

Example 2:

Input: 3
Output: False



A:

class Solution {
public:
    bool judgeSquareSum(int c) {
        set<int> S;
        for(int i =0; i <= sqrt(c) ; ++i)// 0 is also counted
        {
            int i2 = i*i;
            S.insert(i2);
            if(S.find(c-i2) != S.end())
                return true;
        }
        return false;
    }
};

----------------错误
1: 一开始没有考虑 0  也可以
2:用i*i, 导致有可能溢出

341. Flatten Nested List Iterator -M !!!!!!!!!!!!!!! 方法2,简洁多了

You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.

Implement the NestedIterator class:

  • NestedIterator(List<NestedInteger> nestedList) Initializes the iterator with the nested list nestedList.
  • int next() Returns the next integer in the nested list.
  • boolean hasNext() Returns true if there are still some integers in the nested list and false otherwise.

Your code will be tested with the following pseudocode:

initialize iterator with nestedList
res = []
while iterator.hasNext()
    append iterator.next() to the end of res
return res

If res matches the expected flattened list, then your code will be judged as correct.

 

Example 1:

Input: nestedList = [[1,1],2,[1,1]]
Output: [1,1,2,1,1]
Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].

Example 2:

Input: nestedList = [1,[4,[6]]]
Output: [1,4,6]
Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].

 

Constraints:

  • 1 <= nestedList.length <= 500
  • The values of the integers in the nested list is in the range [-106, 106].
A:
在stack中保持 List
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* class NestedInteger {
* public:
* // Return true if this NestedInteger holds a single integer, rather than
* a nested list. bool isInteger() const;
*
* // Return the single integer that this NestedInteger holds, if it holds a
* single integer
* // The result is undefined if this NestedInteger holds a nested list
* int getInteger() const;
*
* // Return the nested list that this NestedInteger holds, if it holds a
* nested list
* // The result is undefined if this NestedInteger holds a single integer
* const vector<NestedInteger> &getList() const;
* };
*/

class NestedIterator {
public:
NestedIterator(vector<NestedInteger>& nestedList) {
Slist.push(nestedList);
Sindex.push(0);
}

int next() {
int res = Slist.top()[Sindex.top()].getInteger();
Sindex.top() += 1;
return res;
}

bool hasNext() { // need allow multiple hasNext() while for a single integer
while (!Slist.empty()) {
if (Sindex.top() < Slist.top().size()) {
auto topVal = Slist.top()[Sindex.top()];
if (topVal.isInteger()) {
return true;
} else { // now is a list
Slist.push(topVal.getList());
Sindex.push(0);
}
} else { // now we go beyond the current list
Sindex.pop();
Slist.pop();
if (!Sindex.empty()) {
Sindex.top() += 1;
}
}
}
return false;
}

private:
stack<vector<NestedInteger>> Slist;
stack<int> Sindex;
};

/**
* Your NestedIterator object will be instantiated and called as such:
* NestedIterator i(nestedList);
* while (i.hasNext()) cout << i.next();
*/

******************************************************************
在stack中,直接保持了NestedInteger

class NestedIterator {
public:
NestedIterator(vector<NestedInteger> &nestedList) {
for(int i = nestedList.size()-1; i >= 0 ; i--){
S.push(nestedList[i]);
}
}
int next() {
auto res = S.top().getInteger();
S.pop();
return res;
}
bool hasNext() {
if(S.empty()){
return false;
}
if(S.top().isInteger()){
return true;
}else{
auto top = S.top().getList();
S.pop();
for(int i = top.size()-1; i >= 0 ; i--){
S.push(top[i]);
}
return hasNext();
}
}
private:
stack<NestedInteger> S;
};


Wednesday, April 8, 2020

427. Construct Quad Tree --M

Given a n * n matrix grid of 0's and 1's only. We want to represent the grid with a Quad-Tree.
Return the root of the Quad-Tree representing the grid.
Notice that you can assign the value of a node to True or False when isLeaf is False, and both are accepted in the answer.
A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:
  • val: True if the node represents a grid of 1's or False if the node represents a grid of 0's. 
  • isLeaf: True if the node is leaf node on the tree or False if the node has the four children.
class Node {
    public boolean val;
    public boolean isLeaf;
    public Node topLeft;
    public Node topRight;
    public Node bottomLeft;
    public Node bottomRight;
}
We can construct a Quad-Tree from a two-dimensional area using the following steps:
  1. If the current grid has the same value (i.e all 1's or all 0's) set isLeaf True and set val to the value of the grid and set the four children to Null and stop.
  2. If the current grid has different values, set isLeaf to False and set val to any value and divide the current grid into four sub-grids as shown in the photo.
  3. Recurse for each of the children with the proper sub-grid.

If you want to know more about the Quad-Tree, you can refer to the wiki.
Quad-Tree format:
The output represents the serialized format of a Quad-Tree using level order traversal, where null signifies a path terminator where no node exists below.
It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list [isLeaf, val].
If the value of isLeaf or val is True we represent it as 1 in the list [isLeaf, val] and if the value of isLeaf or val is False we represent it as 0.

Example 1:

Input: grid = [[0,1],[1,0]]
Output: [[0,1],[1,0],[1,1],[1,1],[1,0]]
Explanation: The explanation of this example is shown below:
Notice that 0 represnts False and 1 represents True in the photo representing the Quad-Tree.

Example 2:
Input: grid = [[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]]
Output: [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]
Explanation: All values in the grid are not the same. We divide the grid into four sub-grids.
The topLeft, bottomLeft and bottomRight each has the same value.
The topRight have different values so we divide it into 4 sub-grids where each has the same value.
Explanation is shown in the photo below:

Example 3:
Input: grid = [[1,1],[1,1]]
Output: [[1,1]]
Example 4:
Input: grid = [[0]]
Output: [[1,0]]
Example 5:
Input: grid = [[1,1,0,0],[1,1,0,0],[0,0,1,1],[0,0,1,1]]
Output: [[0,1],[1,1],[1,0],[1,0],[1,1]]

Constraints:
  • n == grid.length == grid[i].length
  • n == 2^x where 0 <= x <= 6


A:



Tuesday, April 7, 2020

593. Valid Square --M

Given the coordinates of four points in 2D space, return whether the four points could construct a square.
The coordinate (x,y) of a point is represented by an integer array with two integers.
Example:
Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
Output: True

Note:
  1. All the input integers are in the range [-10000, 10000].
  2. A valid square has four equal sides with positive length and four equal angles (90-degree angles).
  3. Input points have no order.

A:


根据4个边相等。对角线是  sqrt(2)的关系。

class Solution {
public:
    bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {
        if(p1[0] == p2[0] and p2[0] == p3[0]) // if they are same
            return false;
        vector<int> V;
        V.push_back(getLen2(p1,p2));
        V.push_back(getLen2(p1,p3));
        V.push_back(getLen2(p1,p4));
        V.push_back(getLen2(p2,p3));
        V.push_back(getLen2(p2,p4));
        V.push_back(getLen2(p3,p4));
        sort(V.begin(), V.end());
        bool first4Equal = V[0] == V[1] and V[1] == V[2] and V[2] == V[3];
        bool last2Equal = V[4] == V[5];
        bool time2 = V[0]  * 2 == V[5];
        return first4Equal && last2Equal && time2;
    }
private:
    int getLen2(vector<int> & p1, vector<int> & p2)
    {
        int a = p1[0] - p2[0];
        int b = p1[1] - p2[1];
        return a*a + b * b;
    }
};