slow:
class Solution { public: int maximumSwap(int num) { string s = to_string(num); int pos[10] = { -1 }; for (int i = s.length() - 1; i >= 0; i--) { if (i > pos[s[i]-'0']) pos[s[i]-'0'] = i; } for (int i = 0; i < s.length(); i++) { for (int j = 9; j > s[i]-'0'; j--) if (pos[j] > i) { swap(s[pos[j]], s[i]); return stoi(s); } } return num; } };
faster:
class Solution { public: int maximumSwap(int num) { string s = to_string(num); int x = -1, y = -1, _max = s.length() - 1; for (int i = s.length() - 2; i >= 0; i--) { if (s[i] > s[_max]) { _max = i; } else if (s[i] < s[_max]) { x = i; y = _max; } } if (x >= 0) { swap(s[x], s[y]); } return stoi(s); } };