|
41 | 41 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
42 | 42 |
|
43 | 43 | ```python
|
44 |
| - |
| 44 | +class Solution: |
| 45 | + def maximumSwap(self, num: int) -> int: |
| 46 | + chars = list(str(num)) |
| 47 | + n = len(chars) |
| 48 | + for i in range(n - 1): |
| 49 | + mx = i + 1 |
| 50 | + for j in range(i + 1, n): |
| 51 | + if ord(chars[j]) >= ord(chars[mx]): |
| 52 | + mx = j |
| 53 | + if ord(chars[i]) < ord(chars[mx]): |
| 54 | + chars[i], chars[mx] = chars[mx], chars[i] |
| 55 | + break |
| 56 | + return int(''.join(chars)) |
45 | 57 | ```
|
46 | 58 |
|
47 | 59 | ### **Java**
|
48 | 60 |
|
49 | 61 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
50 | 62 |
|
51 | 63 | ```java
|
| 64 | +class Solution { |
| 65 | + public int maximumSwap(int num) { |
| 66 | + char[] chars = String.valueOf(num).toCharArray(); |
| 67 | + int n = chars.length; |
| 68 | + for (int i = 0; i < n - 1; ++i) { |
| 69 | + int mx = i + 1; |
| 70 | + for (int j = i + 1; j < n; ++j) { |
| 71 | + if (chars[j] >= chars[mx]) { |
| 72 | + mx = j; |
| 73 | + } |
| 74 | + } |
| 75 | + if (chars[i] < chars[mx]) { |
| 76 | + char t = chars[i]; |
| 77 | + chars[i] = chars[mx]; |
| 78 | + chars[mx] = t; |
| 79 | + break; |
| 80 | + } |
| 81 | + } |
| 82 | + return Integer.parseInt(String.valueOf(chars)); |
| 83 | + } |
| 84 | +} |
| 85 | +``` |
| 86 | + |
| 87 | +### **C++** |
| 88 | + |
| 89 | +```cpp |
| 90 | +class Solution { |
| 91 | +public: |
| 92 | + int maximumSwap(int num) { |
| 93 | + string s = to_string(num); |
| 94 | + int n = s.size(); |
| 95 | + for (int i = 0; i < n - 1; ++i) |
| 96 | + { |
| 97 | + int mx = i + 1; |
| 98 | + for (int j = i + 1; j < n; ++j) |
| 99 | + { |
| 100 | + if (s[j] >= s[mx]) mx = j; |
| 101 | + } |
| 102 | + if (s[i] < s[mx]) |
| 103 | + { |
| 104 | + swap(s[i], s[mx]); |
| 105 | + break; |
| 106 | + } |
| 107 | + } |
| 108 | + return stoi(s); |
| 109 | + } |
| 110 | +}; |
| 111 | +``` |
52 | 112 |
|
| 113 | +### **Go** |
| 114 | +
|
| 115 | +```go |
| 116 | +func maximumSwap(num int) int { |
| 117 | + s := strconv.Itoa(num) |
| 118 | + chars := []byte(s) |
| 119 | + n := len(chars) |
| 120 | + for i := range chars[:n-1] { |
| 121 | + mx := i + 1 |
| 122 | + for j := i + 1; j < n; j++ { |
| 123 | + if chars[j] >= chars[mx] { |
| 124 | + mx = j |
| 125 | + } |
| 126 | + } |
| 127 | + if chars[i] < chars[mx] { |
| 128 | + chars[i], chars[mx] = chars[mx], chars[i] |
| 129 | + break |
| 130 | + } |
| 131 | + } |
| 132 | + ans, _ := strconv.Atoi(string(chars)) |
| 133 | + return ans |
| 134 | +} |
53 | 135 | ```
|
54 | 136 |
|
55 | 137 | ### **...**
|
|
0 commit comments