Skip to content

Latest commit

 

History

History
140 lines (113 loc) · 2.88 KB

File metadata and controls

140 lines (113 loc) · 2.88 KB

English Version

题目描述

给定一个非负整数,你至多可以交换一次数字中的任意两位。返回你能得到的最大值。

示例 1 :

输入: 2736
输出: 7236
解释: 交换数字2和数字7。

示例 2 :

输入: 9973
输出: 9973
解释: 不需要交换。

注意:

  1. 给定数字的范围是 [0, 108]

解法

Python3

class Solution:
    def maximumSwap(self, num: int) -> int:
        chars = list(str(num))
        n = len(chars)
        for i in range(n - 1):
            mx = i + 1
            for j in range(i + 1, n):
                if ord(chars[j]) >= ord(chars[mx]):
                    mx = j
            if ord(chars[i]) < ord(chars[mx]):
                chars[i], chars[mx] = chars[mx], chars[i]
                break
        return int(''.join(chars))

Java

class Solution {
    public int maximumSwap(int num) {
        char[] chars = String.valueOf(num).toCharArray();
        int n = chars.length;
        for (int i = 0; i < n - 1; ++i) {
            int mx = i + 1;
            for (int j = i + 1; j < n; ++j) {
                if (chars[j] >= chars[mx]) {
                    mx = j;
                }
            }
            if (chars[i] < chars[mx]) {
                char t = chars[i];
                chars[i] = chars[mx];
                chars[mx] = t;
                break;
            }
        }
        return Integer.parseInt(String.valueOf(chars));
    }
}

C++

class Solution {
public:
    int maximumSwap(int num) {
        string s = to_string(num);
        int n = s.size();
        for (int i = 0; i < n - 1; ++i) {
            int mx = i + 1;
            for (int j = i + 1; j < n; ++j) {
                if (s[j] >= s[mx]) mx = j;
            }
            if (s[i] < s[mx]) {
                swap(s[i], s[mx]);
                break;
            }
        }
        return stoi(s);
    }
};

Go

func maximumSwap(num int) int {
	s := strconv.Itoa(num)
	chars := []byte(s)
	n := len(chars)
	for i := range chars[:n-1] {
		mx := i + 1
		for j := i + 1; j < n; j++ {
			if chars[j] >= chars[mx] {
				mx = j
			}
		}
		if chars[i] < chars[mx] {
			chars[i], chars[mx] = chars[mx], chars[i]
			break
		}
	}
	ans, _ := strconv.Atoi(string(chars))
	return ans
}

...