classSolution { constint INF = 0x3f3f3f3f; public: intgetMinDistance(vector<int>& nums, int target, int start){ int ans = -INF; for (int i = 0; i < nums.size(); ++i) { if (nums[i] == target) { if (abs(i - start) < abs(ans - start)) { ans = i; } } } returnabs(ans - start); } };
1849. Splitting a String Into Descending Consecutive Values
Backtracking, 搜索可能的分割点。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution: defsplitString(self, s: str) -> bool: n = len(s) if n <= 1: returnFalse @cache defdfs(i: int, last: int) -> bool: if i >= n: returnFalse if i != 0: final = int(s[i:]) if final < last and last - final == 1: returnTrue for j inrange(i + 1, n): new = int(s[i:j]) if new < last and (i == 0or last - new == 1): if dfs(j, new): returnTrue returnFalse return dfs(0, float('inf'))
classSolution { public: intgetMinSwaps(string num, int k){ auto s = num; while(std::next_permutation(s.begin(), s.end()) && k - 1 > 0) { // std::cout << s << '\n'; --k; } constint n = num.size(); int ans = 0; for (int j = 0; j < n; ++j) { if (num[j] == s[j]) continue; // find next digit and swap it here int i = j + 1; for (; i < n and num[i] != s[j]; ++i); // cout << i << " " << j << endl; ans += i - j; for (int x = i; x > j; --x) { swap(num[x], num[x - 1]); } } return ans; } };