556. Next Greater Element III下一个更大的数字

[抄题]:

Given a positive 32-bit integer n, you need to find the smallest 32-bit integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive 32-bit integer exists, you need to return -1.

Example 1:

Input: 12
Output: 21

Example 2:

Input: 21
Output: -1

[暴力解法]:

时间分析:

空间分析:

[优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

完全没思路啊:这种题一般是从递增/递减的角度来考虑

[英文数据结构或算法,为什么不用别的数据结构或算法]:

parselong里面是字符串型

long val = Long.parseLong(new String(nums));

[一句话思路]:

找到递增元素,把前面的一个最小元素往后换,然后后半截排序

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

556. Next Greater Element III下一个更大的数字

[一刷]:

  1. smallest是大的那边,所以从i开始换, nums[i-1]保持不变就行了

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[五分钟肉眼debug的结果]:

[总结]:

找到递增元素,把前面的一个最小元素往后换,然后后半截排序

[复杂度]:Time complexity: O() Space complexity: O()

[算法思想:迭代/递归/分治/贪心]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

[代码风格] :

[是否头一次写此类driver funcion的代码] :

[潜台词] :

class Solution {
public int nextGreaterElement(int n) {
//initilization: new array
char[] nums = (n + "").toCharArray();
int i; //find the increasing element from the end to ensure the first bigger
for (i = nums.length - 1; i > 0; i--) {
if (nums[i] > nums[i - 1]) {
break;
}
}
//corner case: decrease, put the inner variable together
if (i == 0) return -1; //find the later element
int smallest = i;
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] > nums[i - 1] && nums[j] <= nums[smallest]) {
smallest = j;
}
} //swap the smaller with the later element
char temp = nums[smallest];
nums[smallest] = nums[i - 1];
nums[i - 1] = temp; //sort the later element
Arrays.sort(nums, i, nums.length); //change to long and int, notice corner case
long val = Long.parseLong(new String(nums));
return (val <= Integer.MAX_VALUE) ? (int) val : -1;
}
}
上一篇:Python3 pip出现Fatal error in launcher: Unable to create process using '"'


下一篇:精讲响应式WebClient第2篇-GET请求阻塞与非阻塞调用方法详解