Showing posts with label hashmap. Show all posts
Showing posts with label hashmap. Show all posts

Tuesday, February 11, 2020

Leetcode 1166 @ Design System Files

1166. Design File System
Medium
You are asked to design a file system which provides two functions:
  • createPath(path, value): Creates a new path and associates a value to it if possible and returns True. Returns False if the path already exists or its parent path doesn't exist.
  • get(path): Returns the value associated with a path or returns -1 if the path doesn't exist.
The format of a path is one or more concatenated strings of the form: / followed by one or more lowercase English letters. For example, /leetcode and /leetcode/problems are valid paths while an empty string and / are not.
Implement the two functions.
Please refer to the examples for clarifications.

Example 1:
Input: 
["FileSystem","createPath","get"]
[[],["/a",1],["/a"]]
Output: 
[null,true,1]
Explanation: 
FileSystem fileSystem = new FileSystem();

fileSystem.createPath("/a", 1); // return true
fileSystem.get("/a"); // return 1
Example 2:
Input: 
["FileSystem","createPath","createPath","get","createPath","get"]
[[],["/leet",1],["/leet/code",2],["/leet/code"],["/c/d",1],["/c"]]
Output: 
[null,true,true,2,false,-1]
Explanation: 
FileSystem fileSystem = new FileSystem();

fileSystem.createPath("/leet", 1); // return true
fileSystem.createPath("/leet/code", 2); // return true
fileSystem.get("/leet/code"); // return 2
fileSystem.createPath("/c/d", 1); // return false because the parent path "/c" doesn't exist.
fileSystem.get("/c"); // return -1 because this path doesn't exist.

Constraints:
  • The number of calls to the two functions is less than or equal to 10^4 in total.
  • 2 <= path.length <= 100
  • 1 <= value <= 10^9
NOTE: create method has been changed on August 29, 2019 to createPath. Please reset to default code definition to get new method signature.
这道题思路很简单,只要把出现过的path和对应的文件当作key-value pair都存起来就好了,那么很容易想到hashmap来做。由于这里有层级递推地查找,也是个应用trie的case。所以hashmap or trie都可以做。
只是用trie的话,trieNode里面存的值,和"/"的处理需要注意。

问题还有follow up, 就是设计一个watch function, 是callback的功能,可以看一看java的callback。Callback就是说,如果在某个被watch的path下面新添了任何文件夹,或者有任何改动,就call callBack function,callback里面自定义干些事情,干什么都行。这样可以维护一个全局的callback数组,里面存被关照的path, 假如在create or create file时,查一下当前path是不是在callback array里面,如果在,就trigger callBack method after modification.

Hashmap的做法

class FileSystem {
    unordered_map<string, int> paths;
public:
    FileSystem() {
        
    }
    
    bool createPath(string path, int value) {
         if (paths.count(path) > 0)
            return false; 
         string cur;
         for (int i = 0; i<path.size(); i++)
         {
             if (i == 0 || path[i] != '/')
             {
                 cur += path[i];
             }
             else if (i != 0 && path[i] == '/')
             {
                 if (paths.count(cur) == 0)
                     return false;
                 else
                 {
                     cur += path[i];
                 }
             }
         }
         paths[path] = value;
         return true;
    }
    
    int get(string path) {
        if (!paths.empty() && paths.count(path) > 0)
        {
            return paths[path];
        }
        return -1;
    }
};


Trie的做法
struct TrieNode {
    unordered_map<string, TrieNode*> child;
    bool isFile;
    int content;

    TrieNode() {
        isFile = false;
        content = -1;
    }
};

class FileSystem {
private:
    TrieNode* root = nullptr;

    vector<string> split(string& path) {
        vector<string> result;
        stringstream ss(path);
        string s;
        while(getline(ss, s, '/'))
        {
            if (s != "")
            {
                result.push_back(s);
            }
        }
        return result;
    }

    bool insert(vector<string>& path, int value) {
        int n = path.size();
        TrieNode* cur = root;
        for (int i = 0; i < n; ++i) {
            if (cur -> child.find(path[i]) == cur -> child.end()) {
                if (i != n - 1) {
                    return false;
                }
                cur -> child[path[i]] = new TrieNode();
            }
            else {
                if (i == n - 1) {
                    return false; // the path already exist
                }
            }
            cur = cur -> child[path[i]];
        }
        cur -> isFile = true;
        cur -> content = value;
        return true;
    }

    int find(vector<string>& path) {
        int n = path.size();
        TrieNode* cur = root;
        for (int i = 0; i < n; ++i) {
            if (cur -> child.find(path[i]) == cur -> child.end()) {
                return -1;
            }
            cur = cur -> child[path[i]];
        }
        return cur -> content;
    }
public:
    FileSystem() {
        root = new TrieNode();
    }
    bool createPath(string path, int value) {
        vector<string> p = split(path);
        return insert(p, value);
    }

    int get(string path) {
        vector<string> p = split(path);
        return find(p);
    }
};

Sunday, February 9, 2020

Leetcode 220 @ Contains Duplicate III

Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3, t = 0
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1, t = 2
Output: true
Example 3:
Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false
从contains duplicate I, II 做过来的。I,II都很简单,hashmap的基本做法。III的话,就是维护一个index k size 的window,找到这个window里面,只要有任意两个数的差小于等于t就可以。但是这一步怎么做呢?
我的做法是,建立一个vector<pair<int, int>> 存值和index,然后sort vector based on value。然后维护一个t size window,每个数字index差值小于等于k的,就返回。
时间复杂度 nlogn + tn => O(nlogn)
注意溢出的问题,就是假如有int_max - negavive number,就溢出了,把它们每个都cast成long.  
class Comparator
{
    public:
    bool operator() (const pair<int, int>& a, const pair<int, int> &b)
        const {
        return a.first < b.first;
    }
};
class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t){
        vector<pair<int, int>> rec;
        for (int i = 0; i<nums.size(); i++)
        {
            rec.push_back({nums[i], i});
        }
        sort(rec.begin(), rec.end(), Comparator());
        for (int i = 0; i<nums.size(); i++)
        {
            int j = i+1;
            while(j < nums.size() && (long)((long)rec[j].first - (long)rec[i].first) <= t)
            {
                int dis = abs(rec[j].second - rec[i].second);
                if (dis <= k) return true;
                j++;
            }
        }
        return false;
    }
};

Thursday, October 17, 2013

Copy List with random pointer@leetcode

刷题必备书籍:Cracking the Coding Interview: 150 Programming Questions and Solutions 

简历:The Google Resume: How to Prepare for a Career and Land a Job at Apple, Microsoft, Google, or any Top Tech Company
算法学习书籍:Introduction to Algorithms
编程珠玑:Programming Pearls (2nd Edition)
C++ 学习:The C++ Programming Language, 4th Edition
经典操作系统书籍,龙书:Operating System Concepts
创业:The Start-up of You: Adapt to the Future, Invest in Yourself, and Transform Your Career

Copy List with Random Pointer


AC Rate: 1399/7131
My Submissions
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
利用一个hashtable,在一边查找random和next的时候一边建立。

Tuesday, September 10, 2013

two sums@leetcode

刷题必备书籍:Cracking the Coding Interview: 150 Programming Questions and Solutions 

简历:The Google Resume: How to Prepare for a Career and Land a Job at Apple, Microsoft, Google, or any Top Tech Company
算法学习书籍:Introduction to Algorithms
编程珠玑:Programming Pearls (2nd Edition)
C++ 学习:The C++ Programming Language, 4th Edition
经典操作系统书籍,龙书:Operating System Concepts
创业:The Start-up of You: Adapt to the Future, Invest in Yourself, and Transform Your Career
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
» Solve this problem

Sunday, September 8, 2013

Longest Consequent Sequence@leetcode

刷题必备书籍:Cracking the Coding Interview: 150 Programming Questions and Solutions 

简历:The Google Resume: How to Prepare for a Career and Land a Job at Apple, Microsoft, Google, or any Top Tech Company
算法学习书籍:Introduction to Algorithms
编程珠玑:Programming Pearls (2nd Edition)
C++ 学习:The C++ Programming Language, 4th Edition
经典操作系统书籍,龙书:Operating System Concepts
创业:The Start-up of You: Adapt to the Future, Invest in Yourself, and Transform Your Career
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
» Solve this problem

Because it has to be solved in O(n) time. Thus, normal sorting algorithm cannot be applied here. So hashmap came to my mind, to quick allocate the element.

Algorithm:
1. Create a hashmap to store the given sequence
2. Create a vector to mark visited elements and avoid duplicate search
3. search num[i] +1 and num[i]-1 iteratively, and set count.
4. Return the longest length we found.


Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...