Leetcode 420-430题

第四百二十题:

class Solution {
public:
    int strongPasswordChecker(string s) {
        int a = 0, b = 0, c = 0, n = s.size(), k = 0;
        for (auto x: s) {
            if (x >= '0' && x <= '9') a = 1;
            else if (x >= 'a' && x <= 'z') b = 1;
            else if (x >= 'A' && x <= 'Z') c = 1;
        }
        k = a + b + c;
        if (n < 6) return max(6 - n, 3 - k);
        else {
            int p = 0, del = n - 20, res = del;
            int d[3] = {0};
            for (int i = 0; i < s.size(); i ++ ) {
                int j = i;
                while (j < s.size() && s[j] == s[i]) j ++ ;
                int s = j - i;
                i = j - 1;
                p += s / 3;
                if (s >= 3) d[s % 3] ++ ;
            }
            if (n <= 20) return max(p, 3 - k);
            if (d[0] && del > 0) {
                int t = min(d[0], del);
                del -= t;
                p -= t;
            }
            if (d[1] && del > 0) {
                int t = min(d[1] * 2, del);
                del -= t;
                p -= t / 2;
            }
            if (p && del > 0) {
                int t = min(p * 3, del);
                p -= t / 3;
            }
            return res + max(p, 3 - k);
        }
    }
};
public class Solution3 {
    /**
     * 记录连续出现的字符 起始和终止坐标
     */
    class SameChar {
        int st;
        int en;
        char c;

        SameChar(int st, int en, char c) {
            this.st = st;
            this.en = en;
            this.c = c;
        }

    }

    public int strongPasswordChecker(String str) {
        // 统计小写字符
        int lowerCase = 0;
        // 统计大写字符
        int upwerCase = 0;
        // 统计数字
        int number = 0;
        // 统计连续字符出现的位置
        java.util.ArrayList<SameChar> sameChars = new java.util.ArrayList<SameChar>();
        char[] chars = str.toCharArray();
        if (chars.length == 0) {
            return 6;
        }
        // 记露连续出现的字符
        SameChar sameChar = new SameChar(0, 0, '\0');
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] >= 'a' && chars[i] <= 'z') {
                lowerCase++;
            } else if (chars[i] >= 'A' && chars[i] <= 'Z') {
                upwerCase++;
            } else if (chars[i] >= '0' && chars[i] <= '9') {
                number++;
            }
            if (sameChar.c != chars[i]) {
                if (sameChar.en - sameChar.st >= 2) {
                    sameChars.add(new SameChar(sameChar.st, sameChar.en, sameChar.c));
                }
                sameChar.c = chars[i];
                sameChar.st = i;
                sameChar.en = i;
            } else {
                sameChar.en = i;
            }
        }
        if (sameChar.en - sameChar.st >= 2) {
            sameChars.add(new SameChar(sameChar.st, sameChar.en, sameChar.c));
        }
        // 缺失的类型. 只可能是1 or 2
        int needType = count0(lowerCase, upwerCase, number);
        // 连续的字符出现的要消除的个数 连续值-2
        int[] chages = new int[sameChars.size()];
        for (int j = 0; j < sameChars.size(); j++) {
            chages[j] = sameChars.get(j).en - sameChars.get(j).st - 1;
        }
        int res = 0;
        // 如果长度小于6 , 很简单 要补的字符和缺失的类型择大
        if (str.length() < 6) {
            return Integer.max(6 - str.length(), needType);
        }
        // 删除的时候 要有优先概念
        if (str.length() > 20) {
            int index = -1;
            while (needType > 0 && (index = find(chages, 0)) > -1) {
                chages[index] = Integer.max(chages[index] - 3, 0);
                res++;
                needType--;
            }
            int d = str.length() - 20;
            while (d > 0 && (index = find(chages, 1)) > -1) {
                d--;
                res++;
                chages[index]--;
            }
            int n = 0;
            for (int l = 0; l < chages.length; l++) {
                n += chages[l] % 3 == 0 ? chages[l] / 3 : chages[l] / 3 + 1;
            }
            return res + d + needType + n;
        }
        int n = 0;
        for (int l = 0; l < chages.length; l++) {
            n += chages[l] % 3 == 0 ? chages[l] / 3 : chages[l] / 3 + 1;
        }
        return Integer.max(n, needType);
    }

    private int count0(int... array) {
        int n = 0;
        for (int i = 0; i < array.length; i++) {
            if (array[i] == 0) {
                n++;
            }
        }
        return n;
    }

    private int find(int[] array, int n) {
        int n0 = -1;
        int n1 = -1;
        int n2 = -1;
        for (int i = 0; i < array.length; i++) {
            if (array[i] > 0 && array[i] % 3 == 0) {
                n0 = i;
            }
            if (array[i] > 0 && array[i] % 3 == 1) {
                n1 = i;
            }
            if (array[i] > 0 && array[i] % 3 == 2) {
                n2 = i;
            }
        }
        if (n == 0) {
            return n0 > -1 ? n0 : (n2 > -1 ? n2 : n1);
        }
        if (n == 1) {
            return n1 > -1 ? n1 : (n2 > -1 ? n2 : n0);
        }
        return -1;
    }
}
class Solution:
    def strongPasswordChecker(self, s: str) -> int:
        # 计算保持三种字符所需的替换或插入次数
        min_r_or_i = 3 - any(c.islower() for c in s) - any(c.isupper() for c in s) - any(c.isdigit() for c in s)
        # 长度小于 6 时重复字串不是主导因素
        if len(s) < 6:
            return max(6 - len(s), min_r_or_i)
        # 计算处理重复子串的最小次数, 替换优于插入优于删除
        count = 0
        repeat_count = {1: 0, 2: 0, 3: 0}
        for c, last_c in zip(s + '.', '.' + s):
            if c != last_c:
                if count > 2:
                    repeat = count - 2
                    for i in [3, 2, 1]:
                        repeat_count[i] += repeat // i
                        repeat %= i
                count = 0
            count += 1
        # 长度小于等于 20 时都使用替换
        if len(s) <= 20:
            return max(sum(repeat_count.values()), min_r_or_i)
        # 长度大于 20, 考虑加入删除操作
        min_remove = len(s) - 20
        for i in range(1, 4):
            if min_remove > repeat_count[i] * i:
                min_remove -= repeat_count[i] * i
                repeat_count[i] = repeat_count[i] * i
            else:
                repeat_count[i] = (repeat_count[i] * i - min_remove + i - 1) // i + min_remove
                break
        return max(sum(repeat_count.values()), len(s) - 20 + min_r_or_i)
func strongPasswordChecker(s string) int {
	// 统计字符类型
	missTypes := 3
	hasLowercase, hasUppercase, hasDigit := false, false, false
	sLen := len(s)
	for _, v := range s {
		if !hasLowercase && unicode.IsLower(v) {
			missTypes = missTypes - 1
			hasLowercase = true
		} else if !hasUppercase && unicode.IsUpper(v) {
			missTypes = missTypes - 1
			hasUppercase = true
		} else if !hasDigit && unicode.IsDigit(v) {
			missTypes = missTypes - 1
			hasDigit = true
		}
	}
	steps := 0

	// 长度小于6的时候,优先考虑插入,优先考虑补充类型
	if sLen < 6 {
		if 6 - sLen >= missTypes {
			return 6 - sLen
		}
		return missTypes
	} else if sLen > 20 {
		// 先使用缺失类型替换
		result := getSameCharArray(s)
		for{
			index := find(result, 2)
			if missTypes <=0 || index <= -1 {
				break
			}
			if result[index] - 3 > 0 {
				result[index] = result[index] - 3
			}else {
				result[index] = 0
			}
			steps++
			missTypes--
		}

		// 删除连续字符
		minDelete := sLen - 20
		for{
			index := find(result, 0)
			if minDelete <= 0 || index <= -1{
				steps += minDelete
				break
			}
			minDelete--
			steps++
			if result[index] - 3 > 0 {
				result[index] = result[index] - 1
			}else {
				result[index] = 0
			}
		}
		for _, v := range result {
			steps += v / 3
		}
		return steps + missTypes
	}
    // 6 - 20 直接考虑替换
	result := getSameCharArray(s)
	for _, v := range result {
		steps += v / 3
	}
	if steps < missTypes {
		return missTypes
	}
	return steps
}

func getSameCharArray(s string) (result []int){
	length := 0
	lastIndex := ""
	for index, v := range s{
		if string(v) != lastIndex{
			if length >= 3 {
				result = append(result, length)
			}
			lastIndex = string(v)
			length = 1
		} else if index == len(s)-1{
			length = length+1
			if length >= 3 {
				result = append(result, length)
			}
		}else{
			length = length + 1
		}
	}
	return result
}

func find(array []int, left int) int {
	n0, n1, n2 := -1, -1, -1
	for i := 0; i< len(array); i++ {
		if array[i] > 0 && array[i] % 3 == 0 {
			n0 = i
		}

		if array[i] > 0 && array[i] % 3 == 1 {
			n1 = i
		}

		if array[i] > 0 && array[i] % 3 == 2 {
			n2 = i
		}
	}

    // 0 > 1 > 2
	if left == 0 {
		if n0 > -1 {
			return n0
		} else if n1 > -1 {
			return n1
		} else {
			return n2
		}
	} else if left == 2 { // 2 > 1 > 0
		if n2 > -1 {
			return n2
		} else if n1 > -1 {
			return n1
		} else {
			return n0
		}
	}
	return -1
}

第四百二十一题:

class Solution {
public:
    vector<vector<int>> s;

    void insert(int x) {
        int p = 0;
        for (int i = 30; i >= 0; i -- ) {
            int u = x >> i & 1;
            if (!s[p][u]) s[p][u] = s.size(), s.push_back({0, 0});
            p = s[p][u];
        }
    }

    int query(int x) {
        int p = 0, res = 0;
        for (int i = 30; i >= 0; i -- ) {
            int u = x >> i & 1;
            if (s[p][!u]) p = s[p][!u], res = res * 2 + !u;
            else p = s[p][u], res = res * 2 + u;
        }
        return res ^ x;
    }

    int findMaximumXOR(vector<int>& nums) {
        s.push_back({0, 0});
        int res = 0;
        for (auto x: nums) {
            res = max(res, query(x));
            insert(x);
        }
        return res;
    }
};
class Solution {
  public int findMaximumXOR(int[] nums) {
    int maxNum = nums[0];
    for(int num : nums) maxNum = Math.max(maxNum, num);
    // length of max number in a binary representation
    int L = (Integer.toBinaryString(maxNum)).length();

    int maxXor = 0, currXor;
    Set<Integer> prefixes = new HashSet<>();
    for(int i = L - 1; i > -1; --i) {
      // go to the next bit by the left shift
      maxXor <<= 1;
      // set 1 in the smallest bit
      currXor = maxXor | 1;
      prefixes.clear();
      // compute all possible prefixes 
      // of length (L - i) in binary representation
      for(int num: nums) prefixes.add(num >> i);
      // Update maxXor, if two of these prefixes could result in currXor.
      // Check if p1^p2 == currXor, i.e. p1 == currXor^p2.
      for(int p: prefixes) {
        if (prefixes.contains(currXor^p)) {
          maxXor = currXor;
          break;
        }
      }
    }
    return maxXor;
  }
}
class Solution:
    def findMaximumXOR(self, nums: List[int]) -> int:
        # length of max number in a binary representation
        L = len(bin(max(nums))) - 2
        max_xor = 0
        for i in range(L)[::-1]:
            # go to the next bit by the left shift
            max_xor <<= 1
            # set 1 in the smallest bit
            curr_xor = max_xor | 1
            # compute all existing prefixes 
            # of length (L - i) in binary representation
            prefixes = {num >> i for num in nums}
            # Update max_xor, if two of these prefixes could result in curr_xor.
            # Check if p1^p2 == curr_xor, i.e. p1 == curr_xor^p2
            max_xor |= any(curr_xor^p in prefixes for p in prefixes)
                    
        return max_xor
func findMaximumXOR(nums []int) int {
    sort.Ints(nums)
	maxBinStr := strconv.FormatInt(int64(nums[len(nums)-1]), 2)

	var maxNums []int

	format := "%" + fmt.Sprintf("0%ds", len(maxBinStr))
	for i := len(nums) - 1; i >= 0; i-- {
		in := fmt.Sprintf(format, strconv.FormatInt(int64(nums[i]), 2))
		if in[0] == '1' {
			maxNums = append(maxNums, nums[i])
		} else {
			break
		}
	}

	var result int

	for _, max := range maxNums {
		for _, num := range nums {
			if max == num {
				continue
			}

			result = int(math.Max(float64(result), float64(max^num)))
		}
	}

	return result
}

第四百二十三题:

class Solution {
public:
    string originalDigits(string s) {
        string name[] = {
            "zero", "one", "two", "three", "four", "five",
            "six", "seven", "eight", "nine"
        };
        int ord[] = {0, 8, 3, 2, 6, 4, 5, 1, 7, 9};
        unordered_map<char, int> cnt;
        for (auto c: s) cnt[c] ++ ;
        string res;
        for (int x: ord) {
            while (true) {
                bool flag = true;
                for (auto c: name[x])
                    if (!cnt[c]) {
                        flag = false;
                        break;
                    }
                    if (flag) {
                        res += to_string(x);
                        for (auto c: name[x]) cnt[c] -- ;
                    }
                    else break;
            }
        }
        sort(res.begin(), res.end());
        return res;
    }
};
class Solution {
  public String originalDigits(String s) {
    // building hashmap letter -> its frequency
    char[] count = new char[26 + (int)'a'];
    for(char letter: s.toCharArray()) {
      count[letter]++;
    }

    // building hashmap digit -> its frequency
    int[] out = new int[10];
    // letter "z" is present only in "zero"
    out[0] = count['z'];
    // letter "w" is present only in "two"
    out[2] = count['w'];
    // letter "u" is present only in "four"
    out[4] = count['u'];
    // letter "x" is present only in "six"
    out[6] = count['x'];
    // letter "g" is present only in "eight"
    out[8] = count['g'];
    // letter "h" is present only in "three" and "eight"
    out[3] = count['h'] - out[8];
    // letter "f" is present only in "five" and "four"
    out[5] = count['f'] - out[4];
    // letter "s" is present only in "seven" and "six"
    out[7] = count['s'] - out[6];
    // letter "i" is present in "nine", "five", "six", and "eight"
    out[9] = count['i'] - out[5] - out[6] - out[8];
    // letter "n" is present in "one", "nine", and "seven"
    out[1] = count['n'] - out[7] - 2 * out[9];

    // building output string
    StringBuilder output = new StringBuilder();
    for(int i = 0; i < 10; i++)
      for (int j = 0; j < out[i]; j++)
        output.append(i);
    return output.toString();
  }
}
class Solution:
    def originalDigits(self, s: 'str') -> 'str':
        # building hashmap letter -> its frequency
        count = collections.Counter(s)
        
        # building hashmap digit -> its frequency 
        out = {}
        # letter "z" is present only in "zero"
        out["0"] = count["z"]
        # letter "w" is present only in "two"
        out["2"] = count["w"]
        # letter "u" is present only in "four"
        out["4"] = count["u"]
        # letter "x" is present only in "six"
        out["6"] = count["x"]
        # letter "g" is present only in "eight"
        out["8"] = count["g"]
        # letter "h" is present only in "three" and "eight"
        out["3"] = count["h"] - out["8"]
        # letter "f" is present only in "five" and "four"
        out["5"] = count["f"] - out["4"]
        # letter "s" is present only in "seven" and "six"
        out["7"] = count["s"] - out["6"]
        # letter "i" is present in "nine", "five", "six", and "eight"
        out["9"] = count["i"] - out["5"] - out["6"] - out["8"]
        # letter "n" is present in "one", "nine", and "seven"
        out["1"] = count["n"] - out["7"] - 2 * out["9"]

        # building output string
        output = [key * out[key] for key in sorted(out.keys())]
        return "".join(output)
func originalDigits(s string) string {
	M := map[byte]int{}
	for i := 0; i < len(s); i++ {
		M[s[i]]++
	}

	order := []byte{'z', 'x', 'w', 'u', 'g', 'o', 't', 'f', 's', 'i'}
	number := []byte{'0', '6', '2', '4', '8', '1', '3', '5', '7', '9'}
	erase := [][]byte{{'z', 'e', 'r', 'o'},
		{'s', 'i', 'x'},
		{'t', 'w', 'o'},
		{'f', 'o', 'u', 'r'},
		{'e', 'i', 'g', 'h', 't'},
		{'o', 'n', 'e'},
		{'t', 'h', 'r', 'e', 'e'},
		{'f', 'i', 'v', 'e'},
		{'s', 'e', 'v', 'e', 'n'},
		{'n', 'i', 'n', 'e'},
	}
	var buf [][]byte
	for i := 0; i < len(order); i++ {
		c := M[order[i]]
		var b []byte
		for j := 0; j < c; j++ {
			b = append(b, number[i])
		}
		for j := 0; j < len(erase[i]); j++ {
			M[erase[i][j]] -= c
		}
		buf = append(buf, b)
	}

	return string(buf[0]) + string(buf[5]) + string(buf[2]) + string(buf[6]) + string(buf[3]) + string(buf[7]) + string(buf[1]) + string(buf[8]) + string(buf[4]) + string(buf[9])
}

第四百二十四题:

class Solution {
public:
    int characterReplacement(string s, int k) {
        int res = 0;
        for (char c = 'A'; c <= 'Z'; c ++ ) {
            for (int i = 0, j = 0, cnt = 0; i < s.size(); i ++ ) {
                if (s[i] == c) cnt ++ ;
                while (i - j + 1 - cnt > k) {
                    if (s[j] == c) cnt -- ;
                    j ++ ;
                }
                res = max(res, i - j + 1);
            }
        }
        return res;
    }
};
public class Solution {

    public int characterReplacement(String s, int k) {
        int len = s.length();
        if (len < 2) {
            return len;
        }

        char[] charArray = s.toCharArray();
        int left = 0;
        int right = 0;

        int res = 0;
        int maxCount = 0;
        int[] freq = new int[26];
        // [left, right) 内最多替换 k 个字符可以得到只有一种字符的子串
        while (right < len){
            freq[charArray[right] - 'A']++;
            // 在这里维护 maxCount,因为每一次右边界读入一个字符,字符频数增加,才会使得 maxCount 增加
            maxCount = Math.max(maxCount, freq[charArray[right] - 'A']);
            right++;

            if (right - left > maxCount + k){
              	// 说明此时 k 不够用
                // 把其它不是最多出现的字符替换以后,都不能填满这个滑动的窗口,这个时候须要考虑左边界向右移动
                // 移出滑动窗口的时候,频数数组须要相应地做减法
                freq[charArray[left] - 'A']--;
                left++;
            }
            res = Math.max(res, right - left);
        }
        return res;
    }
}
class Solution:
    def characterReplacement(self, s: str, k: int) -> int:
        n_char = [0] * 26
        max_n = 0
        start = 0
        ret = 0
        for end in range(len(s)):
            ind = ord(s[end]) - ord('A')
            n_char[ind] += 1
            max_n = max_n if max_n > n_char[ind] else n_char[ind]
            if max_n + k < end - start + 1:
                n_char[ord(s[start]) - ord('A')] -= 1
                start += 1
            else:
               ret = max(ret, end - start + 1)
        return ret         
func characterReplacement(s string, k int) int {
	if s == "" {
		return 0
	}
	// 左指针 / 右指针
	left, right := 0, 0
	// 最长长度 / 当前窗口所有字符计数
	maxLen, m := 0, make(map[uint8]int)
	for right = 0; right < len(s); right++ {
		m[s[right]]++
		maxLen = max(maxLen, m[s[right]]) // 当前窗口最多的字符计数
		// 如果窗口无法满足凑成全部一样的字符,滑动左指针
		if right-left+1 > maxLen+k {
			m[s[left]]--
			left++
		}
	}
	return len(s) - left
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

第四百二十七题:

/*
// Definition for a QuadTree node.
class Node {
public:
    bool val;
    bool isLeaf;
    Node* topLeft;
    Node* topRight;
    Node* bottomLeft;
    Node* bottomRight;

    Node() {
        val = false;
        isLeaf = false;
        topLeft = NULL;
        topRight = NULL;
        bottomLeft = NULL;
        bottomRight = NULL;
    }

    Node(bool _val, bool _isLeaf) {
        val = _val;
        isLeaf = _isLeaf;
        topLeft = NULL;
        topRight = NULL;
        bottomLeft = NULL;
        bottomRight = NULL;
    }

    Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) {
        val = _val;
        isLeaf = _isLeaf;
        topLeft = _topLeft;
        topRight = _topRight;
        bottomLeft = _bottomLeft;
        bottomRight = _bottomRight;
    }
};
*/

class Solution {
public:
    vector<vector<int>> s;


    Node* construct(vector<vector<int>>& w) {
        int n = w.size();
        s = vector<vector<int>>(n + 1, vector<int>(n + 1));
        for (int i = 1; i <= n; i ++ )
            for (int j = 1; j <= n; j ++ )
                s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + w[i - 1][j - 1];
        return dfs(1, 1, n, n);
    }

    Node* dfs(int x1, int y1, int x2, int y2) {
        int n = x2 - x1 + 1;
        int sum = s[x2][y2] - s[x2][y1 - 1] - s[x1 - 1][y2] + s[x1 - 1][y1 - 1];
        if (sum == 0 || sum == n * n) return new Node(!!sum, true);
        auto node = new Node(0, false);
        int m = n / 2;
        node->topLeft = dfs(x1, y1, x1 + m - 1, y1 + m - 1);
        node->topRight = dfs(x1, y1 + m, x1 + m - 1, y2);
        node->bottomLeft = dfs(x1 + m, y1, x2, y1 + m - 1);
        node->bottomRight = dfs(x1 + m, y1 + m, x2, y2);
        return node;
    }
};
class Solution {
    public Node construct(int[][] grid) {
        //left, right, up, down
        return helper(grid, 0, grid.length - 1, 0, grid[0].length - 1);
    }

    private Node helper(int[][] grid, int left, int right, int up, int down){
        Node root  = new Node();
        if(isSame(grid, left, right, up, down)){
            root.val = grid[up][left] == 1 ? true : false;
            root.isLeaf = true;
            return root;
        }

        root.isLeaf = false;
        root.topLeft     = helper(grid, left,(right + left) / 2,  up, (up + down) / 2);
        root.topRight    = helper(grid, (right + left) / 2 + 1 , right, up, (up + down) / 2);
        root.bottomLeft  = helper(grid, left, (right + left) / 2 , (up + down) / 2 + 1, down);
        root.bottomRight = helper(grid, (right + left) / 2 + 1, right, (up + down) / 2 + 1, down);
        
        return root;
    }

    private boolean isSame(int[][] grid, int left, int right, int up, int down){
        int pre = -1;
        for(int i = up; i <= down; i++)
            for(int j = left; j <= right; j++)
                if(pre != -1){
                    if(pre != grid[i][j])
                        return false;
                }else
                    pre = grid[i][j];


        return true;
    }
}
"""
# Definition for a QuadTree node.
class Node:
    def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):
        self.val = val
        self.isLeaf = isLeaf
        self.topLeft = topLeft
        self.topRight = topRight
        self.bottomLeft = bottomLeft
        self.bottomRight = bottomRight
"""

class Solution:
    def construct(self, grid: List[List[int]]) -> 'Node':
        return Node(bool(s), True) if not (s := sum(map(sum, grid))) or not (m := len(grid) >> 1) or s == 4 * m * m else Node(True, False, self.construct([g[:m] for g in grid[:m]]), self.construct([g[m:] for g in grid[:m]]), self.construct([g[:m] for g in grid[m:]]), self.construct([g[m:] for g in grid[m:]]))
func construct(grid [][]int) *Node {
    
    var helper func(x1, y1, x2, y2 int) *Node
    helper = func(x1, y1, x2, y2 int) *Node {
        if x1 == x2-1 {
            val := false
            if grid[x1][y1] == 1 {
                val = true
            }
            return &Node{
                Val : val,
                IsLeaf : true,
            }
        }
        midX, midY := (x1+x2)>>1, (y1+y2)>>1
        tl := helper(x1, y1, midX, midY)
        tr := helper(x1, midY, midX, y2)
        bl := helper(midX, y1, x2, midY)
        br := helper(midX, midY, x2, y2)
        // 都是叶节点且值一样就丢弃(只保留叶节点的值)
        if tl.IsLeaf && tr.IsLeaf && bl.IsLeaf && br.IsLeaf &&
         (tl.Val && tr.Val && bl.Val && br.Val || (!tl.Val && !tr.Val && !bl.Val && !br.Val)) {
            return &Node{
                Val : tl.Val,
                IsLeaf : true,
            }
        }
        return &Node{
            IsLeaf : false,
            TopLeft : tl,
            TopRight : tr,
            BottomLeft : bl,
            BottomRight : br,
        }
    }

    return helper(0, 0, len(grid), len(grid[0]))
}

第四百二十九题:

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

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
public:
    vector<vector<int>> levelOrder(Node* root) {
        vector<vector<int>> res;
        if (!root) return res;
        queue<Node*> q;
        q.push(root);
        while (q.size()) {
            int len = q.size();
            vector<int> line;
            while (len -- ) {
                auto t = q.front();
                q.pop();
                line.push_back(t->val);
                for (auto c: t->children) q.push(c);
            }
            res.push_back(line);
        }
        return res;
    }
};
// This code is a modified version of the code posted by
// #zzzliu on the discussion forums.
class Solution {

    public List<List<Integer>> levelOrder(Node root) {      
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) return result;
        Queue<Node> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            List<Integer> level = new ArrayList<>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                Node node = queue.poll();
                level.add(node.val);
                queue.addAll(node.children);
            }
            result.add(level);
        }
        return result;
    }
}
def levelOrder(self, root: 'Node') -> List[List[int]]:
    if root is None:
        return []
    result = []
    queue = collections.deque([root])
    while queue:
        level = []
        for _ in range(len(queue)):
            node = queue.popleft()
            level.append(node.val)
            queue.extend(node.children)
        result.append(level)
    return result
/**
 * Definition for a Node.
 * type Node struct {
 *     Val int
 *     Children []*Node
 * }
 */

var res [][]int

func levelOrder(root *Node) [][]int {
	res = [][]int{}
	if root == nil {
		return res
	}

	queue := []*Node{root}
	var level int
	for 0 < len(queue) {
		counter := len(queue)
        res = append(res,[]int{})
		for i := 0; i < counter; i++ {
			if queue[i] != nil {
				res[level] = append(res[level], queue[i].Val)
				for _, n := range queue[i].Children {
					queue = append(queue, n)
				}
			}
		}
		queue = queue[counter:]
		level++
	}
	return res
}

第四百三十题:

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* prev;
    Node* next;
    Node* child;
};
*/

class Solution {
public:
    Node* flatten(Node* head) {
        auto res = dfs(head);
        return res[0];
    }

    vector<Node*> dfs(Node* head) {
        if (!head) return {NULL, NULL};
        auto cur = head, tail = head;
        while (cur) {
            tail = cur;
            if (cur->child) {
                auto t = dfs(cur->child);
                cur->child = NULL;
                t[1]->next = cur->next;
                if (cur->next) cur->next->prev = t[1];
                cur->next = t[0];
                t[0]->prev = cur;
                cur = t[1]->next;
                tail = t[1];
            } else {
                cur = cur->next;
            }
        }
        return {head, tail};
    }
};
/*
// Definition for a Node.
class Node {
    public int val;
    public Node prev;
    public Node next;
    public Node child;

    public Node() {}

    public Node(int _val,Node _prev,Node _next,Node _child) {
        val = _val;
        prev = _prev;
        next = _next;
        child = _child;
    }
};
*/
class Solution {
  public Node flatten(Node head) {
    if (head == null) return head;
    // pseudo head to ensure the `prev` pointer is never none
    Node pseudoHead = new Node(0, null, head, null);

    flattenDFS(pseudoHead, head);

    // detach the pseudo head from the real head
    pseudoHead.next.prev = null;
    return pseudoHead.next;
  }
  /* return the tail of the flatten list */
  public Node flattenDFS(Node prev, Node curr) {
    if (curr == null) return prev;
    curr.prev = prev;
    prev.next = curr;

    // the curr.next would be tempered in the recursive function
    Node tempNext = curr.next;

    Node tail = flattenDFS(curr, curr.child);
    curr.child = null;

    return flattenDFS(tail, tempNext);
  }
}
"""
# Definition for a Node.
class Node(object):
    def __init__(self, val, prev, next, child):
        self.val = val
        self.prev = prev
        self.next = next
        self.child = child
"""
class Solution(object):

    def flatten(self, head):
        if not head:
            return head

        # pseudo head to ensure the `prev` pointer is never none
        pseudoHead = Node(None, None, head, None)
        self.flatten_dfs(pseudoHead, head)

        # detach the pseudo head from the real head
        pseudoHead.next.prev = None
        return pseudoHead.next


    def flatten_dfs(self, prev, curr):
        """ return the tail of the flatten list """
        if not curr:
            return prev

        curr.prev = prev
        prev.next = curr

        # the curr.next would be tempered in the recursive function
        tempNext = curr.next
        tail = self.flatten_dfs(curr, curr.child)
        curr.child = None
        return self.flatten_dfs(tail, tempNext)
/**
 * Definition for a Node.
 * type Node struct {
 *     Val int
 *     Prev *Node
 *     Next *Node
 *     Child *Node
 * }
 */

func flatten(root *Node) *Node {
    if root == nil {
        return root
    }

    var cur, after *Node = root, nil
    for cur != nil {
        after = cur.Next 
        if cur.Child != nil {
            child := cur.Child
            cur.Next = child
            child.Prev = cur
            cur.Child = nil
            for child.Next != nil {
                child = child.Next
            }
            child.Next = after
            if after != nil { // 需要注意这种异常情况,避免panic
                after.Prev = child
            }
            
        }
        cur = cur.Next
    }
    return root
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不能say的秘密

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值