likes
comments
collection
share

Java&C++题解与拓展——leetcode670.最大交换【么的新知识】

作者站长头像
站长
· 阅读数 41
每日一题做题记录,参考官方和三叶的题解

题目要求

Java&C++题解与拓展——leetcode670.最大交换【么的新知识】

思路:模拟

Java

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;
    }
}
  • 时间复杂度:O(log⁡num)O(\log num)O(lognum)
  • 空间复杂度:O(log⁡num)O(\log num)O(lognum)

C++

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;
    }
};
  • 时间复杂度:O(log⁡num)O(\log num)O(lognum)
  • 空间复杂度:O(log⁡num)O(\log num)O(lognum)

Rust

  • 这个部分代码似乎有一点小问题【不用似乎就是有】……有就先有着吧……搞了半个小时也没解决【摆烂】
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
    }
}
  • 时间复杂度:O(log⁡num)O(\log num)O(lognum)
  • 空间复杂度:O(log⁡num)O(\log num)O(lognum)

总结

跟着直觉做就结束~

欢迎指正与讨论!
转载自:https://juejin.cn/post/7142875009252818975
评论
请登录