longlongsmallestNumber(longlong num){ longlong res = 0; if (num > 0) { auto a = getNum(num); sort(a.begin(), a.end()); int i = 0, n =a.size(), k = 0; bool flag = true; vector<int> vec; for (int i = 0; i < n; i ++) { if (a[i] != 0 && flag){ k = i, flag = !flag; continue; } vec.push_back(a[i]); } res += a[k] * pow(10, n - 1); int cnt = vec.size() - 1; for (int i = 0; i < vec.size(); i ++) { res += vec[i] * pow(10, cnt); cnt --; } } else { longlong n1 = -num; auto a = getNum(n1); sort(a.begin(), a.end(), greater<int>()); int cnt = a.size() - 1; for (int i = 0; i < a.size(); i ++) { res += a[i] * pow(10, cnt); cnt --; } res = -res; } return res; } };
classSolution { public: /* 考虑左半部分的最少时间。 当s[i] == '0' pre[i] = pre[i - 1] 当s[i] == '1' pre[i] = min(pre[i - 1] + 2, i + 1) 考虑右半部分的最少时间 s[i] == '0' , suf[i] = suf[i + 1] s[i] == '1' , suf[i] = min(suf[i + 1] + 2, n - i) */ intminimumTime(string s){ int n = s.length(); vector<int> suf(n + 1, 0); // 移除后i个载有违禁货物车所需的最少单位时间数 for (int i = n - 1; i >= 0; i --) { suf[i] = s[i] == '0' ? suf[i + 1] : min(suf[i + 1] + 2, n - i); }
// 枚举分割点 int pre = 0, ans = suf[0]; // pre使用滚动数组优化 for (int i = 0; i < n; i ++) { if (s[i] == '1') pre = min(pre + 2, i + 1); ans = min(ans, pre + suf[i]); } return ans; } };