Sunday, May 27, 2018

325 Maximum Size Subarray Sum Equals k

325Maximum Size Subarray Sum Equals k
Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isn't one, return 0 instead.
Note:
The sum of the entire nums array is guaranteed to fit within the 32-bit signed integer range.
Example 1:
Input: nums = [1, -1, 5, -2, 3], k = 3
Output: 4 
Explanation: The subarray [1, -1, 5, -2] sums to 3 and is the longest.
Example 2:
Input: nums = [-2, -1, 2, 1], k = 1
Output: 2 
Explanation: The subarray [-1, 2] sums to 1 and is the longest.
Follow Up:
Can you do it in O(n) time?
---------------------
Solution #1
Map里key = [0 - i] 的和,value = i.
因为要找的是最左边的点(与当前i距离最远),所以遇到重复的key可以跳过
class Solution {
    public int maxSubArrayLen(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        int len = 0;
        int sofar = 0;
        
        for (int i = 0; i < nums.length; i++) {
            sofar += nums[i];
            if (sofar == k) len = i + 1;
            if (map.containsKey(sofar - k)) {
                len = Math.max(len, i - map.get(sofar - k));
            }
            
            if (!map.containsKey(sofar)) map.put(sofar, i);
        }
        
        return len;
    }
}

Tuesday, May 22, 2018

621 Task Scheduler

621Task Scheduler
Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks.Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle.
However, there is a non-negative cooling interval n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle.
You need to return the least number of intervals the CPU will take to finish all the given tasks.
Example 1:
Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.
Note:

  1. The number of tasks is in the range [1, 10000].
  2. The integer n is in the range [0, 100].
------------------------
Solution #1, 数empty slots。Leetcode上有讲解
复杂度是O(n), n等于task的数量
另一种类似方法是计算相同最大出现次数元素的个数。[A3,B3,C1,D1], 个数为2,A和B。
class Solution {
    public int leastInterval(char[] tasks, int n) {
        int[] map = new int[26];
        
        for (char c : tasks) {
            map[c - 'A']++;
        }
        
        Arrays.sort(map);
        
        int maxCount = map[25] - 1;
        int slots = maxCount * n;
        for (int i = 24; i >= 0; i--) {
            slots -= Math.min(maxCount, map[i]);
        }
        
        if (slots > 0) {
            return slots + tasks.length;
        }
        return tasks.length;
    }
}

Solution#2,priority queue
class Solution {
    public int leastInterval(char[] tasks, int n) {
        int[] map = new int[26];
        
        for (char c : tasks) {
            map[c - 'A']++;
        }
        
        PriorityQueue<Integer> queue = new PriorityQueue<>(26, Collections.reverseOrder());
        for (int i : map) {
            queue.add(i);
        }
        
        int top = queue.poll();
        int count = top;
        for (int i = 0; i < top - 1; i++) {
            List<Integer> hold = new ArrayList<>();
            int index = 0;
            while (index < n && !queue.isEmpty()) {
                int pop = queue.poll() - 1;
                if (pop > 0) {
                    hold.add(pop);
                }
                
                index++;
                count++;
            }
            count += n - index;
            
            for (int j : hold) {
                queue.add(j);
            }
        }
        
        while (!queue.isEmpty()) {
            count += queue.poll();
        }
        
        return count;
    }
}

Sunday, May 6, 2018

388, 683 Longest Absolute File Path, K Empty Slots

388. Longest Absolute File Path

Suppose we abstract our file system by a string in the following manner:
The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents:
dir
    subdir1
    subdir2
        file.ext
The directory dir contains an empty sub-directory subdir1 and a sub-directory subdir2 containing a file file.ext.
The string "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext" represents:
dir
    subdir1
        file1.ext
        subsubdir1
    subdir2
        subsubdir2
            file2.ext
The directory dir contains two sub-directories subdir1 and subdir2. subdir1 contains a file file1.ext and an empty second-level sub-directory subsubdir1. subdir2 contains a second-level sub-directory subsubdir2 containing a file file2.ext.
We are interested in finding the longest (number of characters) absolute path to a file within our file system. For example, in the second example above, the longest absolute path is "dir/subdir2/subsubdir2/file2.ext", and its length is 32 (not including the double quotes).
Given a string representing the file system in the above format, return the length of the longest absolute path to file in the abstracted file system. If there is no file in the system, return 0.
Note:

  • The name of a file contains at least a . and an extension.
  • The name of a directory or sub-directory will not contain a ..

Time complexity required: O(n) where n is the size of the input string.
Notice that a/aa/aaa/file1.txt is not the longest file path, if there is another path aaaaaaaaaaaaaaaaaaaaa/sth.png.
----------------------------------
1. Get the current level
2. Keep the length-so-far of previous levels in stack or array.

 Solution #1, with Stack
class Solution {
    public int lengthLongestPath(String input) {
        Stack<Integer> s = new Stack<>();
        int currentLevel = 1;
        int index = 0;
        String str = "";
        int maxLength = 0;

        while (index <= input.length()) {
            if (index == input.length() || input.charAt(index) == '\n') {
                while (currentLevel - s.size() <= 0 && !s.isEmpty()) {
                    s.pop();
                }

                int currentLength = 0;
                if (!s.isEmpty()) {
                    currentLength = s.peek() + 1;
                }
                currentLength += str.length();
                s.push(currentLength);
                
                if (isFile(str)) {
                    maxLength = Math.max(maxLength, currentLength);
                }
                
                currentLevel = 1;
                str = "";
            } else if (input.charAt(index) == '\t') {
                currentLevel++;
            } else {
                str += input.charAt(index);
            }
            index++;
        }

        return maxLength;
    }
    
    private static boolean isFile(String str) {
        return  str.indexOf(".") > -1;
    } 
}

Solution #2, with array
class Solution {
    public int lengthLongestPath(String input) {
        List<Integer> levels = new ArrayList<>();
        int index = 0;
        int currentLevel = 0;
        StringBuilder stb = new StringBuilder();
        int maxLength = 0;
        
        while (index <= input.length()) {
            if (index == input.length() || input.charAt(index) == '\n') {
                int preLevelSum = getPreLevel(currentLevel - 1, levels);
                int currentLength = preLevelSum + stb.length();
                
                levels.add(currentLevel, currentLength);
                if (isFile(stb.toString())) {
                    maxLength = Math.max(maxLength, currentLength);
                }
                
                stb = new StringBuilder();
                currentLevel = 0;
            } else if (input.charAt(index) == '\t') {
                currentLevel++;
            } else {
                stb.append(input.charAt(index));
            }
            
            index++;
        }
        
        return maxLength;
    }
    
    private int getPreLevel(int level, List<Integer> levels) {
        if (level < 0) {
            return 0;
        }
        
        return levels.get(level) + 1;
    }
    
    private static boolean isFile(String str) {
        return  str.indexOf(".") > -1;
    }
}
Shorter version, from online
class Solution {
    public int lengthLongestPath(String input) {
        String[] paths = input.split("\n");
        int[] stack = new int[paths.length+1];
        int maxLen = 0;
        for(String s : paths){
            int level = s.lastIndexOf("\t") + 1;
            int currentLength = stack[level] + s.length() - level + 1;
            stack[level + 1] = currentLength;
            if(s.contains(".")) {
                maxLen = Math.max(maxLen, currentLength - 1);
            }
        }
        return maxLen;
    }
}


683K Empty Slots
There is a garden with N slots. In each slot, there is a flower. The N flowers will bloom one by one in N days. In each day, there will be exactly one flower blooming and it will be in the status of blooming since then.
Given an array flowers consists of number from 1 to N. Each number in the array represents the place where the flower will open in that day.
For example, flowers[i] = x means that the unique flower that blooms at day i will be at position x, where i and x will be in the range from 1 to N.
Also given an integer k, you need to output in which day there exists two flowers in the status of blooming, and also the number of flowers between them is k and these flowers are not blooming.
If there isn't such day, output -1.
Example 1:
Input: 
flowers: [1,3,2]
k: 1
Output: 2
Explanation: In the second day, the first and the third flower have become blooming.
Example 2:
Input: 
flowers: [1,2,3]
k: 1
Output: -1
Note:

  1. The given array will be in the range [1, 20000].
------------------------------
Solution #1
1. 建立flower -> day的对应days[]
2. 对于i和 i+k+1 位置的花,如果中间所有的位置开花时间比两者都大,则可以确认i和i+k+1为可能的答案

class Solution {
    public int kEmptySlots(int[] flowers, int k) {  
        int len = flowers.length + 1;
        int[] days = reverseFlowers(flowers);

        int prePos = 1;
        int futurePos = prePos + k + 1;
        int index = prePos + 1;
        int shortest = Integer.MAX_VALUE;
        while (index < len && futurePos < len) {
            if (index == futurePos) {
                shortest = Math.min(shortest, Math.max(days[futurePos], days[prePos]));
                prePos = index;
                futurePos = prePos + k + 1;
            } else if (days[index] < days[futurePos] || days[index] < days[prePos]) {
                prePos = index;
                futurePos = prePos + k + 1;
            }

            index++;
        }

        return shortest == Integer.MAX_VALUE ? -1 : shortest;
    }
    
    private int[] reverseFlowers(int[] flowers) {
        int len = flowers.length + 1;
        int days[] = new int[len];
        
        for (int i = 1; i < len; i++) {
            days[flowers[i - 1]] = i;
        }
        
        return days;
    }
}

这题有点范围搜索的意思
Solution #2
每开完一朵花,分别检查它左右范围(k+1)的花是否开放,且两者之间的花都未开放
参考:http://zxi.mytechroad.com/blog/simulation/leetcode-683-k-empty-slots/
class Solution {
    public int kEmptySlots(int[] flowers, int k) {
        int len = flowers.length;
        boolean[] bloomed = new boolean[len];
        int minDay = Integer.MAX_VALUE;
        
        for (int i = 0; i < len; i++) {
            int pos = flowers[i] - 1;
            if (isValidDay(pos, bloomed, k)) {
                return i + 1;
            }
        }
        
        return -1;
    }
    
    public boolean isValidDay(int pos, boolean[] bloomed, int k) {
        int len = bloomed.length;
        bloomed[pos] = true;
        if (pos + k + 1 < len && bloomed[pos + k + 1]) {
            boolean valid = true;
            for (int i = pos + 1; i < pos + k + 1; i++) {
                if (bloomed[i]) {
                    valid = false;
                    break;
                }
            }
            
            if (valid) return true;
        }
        
        if (pos - k - 1 >= 0 && bloomed[pos - k - 1]) {
            boolean valid = true;
            for (int i = pos - k; i < pos; i++) {
                if (bloomed[i]) {
                    return false;
                }
            }
            
            return true;
        }
        
        return false;
    }
}
Solution #3, 用BinarySearchTree来存开过花的位置
class Solution {
    public int kEmptySlots(int[] flowers, int k) {
        TreeSet<Integer> bst = new TreeSet<>();
        for (int i = 0; i < flowers.length; i++) {
            int pos = flowers[i];
            bst.add(pos);
            Integer lower = bst.lower(pos);
            Integer higher = bst.higher(pos);
            if (bst.lower(pos) != null) {
                if (pos - lower == k + 1) {
                    return i + 1;
                }
            }
            if (bst.higher(pos) != null) {
                if (pos + k + 1 == higher) {
                    return i + 1;
                }
            }
        }
        
        return -1;
    }
}
Solution #4, 类似bucket sort,每个bucket的大小为 k + 1
class Solution {
    public int kEmptySlots(int[] flowers, int k) {
        int len = flowers.length;
        int bucketSize = (len + k) / (k + 1);
        List<Integer> lower = getBucket(Integer.MAX_VALUE, bucketSize);
        List<Integer> higher = getBucket(Integer.MIN_VALUE, bucketSize);

        for (int i = 0; i < len; i ++) {
            int slot = flowers[i];
            int curBucket = (slot - 1) / (k + 1);
            if (slot < lower.get(curBucket)) {
                lower.set(curBucket, slot);
                if (curBucket > 0 && slot - k - 1 == higher.get(curBucket - 1)) {
                    return i + 1;
                }
            }

            if (slot > higher.get(curBucket)) {
                higher.set(curBucket, slot);
                if (curBucket < bucketSize - 1 && slot + k + 1== lower.get(curBucket + 1)) {
                    return i + 1;
                }
            }
        }

        return -1;
    }
    
    public List<Integer> getBucket(int fill, int size) {
        List<Integer> rt = new ArrayList<>();
        for (int i = 0; i < size; i ++) {
            rt.add(fill);
        }
        return rt;
    }
}

Saturday, March 25, 2017

Day 136, 380, Insert Delete GetRandom O(1)

380. Insert Delete GetRandom O(1)
Design a data structure that supports all following operations in average O(1) time.
  1. insert(val): Inserts an item val to the set if not already present.
  2. remove(val): Removes an item val from the set if present.
  3. getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.
class RandomizedSet {
    private static Random random = new Random();
    private List<Integer> list;
    private Map<Integer, Integer> map;
    private int size;
    /** Initialize your data structure here. */
    public RandomizedSet() {
        size = 0;
        list = new ArrayList<>();
        map = new HashMap<>();
    }
    
    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    public boolean insert(int val) {
        if (map.containsKey(val)) return false;
        map.put(val, size);
        if (list.size() == size) {
            list.add(size, val);   
        }else {
            list.set(size, val);
        }
        size++;
        
        return true;
    }
    
    /** Removes a value from the set. Returns true if the set contained the specified element. */
    public boolean remove(int val) {
        if (!map.containsKey(val)) return false;
        
        int pos = map.get(val);
        int value = list.get(size - 1);
        list.set(pos, value);
        map.put(value, pos);
        size--;
        map.remove(val);
        
        return true;
    }
    
    /** Get a random element from the set. */
    public int getRandom() {
        return list.get(random.nextInt(size));
    }
}

/**
 * Your RandomizedSet object will be instantiated and called as such:
 * RandomizedSet obj = new RandomizedSet();
 * boolean param_1 = obj.insert(val);
 * boolean param_2 = obj.remove(val);
 * int param_3 = obj.getRandom();
 */

Follow up: duplicates are allowed.
Use Set as values in the map

Saturday, March 18, 2017

Day 135, 532, 438, 387, 459, K-diff Pairs in an Array, Find All Anagrams in a String, First Unique Character in a String, Repeated Substring Pattern

532. K-diff Pairs in an Array
Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k.
Example 1:
Input: [3, 1, 4, 1, 5], k = 2
Output: 2
Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
Although we have two 1s in the input, we should only return the number of unique pairs.
Example 2:
Input:[1, 2, 3, 4, 5], k = 1
Output: 4
Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).
Example 3:
Input: [1, 3, 1, 5, 4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).
Note:
  1. The pairs (i, j) and (j, i) count as the same pair.
  2. The length of the array won't exceed 10,000.
  3. All the integers in the given input belong to the range: [-1e7, 1e7].
public class Solution {
    public int findPairs(int[] nums, int k) {
        if (k < 0) return 0;
        
        Set<Integer> set = new HashSet<>();
        Set<Integer> firtInPair = new HashSet<>();
        
        for (int i = 0; i < nums.length; i++) {
            int cur = nums[i];
            if (set.contains(cur + k)) {
                firstInPair.add(cur);
            }
            if (set.contains(cur - k)) {
                firstInPair.add();
            }
            set.add(cur);
        }
        
        return cur.size();
    }
}


438. Find All Anagrams in a String
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
The order of output does not matter.
Example 1:
Input:
s: "cbaebabacd" p: "abc"

Output:
[0, 6]

Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".
Example 2:
Input:
s: "abab" p: "ab"

Output:
[0, 1, 2]

Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".
Sliding window
另一种写法是用array[256]来代替Map,代码会更简洁。因为array[char] == 0可以同时代表没有出现过的char和已经用完的char
public class Solution {
    public List findAnagrams(String s, String p) {
        Map occurance = getOccurance(p);
        return findIndexes(s, p.length(), occurance, new HashMap<>(occurance));
    }
    
    private Map getOccurance(String p) {
        Map occ = new HashMap<>();
        
        for (int i = 0; i < p.length(); i++) {
            char c = p.charAt(i);
            if (occ.containsKey(c)) {
                occ.put(c, occ.get(c) + 1);
            } else {
              occ.put(c, 1);  
            }
        }
        
        return occ;
    }
    
    private List findIndexes(String s, int count, Map occ, Map backup) {
        
        List rt = new ArrayList<>();
        int start = 0;
        for (int i = 0; i < s.length(); i++) {
            char c =s.charAt(i);
            if (!occ.containsKey(c)) {
                // reset
                occ = new HashMap<>(backup);
                start = i + 1;
                count = occ.size();
                continue;
            }
            
            while (occ.get(c) == 0) {
                occ.put(s.charAt(start), occ.get(s.charAt(start)) + 1);
                start++;
                count++;
            }
            
            count--;
            if (count == 0) {
                rt.add(start);
            }
            occ.put(c, occ.get(c) - 1);
        }
        
        return rt;
    }
}
387. First Unique Character in a String
Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
Examples:
s = "leetcode"
return 0.

s = "loveleetcode",
return 2.

Note: You may assume the string contain only lowercase letters.
public class Solution {
    public int firstUniqChar(String s) {
        int occ[] = new int[256];
        
        for (int i = 0; i < s.length(); i++) {
            int val = s.charAt(i) - '0';
            occ[val]++;
        }
        
        for (int i = 0; i < s.length(); i++) {
            int val = s.charAt(i) - '0';
            if (occ[val] == 1) {
                return i;
            }
        }
        
        return -1;
    }
}
459. Repeated Substring Pattern
Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.
Example 1:
Input: "abab"

Output: True

Explanation: It's the substring "ab" twice.
Example 2:
Input: "aba"

Output: False
Example 3:
Input: "abcabcabcabc"

Output: True

Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)
可以用KMP
以下方法可以稍微再简化:inner loop里可以把所有的substring加起来然后跟原来的比较
public class Solution {
    public boolean repeatedSubstringPattern(String s) {
        
        for (int i = 0; i < s.length() / 2; i++) {
            if (s.length() % (i + 1) != 0) {
                continue;
            }
            
            String sub = s.substring(0, i + 1);
            boolean flag = true;
            for (int j = i + 1; j < s.length() - i; j += i + 1) {
                String secSub = s.substring(j, j + i + 1);
                if (!secSub.equals(sub)) {
                    flag = false;
                    break;
                }
            }
            if (flag == true) return true;
        }
        
        return false;
    }
}

Saturday, November 14, 2015

Day 134, #302 #305 Smallest Rectangle Enclosing Black Pixels, Number of Islands II

Smallest Rectangle Enclosing Black Pixels
An image is represented by a binary matrix with 0 as a white pixel and 1 as a black pixel. The black pixels are connected, i.e., there is only one black region. Pixels are connected horizontally and vertically. Given the location (x, y) of one of the black pixels, return the area of the smallest (axis-aligned) rectangle that encloses all black pixels.
For example, given the following image:
[
  "0010",
  "0110",
  "0100"
]
and x = 0y = 2,
Return 6.
----------------------------------------------------------------------
COME_BACK, mid的取值问题
binary search
getTop()和getLeft() 返回的都是包含black,其他2个返回的是不包含black。
稍微简单一点写法:https://leetcode.com/discuss/68246/c-java-python-binary-search-solution-with-explanation
class Solution {
public:
    int getTop(vector<vector<char>>& image, int x) {
        int top = 0, bottom = x, n = image[0].size();
        
        while (top < bottom) {
            int mid = (top + bottom) / 2;
            int k = 0;
            while (k < n && image[mid][k] == '0') {
                k++;
            }
            
            if (k < n) {
                bottom = mid;
            }else {
                top = mid + 1;
            }
        }
        
        return bottom;
    }
    
    int getBottom(vector<vector<char>>& image, int x) {
        int top = x, bottom = image.size(), n = image[0].size();
        
        while (top < bottom) {
            int mid = (top + bottom) / 2;
            int k = 0;
            while (k < n && image[mid][k] == '0') {
                k++;
            }
            
            if (k < n) {
                top = mid + 1;
            }else {
                bottom = mid;
            }
        }
        
        return bottom;
    }
    
    int getLeft(vector<vector<char>>& image, int y) {
        int left = 0, right = y, m = image.size();
        
        while (left < right) {
            int mid = (left + right) / 2;
            int k = 0;
            while (k < m && image[k][mid] == '0') {
                k++;
            }
            
            if (k < m) {
                right = mid;
            }else {
                left = mid + 1;
            }
        }
        return left;
    }
    
    int getRight(vector<vector<char>>& image, int y) {
        int right = image[0].size(), left = y, m = image.size();
        while (left < right) {
            int mid = (left + right) / 2;
            int k = 0;
            while (k < m && image[k][mid] == '0') {
                k++;
            }
            
            if (k < m) {
                left = mid + 1;
            }else {
                right = mid;
            }
        }
        
        return left;
    }

    int minArea(vector<vector<char>>& image, int x, int y) {
        int top = getTop(image,x);
        int bottom = getBottom(image,x + 1);
        int left = getLeft(image,y);
        int right = getRight(image,y + 1);
        
        return (bottom - top) * (right - left);
    }
};

Number of Islands II
A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand operation which turns the water at position (row, col) into a land. Given a list of positions to operate, count the number of islands after each addLand operation. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example:
Given m = 3, n = 3positions = [[0,0], [0,1], [1,2], [2,1]].
Initially, the 2d grid grid is filled with water. (Assume 0 represents water and 1 represents land).
0 0 0
0 0 0
0 0 0
Operation #1: addLand(0, 0) turns the water at grid[0][0] into a land.
1 0 0
0 0 0   Number of islands = 1
0 0 0
Operation #2: addLand(0, 1) turns the water at grid[0][1] into a land.
1 1 0
0 0 0   Number of islands = 1
0 0 0
Operation #3: addLand(1, 2) turns the water at grid[1][2] into a land.
1 1 0
0 0 1   Number of islands = 2
0 0 0
Operation #4: addLand(2, 1) turns the water at grid[2][1] into a land.
1 1 0
0 0 1   Number of islands = 3
0 1 0
We return the result as an array: [1, 1, 2, 3]
Challenge:
Can you do it in time complexity O(k log mn), where k is the length of the positions?
-------------------------------------------------------
COME_BACK
标准union find, O(k * lg k), k 为 0 - m * n
注意:
#1 2维坐标和1维的来回转换
#2 看清题意,对count的计算
class UnionFind {
public:
    UnionFind(vector<pair<int, int>>& positions, int col) {
        this->col = col;
        count = 0;
    }
    
    void addPoint(pair<int,int> &p) {
        int index = encode(p);
        root[index] = index;
        size[index] = 1;
        count++;
    }
 
    int findRoot(pair<int,int> &p) {
        int index = encode(p);
        if (root.find(index) == root.end()) return -1;
        
        while (root[index] != index) {
            index = root[index];
        }
        return index;
    }

    void unionF(pair<int,int> &p1, pair<int,int> &p2) {
        int root1 = findRoot(p1), root2 = findRoot(p2);
        if (root1 == root2) return;
        
        if (size[root1] > size[root2]) {
            size[root1] += size[root2];
            root[root2] = root1;
        }else {
            root[root1] = root2;
        }
        count--;
    }
    
    int getCount() {
        return count;
    }

private:
    unordered_map<int,int> root;
    unordered_map<int,int> size;
    int count;
    int col;
    
    int encode(pair<int, int> &position) {
        return position.first * col + position.second;
    }
    
    pair<int,int> decode(int index) {
        return make_pair<int,int>(index / col, index % col);
    }
};

class Solution {
public:
    vector<int> numIslands2(int m, int n, vector<pair<int, int>>& positions) {
        vector<int> rt;
        UnionFind uf(positions, n);
        
        for (int i = 0; i < positions.size(); i++) {
            uf.addPoint(positions[i]);
            int x = positions[i].first, y = positions[i].second;
            pair<int,int> p = make_pair(x + 1, y);
            if (x + 1 < m && uf.findRoot(p) != - 1) {
                uf.unionF(positions[i], p);
            }
            
            p = make_pair(x - 1,y);
            if (x - 1 >= 0 && uf.findRoot(p) != - 1) {
                uf.unionF(positions[i], p);
            }
            
            p = make_pair(x, y + 1);
            if (y + 1 < n && uf.findRoot(p) != - 1) {
                uf.unionF(positions[i],p);
            }
            
            p = make_pair(x, y - 1);
            if (y - 1 >= 0 && uf.findRoot(p) != - 1) {
                uf.unionF(positions[i], p);
            }
            rt.push_back(uf.getCount());
        }
        
        return rt;
    }
};

Java, ids类似于一个树。注意2处可以优化的地方。 O(k * log m * n), k为插入的次数,log(m*n)为树的深度(find()方法),完全优化后深度为1
https://blog.csdn.net/dm_vincent/article/details/7655764
https://blog.csdn.net/dm_vincent/article/details/7769159 UnionFind更多应用
 
class Solution {
    
    private int[][] dirs = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
    
    public List numIslands2(int m, int n, int[][] positions) {
        List rt = new ArrayList<>();
        UnionFind uf = new UnionFind(m,n);
        
        for (int[] pos : positions) {
            uf.add(pos);
            int p = uf.getRootId(pos[0], pos[1]);
            for (int[] dir : dirs) {
                int i = pos[0] + dir[0];
                int j = pos[1] + dir[1];
                int q = uf.getRootId(i, j);
                if (q > 0 && q != p) {
                    uf.union(pos[0], pos[1], i, j);
                }
            }   
            
            rt.add(uf.getCount());
        }
        
        return rt;
    }
}

class UnionFind {
    
    private int count;
    private int[] ids;
    private int[] sizes;
    private int m;
    private int n;
    
    public UnionFind(int m, int n) {
        count = 0;
        ids = new int[m * n + 1];
        sizes = new int[m * n + 1];
        this.m = m;
        this.n = n;
    }
    
    public int getRootId(int i, int j) {
        if (i >= 0 && i < m && j >= 0 && j < n) {
            int index = getIndex(i,j);
            if ((ids[index]) == 0) return 0;
            return find(i, j);
        }
        
        return 0;
    }
    
    public void add(int[] pos) {
        int id = getIndex(pos[0], pos[1]);
        ids[id] = id;
        sizes[id] = 1;
        count++;
    }
    
    public int find(int i, int j) {
        int id = getIndex(i,j);
        while (ids[id] != id) {
            ids[id] = ids[ids[id]]; // Optimization
            id = ids[id];
        }
        
        return id;
    }
    
    public void union(int pI, int pJ, int qI, int qJ) {
        int rootP = find(pI, pJ);
        int rootQ = find(qI, qJ);
        
        if (rootP == rootQ) return;
        
        if (sizes[rootP] >= sizes[rootQ]) { // Optimization
            sizes[rootP] += sizes[rootQ];
            ids[rootQ] = rootP;    
        }else {
            sizes[rootQ] += sizes[rootP];
            ids[rootP] = rootQ;    
        }
        
        count--;
    }
    
    public int getCount() {
        return count;
    }
    
    private int getIndex(int i, int j) {
        return i * n + j + 1;
    }
}

Tuesday, November 3, 2015

Day 133, #297 #299 #300 #301 Serialize and Deserialize Binary Tree, Bulls and Cows, Longest Increasing Subsequence, Remove Invalid Parentheses

Serialize and Deserialize Binary Tree
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
For example, you may serialize the following tree
    1
   / \
  2   3
     / \
    4   5
as "[1,2,3,null,null,4,5]", just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
----------------------------------------------------------
遍历
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Codec {
public:

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        queue<TreeNode *> que;
        que.push(root);
        string s = "";
        
        while (!que.empty()) {
            TreeNode *t = que.front();
            que.pop();
            if (t == NULL) {
                s += "n";
            }else {
                s += to_string(t->val) + ",";
                que.push(t->left);
                que.push(t->right);
            }
        }
        
        return s;
    }

    int next(string data, int &i) {
        int rt = 0, sign = 1;
        if (data[i] == '-') {
            sign = -1;
            i++;
        }
        while (isdigit(data[i])) {
            rt = rt * 10 + data[i] - '0';
            i++;
        }
        i++;
        return rt * sign;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        if (data == "n") return NULL;
        queue<TreeNode *> que;
        int i = 0;
        TreeNode *root = new TreeNode(next(data,i));
        que.push(root);
        
        while (!que.empty()) {
            TreeNode* t = que.front();
            que.pop();
            
            if (isdigit(data[i]) || data[i] == '-') {
                t->left = new TreeNode(next(data,i));
                que.push(t->left);
            }else {
                i++;
            }
            
            if (isdigit(data[i]) || data[i] == '-') {
                t->right = new TreeNode(next(data,i));
                que.push(t->right);
            }else {
                i++;
            }
        }
        
        return root;
    }
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));

Java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Codec {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if (root == null) return "";
        
        StringBuilder sb = new StringBuilder();
        Queue<TreeNode> que = new LinkedList<>();
        que.add(root);
        
        while (!que.isEmpty()) {
            TreeNode top = que.poll();
            if (top == null) {
                sb.append("n").append(",");
            } else {
                sb.append(top.val).append(",");
                que.add(top.left);
                que.add(top.right);
            }
        }
        
        return sb.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if (data == null || data.length() == 0) {
            return null;
        }
        List<String> l = Arrays.asList(data.split(","));
        Queue<TreeNode> que = new LinkedList<>();
        TreeNode root = new TreeNode(Integer.parseInt(l.get(0)));
        que.add(root);
        for (int i = 1; i < l.size(); i += 2) {
            TreeNode node = que.poll();
            if (l.get(i).equals("n")) {
                node.left = null;
            } else {
                TreeNode left = new TreeNode(Integer.parseInt(l.get(i)));
                node.left = left;
                que.add(left);
            }
            if (l.get(i + 1).equals("n")) {
                node.right = null;
            } else {
                TreeNode right = new TreeNode(Integer.parseInt(l.get(i + 1)));
                node.right = right;
                que.add(right);
            }
        }
        
        return root;
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));

递归
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Codec {
public:
    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        if (root == NULL) {
            return "n";
        }
        string rt = to_string(root->val) + ",";
        rt += serialize(root->left) + serialize(root->right);
        return rt;
    }

    TreeNode *helper(string &s, int &i) {
        if (i == s.length()) return NULL;
        if (s[i] == 'n') {
            i++;
            return NULL;
        }
        
        int sign = 1;
        if (s[i] == '-') {
            sign = -1;
            i++;
        }
        int rt = 0;
        while (isdigit(s[i])) {
            rt = rt * 10 + s[i] - '0';
            i++;
        }
        i++;
        
        TreeNode *root = new TreeNode(rt * sign);
        root->left = helper(s,i);
        root->right = helper(s,i);
        return root;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        int i = 0;
        return helper(data,i);
    }
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));

Java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Codec {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        buildString(root, sb);
        return sb.toString();
    }
    
    private void buildString(TreeNode root, StringBuilder sb) {
        if (root == null) {
            sb.append("n").append(",");
            return;
        }
        
        sb.append(root.val).append(",");
        buildString(root.left, sb);
        buildString(root.right, sb);
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        List<String> s = Arrays.asList(data.split(","));
        return toNode(s);
    }
    
    private int index = 0;
    private TreeNode toNode(List<String> s) {
        if (s.get(index).equals("n")) {
            index++;
            return null;
        }
        
        TreeNode node = new TreeNode(Integer.parseInt(s.get(index)));
        index++;
        node.left = toNode(s);
        node.right = toNode(s);
        
        return node;
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));

Bulls and Cows
You are playing the following Bulls and Cows game with your friend: You write a 4-digit secret number and ask your friend to guess it. Each time your friend guesses a number, you give a hint. The hint tells your friend how many digits are in the correct positions (called "bulls") and how many digits are in the wrong positions (called "cows"). Your friend will use those hints to find out the secret number.
For example:
Secret number:  "1807"
Friend's guess: "7810"
Hint: 1 bull and 3 cows. (The bull is 8, the cows are 01 and 7.)
Write a function to return a hint according to the secret number and friend's guess, use A to indicate the bulls and B to indicate the cows. In the above example, your function should return "1A3B".
Please note that both secret number and friend's guess may contain duplicate digits, for example:
Secret number:  "1123"
Friend's guess: "0111"
In this case, the 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow, and your function should return "1A1B".
You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.
--------------------------------------------------------
class Solution {
public:
    string getHint(string secret, string guess) {
        vector<int> upper(256,0);
        vector<int> lower(256,0);
        int bull = 0, cow = 0;
        
        for (int i = 0; i < guess.length(); i++) {
            if (secret[i] == guess[i]) {
                bull++;
            }else {
                if (upper[guess[i]] > 0) {
                    cow++;
                    upper[guess[i]]--;
                }else {
                    lower[guess[i]]++;
                }
                
                if (lower[secret[i]] > 0) {
                    cow++;
                    lower[secret[i]]--;
                }else {
                    upper[secret[i]]++;
                }
            }
        }
        
        return to_string(bull) + "A" + to_string(cow) + "B";
    }
};

Longest Increasing Subsequence
Given an unsorted array of integers, find the length of longest increasing subsequence.
For example,
Given [10, 9, 2, 5, 3, 7, 101, 18],
The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length.
Your algorithm should run in O(n2) complexity.
Follow up: Could you improve it to O(n log n) time complexity?
--------------------------------------------------------------
Solution #1, dp[i] 里存的是以i为后一位的,[0, i]之间的最长递增subsequence

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

Solution #2, N(lg N)
refhttp://www.geeksforgeeks.org/longest-monotonically-increasing-subsequence-size-n-log-n/
原理:
假设我们有[100, 101, 102, 1, ......], 当处理到[3]的时候,我们不能把前3位的信息抛弃,只有当以1开头的subsequence长度>= 3时,才能将之前的3位丢掉。这时一个方法是把所有的subsequence信息都记录下来,然后每次对比长度。另一个方法就是下面这个,进行元素替换。

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        if (nums.size() == 0) return 0;
        vector<int> arr(1,nums[0]);
        
        for (int i = 1; i < nums.size(); i++) {
            if (nums[i] < arr[0]) {
                arr[0] = nums[i];
            }else if (nums[i] > arr.back()) {
                arr.push_back(nums[i]);
            }else {
                int low = 0, high = arr.size() - 1;
                while (low <= high) {
                    int mid= (low + high) / 2;
                    if (mid > 0 && arr[mid - 1] <= nums[i] && arr[mid] > nums[i]) {
                        arr[mid] = nums[i];
                        break;
                    }
                    if (arr[mid] < nums[i]) {
                        low = mid + 1;
                    }else {
                        high = mid - 1;
                    }
                }
            }
        }
        
        return arr.size();
    }
};

Remove Invalid Parentheses
Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.
Note: The input string may contain letters other than the parentheses ( and ).
Examples:
"()())()" -> ["()()()", "(())()"]
"(a)())()" -> ["(a)()()", "(a())()"]
")(" -> [""]

--------------------------------------------------
都是brute force,以下为bfs
class Solution {
public:
    bool isValid(string s) {
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s[i] == '(') count++;
            if (s[i] == ')') count--;
            if (count < 0) return false;
        }
        
        return count == 0;
    }

    vector<string> removeInvalidParentheses(string s) {
        queue<string> que;
        unordered_set<string> dic;
        que.push(s);
        dic.insert(s);
        vector<string> rt;
        bool found = false;
        
        while (!que.empty()) {
            string str = que.front();
            que.pop();
            if (isValid(str)) {
                rt.push_back(str);
                found = true;
            }
            
            if (found) continue;
            
            for (int i = 0; i < str.length(); i++) {
                if (str[i] != '(' && str[i] != ')') continue;
                
                string newStr = str.substr(0,i) + str.substr(i + 1);
                if (dic.find(newStr) == dic.end()) {
                    que.push(newStr);
                    dic.insert(newStr);
                }
            }
        }
        
        return rt;
    }
};

dfs, ref: http://blog.csdn.net/foreverling/article/details/49740665
remove the minimum number等于是建立一个最长的有效括号字符串
class Solution {
public:
    void dfs(vector<string> &rt, string s, string curS, int left, int totalLeft, int &maxLen, unordered_set<string> &dic) {
        if (s.length() == 0) {
            if (left == 0 && totalLeft > maxLen) {
                maxLen = totalLeft;
            }
            if (left == 0 && maxLen == totalLeft && dic.find(curS) == dic.end()) {
                rt.push_back(curS);
                dic.insert(curS);
            }
            return;
        }
        
        if (s[0] == '(') {
            dfs(rt,s.substr(1), curS + '(', left + 1, totalLeft + 1, maxLen,dic);
            dfs(rt,s.substr(1), curS, left, totalLeft, maxLen,dic);
        }else if (s[0] == ')') {
            if (left > 0) {
                dfs(rt,s.substr(1), curS + ')', left - 1, totalLeft, maxLen,dic);
            }
            dfs(rt, s.substr(1), curS, left, totalLeft, maxLen,dic);
        }else {
            dfs(rt, s.substr(1), curS + s[0], left, totalLeft, maxLen,dic);
        }
    }

    vector<string> removeInvalidParentheses(string s) {
        vector<string> rt;
        unordered_set<string> dic;
        int maxLen = 0;
        dfs(rt,s,"",0,0,maxLen,dic);
        
        return rt;
    }
};

Solution #3, in Java

  1. 先预处理,计算出为了得到合法的String,最少需要移除多少个左、右括号 
  2. 依次移除右、左括号,并递减计数。 
  3. 先移除右括号是为了剪枝,如')(()',虽然不影响最后结果 
  4. 加isValid是为了解决'()()()(' -> '()())(' 
  5. ref: http://zxi.mytechroad.com/blog/searching/leetcode-301-remove-invalid-parentheses/

class Solution {
    public List<String> removeInvalidParentheses(String s) {
        int left = 0, right = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') {                
                left++;
            }else  if (s.charAt(i) == ')') {
                if (left == 0) {
                    right++;
                } else {
                    left--;
                }
            }
        }
        
        List<String> rt = new ArrayList<>();
        dfs(new StringBuilder(s),0,left,right,rt);
        return rt;
    }
    
    public void dfs(StringBuilder s, int index, int left, int right, List<String> rt) {
        if (right == 0 && left == 0 && isValid(s)) {
            rt.add(s.toString());
            return;
        }
        
        for (int i = index; i < s.length(); i++) {
            
            if (i != index && s.charAt(i) == s.charAt(i - 1)) continue;
            
            if (right > 0 && s.charAt(i) == ')') {                
                StringBuilder s1 = new StringBuilder(s);
                s1.deleteCharAt(i);
                dfs(s1, i, left, right - 1, rt);
            } else if (right == 0 && left > 0  && s.charAt(i) == '(') {                
                StringBuilder s1 = new StringBuilder(s);
                s1.deleteCharAt(i);
                dfs(s1, i, left - 1, right, rt);
            } 
        }
    }
    
    public boolean isValid(StringBuilder s) {
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '(') {
                count++;
            } 
            if (c == ')') {
                count--;
            }
            if (count < 0) {
                return false;
            }
        }
        
        return count == 0;
    }
}