leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0670.cpp (505B)


      1 class Solution {
      2   public:
      3     int maximumSwap(int numi) const {
      4         string num = to_string(numi);
      5         const int n = size(num);
      6         int last[10] = {0};
      7 
      8         for (int i = 0; i < n; i++)
      9             last[num[i] - '0'] = i;
     10         for (int i = 0; i < n; i++) {
     11             for (int d = 9; d > num[i] - '0'; d--) {
     12                 if (last[d] <= i) continue;
     13                 swap(num[i], num[last[d]]);
     14                 return stoi(num);
     15             }
     16         }
     17 
     18         return numi;
     19     }
     20 };