目录题目要求思路:模拟Javac++Rust题目要求 思路:模拟 Java class Solution { public int maximumSwap(int num)
class Solution {
public int maximumSwap(int num) {
List<Integer> list = new ArrayList<>();
while (num != 0) {
list.add(num % 10);
num /= 10;
}
int n = list.size(), res = 0;
int[] idx = new int[n];
for (int i = 0, j = 0; i < n; i++) {
if (list.get(i) > list.get(j)) // 严格大于
j = i;
idx[i] = j;
}
for (int i = n - 1; i >= 0; i--) { // 高位开始
if (list.get(idx[i]) != list.get(i)) {
int tmp = list.get(idx[i]);
list.set(idx[i], list.get(i));
list.set(i, tmp);
break;
}
}
for (int i = n - 1; i >= 0; i--)
res = res * 10 + list.get(i);
return res;
}
}
class Solution {
public:
int maximumSwap(int num) {
vector<int> list;
while (num != 0) {
list.emplace_back(num % 10);
num /= 10;
}
int n = list.size(), res = 0;
int idx[n];
for (int i = 0, j = 0; i < n; i++) {
if (list[i] > list[j]) // 严格大于
j = i;
idx[i] = j;
}
for (int i = n - 1; i >= 0; i--) { // 高位开始
if (list[idx[i]] != list[i]) {
int tmp = list[idx[i]];
list[idx[i]] =list[i];
list[i] = tmp;
break;
}
}
for (int i = n - 1; i>= 0; i--)
res = res * 10 + list[i];
return res;
}
};
impl Solution {
pub fn maximum_swap(num: i32) -> i32 {
let mut list = vec![];
let mut res = num;
while (res != 0) {
list.push(res % 10);
res /= 10;
}
let n = list.len();
let mut idx = vec![0; n];
let mut j = 0;
for i in 0..n {
if list[i] > list[j] {
j = i;
}
idx[i] = j;
}
for k in n-1..0 {
if list[idx[k]] != list[k] {
list.swap(idx[k], k);
break;
}
}
for l in n-1..0 {
res = res * 10 + list[l];
}
res
}
}
以上就是Java C++算法题解拓展LeetCode670最大交换示例的详细内容,更多关于Java C++算法最大交换的资料请关注编程网其它相关文章!
--结束END--
本文标题: Java C++ 算法题解拓展leetcode670最大交换示例
本文链接: https://lsjlt.com/news/167465.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0