暑假算法7.20,Day19
贪心
第一题
class Solution {
public:
int integerReplacement(int n) {
int ans=0;
long long x=n;
while(x>1){
if(x%2==0) x=x/2;
else if((x+1)%4==0&&(x-1)%4==0)x=x-1;
else if((x+1)%4==0&&((x+1)/2<x-1)) x=x+1;
else if((x-1)%4==0) x=x-1;
else x=x-1;
ans++;
}
return ans;
}
};
第二题
class Solution {
public:
int maximumSwap(int num) {
string st = to_string(num);
string st_sort = st;
sort(st_sort.rbegin(),st_sort.rend());
int len = st.length();
int id = -1;
char maxval=char('0'-1);
for (int i = 0 ; i < len ; i++){
if (st[i]==st_sort[i]) continue;
if (st[i]>=maxval){
maxval = st[i];
id = i;
}
}
for ( int i = 0 ; i < id ; i++){
if (st[i]<st[id]){
swap(st[i],st[id]);
break;
}
}
return stoi(st);
}
};
第三题
class Solution {
public:
int smallestRangeII(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
int result = nums[nums.size() - 1] - nums[0];
for (int i = 1; i < nums.size(); i++) {
int minValue = min(nums[0] + k, nums[i] - k);
int maxValue = max(nums[nums.size() - 1] - k, nums[i - 1] + k);
result = min(maxValue - minValue, result);
}
return result;
}
};