LeetCode.670

来源:互联网 发布:淘宝卖美瞳最好的店铺 编辑:程序博客网 时间:2024/05/16 14:46
/*
Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get.


Example 1:
Input: 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.


Example 2:
Input: 9973
Output: 9973
Explanation: No swap.


Note:
The given number is in the range [0, 10^8]

*/

#include <iostream>#include <vector>#include <algorithm>using namespace std;int maximumSwap(int num){int temp = num;vector<int> v;vector<int> t;while(temp != 0){v.push_back(temp % 10);t.push_back(temp % 10);temp /= 10;}vector<int>::iterator max;int max_point;int arr[v.size()];while(t.size() > 1){max = max_element(t.begin(),t.end());max_point = distance(t.begin(), max);if(*max == *(t.end() - 1)){t.pop_back();}else{swap(v[max_point], v[t.size() - 1]);break;}}for(int i = v.size() - 1; i > -1; i--){cout << v[i];}cout << endl;int result = 0;for(int i = v.size() - 1; i >= 0; i--){result = result * 10 + v[i];}return result;}


原创粉丝点击