[LeetCode] 556. Next Greater Element III 下一个较大的元素 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 nand 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
给一个32字节的正整数,找出由同样数位组成比给定数大的数字中最小的,其实就是对各个数位重新排序,求出刚好比给定数字大的一种排序,如果不存在就返回-1。
Java:
public class Solution {
public int nextGreaterElement(int n) {
char[] number = (n + "").toCharArray();
int i, j;
// I) Start from the right most digit and
// find the first digit that is
// smaller than the digit next to it.
for (i = number.length-1; i > 0; i--)
if (number[i-1] < number[i])
break;
// If no such digit is found, its the edge case 1.
if (i == 0)
return -1;
// II) Find the smallest digit on right side of (i-1)'th
// digit that is greater than number[i-1]
int x = number[i-1], smallest = i;
for (j = i+1; j < number.length; j++)
if (number[j] > x && number[j] <= number[smallest])
smallest = j;
// III) Swap the above found smallest digit with
// number[i-1]
char temp = number[i-1];
number[i-1] = number[smallest];
number[smallest] = temp;
// IV) Sort the digits after (i-1) in ascending order
Arrays.sort(number, i, number.length);
long val = Long.parseLong(new String(number));
return (val <= Integer.MAX_VALUE) ? (int) val : -1;
}
}
Java:
class Solution {
public int nextGreaterElement(int n) {
// The same as : leetcode 31 Next Permutation, O(n)
char[] number = (n + "").toCharArray();
int i = -1;
//1. find backwards
for(i = number.length - 1; i > 0; i--)
if(number[i - 1] < number[i])
break;
if(i == 0)
return -1;
//2. first, second
int first = i - 1, second = i;
//3. find the next greater than first, backward
for(i = number.length - 1; i > first; i--) {
if(number[i] > number[first]) {
char temp = number[i];
number[i] = number[first];
number[first] = temp;
break;
}
}
//4. reverse after second
reverse(number, second);
//5. Transform back
long val = Long.parseLong(new String(number));
return (val <= Integer.MAX_VALUE) ? (int) val : -1;
}
private void reverse(char[] a,int i)//reverse the number after the number we have found
{
int first = i;
int last = a.length-1;
while(first<last)
{
char t = a[first];
a[first] = a[last];
a[last] = t;
first ++;
last --;
}
}
}
Python:
# Time: O(logn) = O(1)
# Space: O(logn) = O(1)
class Solution(object):
def nextGreaterElement(self, n):
"""
:type n: int
:rtype: int
"""
digits = map(int, list(str(n)))
k, l = -1, 0
for i in xrange(len(digits) - 1):
if digits[i] < digits[i + 1]:
k = i if k == -1:
digits.reverse()
return -1 for i in xrange(k + 1, len(digits)):
if digits[i] > digits[k]:
l = i digits[k], digits[l] = digits[l], digits[k]
digits[k + 1:] = digits[:k:-1]
result = int("".join(map(str, digits)))
return -1 if result >= 0x7FFFFFFF else result
C++:
class Solution {
public:
int nextGreaterElement(int n) {
string str = to_string(n);
int len = str.size(), i = len - 1;
for (; i > 0; --i) {
if (str[i] > str[i - 1]) break;
}
if (i == 0) return -1;
for (int j = len - 1; j >= i; --j) {
if (str[j] > str[i - 1]) {
swap(str[j], str[i - 1]);
break;
}
}
sort(str.begin() + i, str.end());
long long res = stoll(str);
return res > INT_MAX ? -1 : res;
}
};
C++:
/**
* 1. a max number has the property of decreasing in every digit: 9876
* 2. find the first non-max substring from the right; ex. in 1234(59876), 59876 is the first non-max substring from the right
* 3. sort the max part of 5(9876), by reverse, becames 5(6789);
* 4. flip 5,6, becames 65789; because 6 is the next smallest digit than 5, in 56789;
* 5. incase of 66789, you got flip 6 with 7 to make it 76689, to make it bigger.
*/
class Solution {
public:
int nextGreaterElement(int n) {
string s = to_string(n);
if (s.length() == 1) {
return -1;
}
/* find the first decreasing digit from the right, eg: 59876, 5 is the first decreasing digit */
int i = s.length() - 2; // 21 -> i = 0; 59876 -> i = 3
for (; i >= 0 && s[i] >= s[i + 1]; i--) { }
if (i == -1) { // if a decreasing digit cannot be find, the number cannot be larger.
return -1;
}
reverse(s.begin() + i + 1, s.end());
for (int j = i + 1; j < s.length(); j++) {
if (s[j] > s[i]) {
swap(s[i], s[j]);
break;
}
}
long next = stol(s);
return next == n || next > INT_MAX ? -1 : next;
}
};
C++: using next permutation
int nextGreaterElement(int n) {
auto digits = to_string(n);
next_permutation(begin(digits), end(digits));
auto res = stoll(digits);
return (res > INT_MAX || res <= n) ? -1 : res;
}
类似题目:
[LeetCode] 496. Next Greater Element I 下一个较大的元素 I
[LeetCode] 503. Next Greater Element II 下一个较大的元素 II
All LeetCode Questions List 题目汇总
[LeetCode] 556. Next Greater Element III 下一个较大的元素 III的更多相关文章
- [LeetCode] 496. Next Greater Element I 下一个较大的元素 I
You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of n ...
- [LeetCode] 503. Next Greater Element II 下一个较大的元素 II
Given a circular array (the next element of the last element is the first element of the array), pri ...
- [LeetCode] Next Greater Element II 下一个较大的元素之二
Given a circular array (the next element of the last element is the first element of the array), pri ...
- Leetcode496.Next Greater Element I下一个更大的元素1
给定两个没有重复元素的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集.找到 nums1 中每个元素在 nums2 中的下一个比其大的值. nums1 中数字 x 的下一个更 ...
- [leetcode]496. Next Greater Element I下一个较大元素
You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of n ...
- lintcode-1174.下一个更大的元素 III
题目描述: 1174. 下一个更大的元素 III 给定一个32位整数n,用同样的数字组成新的32位整数,使得它要比n大,返回最小的这样的数.如果不存在这样的整数,返回-1. 算法思路: 首先将这个数转 ...
- 503 Next Greater Element II 下一个更大元素 II
给定一个循环数组(最后一个元素的下一个元素是数组的第一个元素),输出每个元素的下一个更大元素.数字 x 的下一个更大的元素是按数组遍历顺序,这个数字之后的第一个比它更大的数,这意味着你应该循环地搜索它 ...
- 496 Next Greater Element I 下一个更大元素 I
给定两个没有重复元素的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集.找到 nums1 中每个元素在 nums2 中的下一个比其大的值.nums1 中数字 x 的下一个更大 ...
- [LeetCode] Next Greater Element I 下一个较大的元素之一
You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of n ...
随机推荐
- Codeforces C. Elections(贪心枚举三分)
题目描述: C. Elections time limit per test 2 seconds memory limit per test 256 megabytes input standard ...
- 项目Alpha冲刺(团队)-第九天冲刺
格式描述 课程名称:软件工程1916|W(福州大学) 作业要求:项目Alpha冲刺(团队) 团队名称:为了交项目干杯 作业目标:描述第九天冲刺的项目进展.问题困难.心得体会 队员姓名与学号 队员学号 ...
- 4、markdown基本语法
一.前言 由于有些语法无法在博客园展示,推荐使用Typora解锁全套,下载地址:https://www.typora.io/ 推荐使用jupyter,使用方法:https://www.cnblogs. ...
- 七牛云——qshell一个神奇的工具
前言 qshell是利用七牛文档上公开的API实现的一个方便开发者测试和使用七牛API服务的命令行工具.该工具设计和开发的主要目的就是帮助开发者快速解决问题.目前该工具融合了七牛存储,CDN,以及其他 ...
- 含-SH的ACE抑制药的青霉胺样反应
关于 含-SH的血管紧张素转化酶(ACE)抑制药如卡托普利具有青霉胺样反应.而依那普利则不含-SH. 青霉胺样反应 青霉胺样反应,指应用含-SH的ACE抑制药产生的皮疹.嗜酸性粒细胞(E)增多.味觉异 ...
- LeetCode 958. Check Completeness of a Binary Tree
原题链接在这里:https://leetcode.com/problems/check-completeness-of-a-binary-tree/ 题目: Given a binary tree, ...
- go正则表达式
单行模式(?s:(.?))万能用法尽量匹配少的文本,最关键的是可以匹配换行的文本,直接写.?不能匹配\n package main import ( "fmt" "reg ...
- 【洛谷P5019】铺设道路
题目链接 众所周知,这道题和积木大赛是同一道题 题意就是给出一段自然数序列,每次操作\((L,R)\)把区间\([L,R]\)的数全部减一,不允许出现负数,问把序列变为零的最小操作次数 贪心做法 样例 ...
- python计算1~2008中0和1的个数
计算1~2008中所有自然数中1和0的个数总数. 通过自然数的大小划分区间,将自然数每位上的数载入列表,循环计数. list = [] onecount = 0 zerocount = 0 for i ...
- [golang]Golang实现高并发的调度模型---MPG模式
Golang实现高并发的调度模型---MPG模式 传统的并发形式:多线程共享内存,这也是Java.C#或者C++等语言中的多线程开发的常规方法,其实golang语言也支持这种传统模式,另外一种是Go语 ...