【Contest】No.172

C01_6和9组成的最大数字

Given a positive integer num consisting only of digits 6 and 9.
Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).

Example 1:
Input: num = 9669
Output: 9969
Explanation:
Changing the first digit results in 6669.
Changing the second digit results in 9969.
Changing the third digit results in 9699.
Changing the fourth digit results in 9666.
The maximum number is 9969.

Example 2:
Input: num = 9996
Output: 9999
Explanation: Changing the last digit 6 to 9 results in the maximum number.
Example 3:

Input: num = 9999
Output: 9999
Explanation: It is better not to apply any change.

Constraints:
1 <= num <= 10^4
num's digits are 6 or 9.

二、题解

(1) 暴力枚举

/**
 * @thought:暴力枚举
 * @date: 1/19/2020 3:48 PM
 * @Execution info:
 *   1 ms 击败 100% 的j
 *   33.2 MB 击败 % 的j
 * @Asymptotic Time Complexity:O()
 */
public int maximum69Number (int num) {
  String numStr = String.valueOf(num);
  if(numStr.indexOf("6") < 0)
    return num;

  int ans = 0, count = 1;
  char[] chars = numStr.toCharArray();
  for (int i = 0; i < chars.length; i++) {
    if(chars[i] == '6' && count > 0) {
      chars[i] = '9';
      int t = Integer.parseInt(String.valueOf(chars));
      if(t > ans) {
        ans = t;
        count--;
      } else chars[i]='6';
    }
  }
  return ans;
}

复杂度分析

  • 时间复杂度: O ( n ) O(n)
  • 空间复杂度: O ( n ) O(n)

(2) 转换思维

/**
 * @thought:转为字符串简单处理
 * @date: 1/19/2020 3:48 PM
 * @Execution info:
 *   1 ms 击败 % 的j
 *   33.4 MB 击败 % 的j
 * @Asymptotic Time Complexity:O()
 */
public int maximum69Number2 (int num) {
  StringBuilder sb = new StringBuilder(String.valueOf(num));
  for (int i = 0; i < sb.length(); i++) {
    if(sb.charAt(i) == '6') {
      sb.setCharAt(i, '9');
      break;
    }
  }
  int ans = Integer.parseInt(sb.toString());
  return ans;
}

C02_竖直打印单词

Given a string s. Return all the words vertically in the same order in which they appear in s.
Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed).
Each word would be put on only one column and that in one column there will be only one word.

Example 1:
Input: s = "HOW ARE YOU"
Output: ["HAY","ORO","WEU"]
Explanation: Each word is printed vertically.
 "HAY"
 "ORO"
 "WEU"

Example 2:
Input: s = "TO BE OR NOT TO BE"
Output: ["TBONTB","OEROOE","   T"]
Explanation: Trailing spaces is not allowed.
"TBONTB"
"OEROOE"
"   T"

Example 3:
Input: s = "CONTEST IS COMING"
Output: ["CIC","OSO","N M","T I","E N","S G","T"]

Constraints:
1 <= s.length <= 200
s contains only upper case English letters.
It's guaranteed that there is only one space between 2 words.

二、题解

(1) 顺着思维走

  • 如何删除尾随空格?
  • 如何控制字符串 s b sb 的添加顺序。
/**
 * 删除字符串s的尾随空格
 * @param s
 * @return
 */
private String removeSuffixSpaces(String s) {
  StringBuilder sb = new StringBuilder();
  boolean flag = false;
  char c;
  for (int i = s.length()-1; i >= 0; i--) {
    c = s.charAt(i);
    if(c != ' ')  flag = true;
    if(flag)  sb.append(c);
  }
  return sb.reverse().toString();
}
/**
 * @thought:
 * @date: 1/19/2020 3:45 PM
 * @Execution info:
 *   1 ms 击败 100% 的j
 *   35.2 MB 击败 100% 的j
 * @Asymptotic Time Complexity:O()
 */
public List<String> printVertically(String s) {
  List<String> ansList = new LinkedList<>();
  String[] strs = s.split(" ");
  int maxLen = 0;
  for(String str : strs)
    if(str.length() > maxLen)
      maxLen = str.length();

  for (int i = 0; i < maxLen; i++) {
    StringBuilder sb = new StringBuilder();
    for (int j = 0; j < strs.length; j++) {
      int curLen = strs[j].length();
      if(i < curLen)
        sb.append(strs[j].charAt(i));
      else
        sb.append(' ');
    }
    String str = removeSuffixSpaces(sb.toString());
    ansList.add(str);
  }
  return ansList;
}

复杂度分析

  • 时间复杂度: O ( m a x L e n N ) O(maxLen * N) m a x L e n maxLen 为分割后得到的字符串数组中最长的字符串长度, N N 为字符串数组的大小。
  • 空间复杂度: O ( n ) O(n)

C03_删除给定值的叶子节点

Given a binary tree root and an integer target, delete all the leaf nodes with value target.
Note that once you delete a leaf node with value target,
if it's parent node becomes a leaf node and has the value target,
it should also be deleted (you need to continue doing that until you can't).

Input: root = [1,2,3,2,null,2,4], target = 2
Output: [1,null,3,null,4]
Explanation: Leaf nodes in green with value (target = 2) are removed (Picture in left).
After removing, new nodes become leaf nodes with value (target = 2) (Picture in center).

二、题解

(1) BFS

将每一层的结点入队、入栈,然后从最后一层往最高层遍历,这要用到 s t a c k stack F I L O FILO 的特性。

/**
 * @thought:BFS:
 * @date: 1/19/2020 4:02 PM
 * @Execution info:
 *   5 ms 击败 % 的j
 *   39.5 MB 击败 % 的j
 * @Asymptotic Time Complexity:O()
 */
public TreeNode removeLeafNodes(TreeNode root, int target) {
  if(root == null)  return null;
  LinkedList<TreeNode> nodeQueue = new LinkedList<>();
  Stack<TreeNode> nodeStack = new Stack<>();
  ArrayList<Integer> widthList = new ArrayList<>();
  widthList.add(1);
  nodeQueue.add(root);
  nodeStack.push(root);
  while( !nodeQueue.isEmpty() ) {
    int cur_level_width = 0;
    for (int i = 0; i < widthList.get(widthList.size() - 1); i++) {
      // queue存储的是最定端的node
      TreeNode node = nodeQueue.pollFirst();
      if(node.left != null) {
        cur_level_width++;
        nodeQueue.addLast(node.left);
        nodeStack.push(node.left);
      }
      if(node.right != null) {
        cur_level_width++;
        nodeQueue.addLast(node.right);
        nodeStack.push(node.right);
      }
    }
    widthList.add(cur_level_width);
  }
  // 从最下面的一层开始遍历,查看是否有符合条件的node
  int levels = widthList.size()-1;  // 是3
  while(!nodeStack.isEmpty()) {
    // 第一遍循环啥也没做,因为
    for (int i = 0; i < widthList.get(levels--); i++) {
      TreeNode node = nodeStack.pop();
      // 如果是node的孩子是叶子结点,并且val==target
      if(node.left!=null && node.left.right == null && node.left.left == null && node.left.val==target)
        node.left = null;
      if(node.right!=null && node.right.right == null && node.right.left == null && node.right.val==target)
        node.right = null;
    }
  }
  // 如果root是叶子结点
  if(root.left == null && root.right==null && root.val == target)
    root=null;
  return root;
}

(2) DFS

/**
 * @thought:DFS
 * @date: 1/19/2020 5:02 PM
 * @Execution info:
 *    ms 击败 % 的j
 *    MB 击败 % 的j
 * @Asymptotic Time Complexity:O()
 */
public TreeNode removeLeafNodes2(TreeNode root, int target) {

  if(root == null)  return null;
  root.left = removeLeafNodes(root.left, target);
  root.right = removeLeafNodes(root.right, target);
  // 如果node结点是叶子结点 && val==target
  if(root.left == null && root.right == null && root.val == target)
    return null;
  return root;
}
发布了300 篇原创文章 · 获赞 48 · 访问量 8047

猜你喜欢

转载自blog.csdn.net/qq_43539599/article/details/104046570