不再中二

[题目链接](https://www.nowcoder.com/practice/3643445eab9b4b969a900e0edacf0dce)

思路

本题要求对数组中每个整数,删除其十进制表示中所有的数字 2,剩余数字按原顺序拼接成新的整数(无前导零)。若删除后为空,则从数组中移除该元素。

做法

遍历数组中的每个数字,将其转为字符串,逐字符过滤掉 '2',将剩余字符拼接回来:

  • 若拼接结果非空,将其转回整数加入结果数组。转回整数的过程自动去除了前导零。
  • 若拼接结果为空(即该数字仅由 2 组成),则跳过,不加入结果数组。

样例演示

输入 [5, 12, 20, 2, 77]

原数字 删除 2 后的字符串 转为整数
5 "5" 5
12 "1" 1
20 "0" 0
2 "" 删除
77 "77" 77

输出 [5, 1, 0, 77]

复杂度

  • 时间复杂度:,其中 为数组长度, 为数字的最大位数。
  • 空间复杂度:,用于存储字符串转换和结果数组。

代码

class Solution {
public:
    vector<int> newArray(vector<int>& a) {
        vector<int> res;
        for (int x : a) {
            string s = to_string(x);
            string t;
            for (char c : s) {
                if (c != '2') t += c;
            }
            if (!t.empty()) {
                res.push_back(stoi(t));
            }
        }
        return res;
    }
};
import java.util.*;

public class Solution {
    public ArrayList<Integer> newArray(ArrayList<Integer> a) {
        ArrayList<Integer> res = new ArrayList<>();
        for (int x : a) {
            String s = String.valueOf(x);
            StringBuilder t = new StringBuilder();
            for (char c : s.toCharArray()) {
                if (c != '2') t.append(c);
            }
            if (t.length() > 0) {
                res.add(Integer.parseInt(t.toString()));
            }
        }
        return res;
    }
}