leetcode 556. Next Greater Element III

leetcode 556. Next Greater Element III

The meaning of the question: Give you a number n, let you swap some bits in this number, and find the smallest number larger than n, n is 32 bits. If there is, output that number, if not, output -1.

Idea: Just simulate the exchange process.

See an example, for 230241

We can swap i = 2,j = 3; i=2,j=4; i=2;j=5 to make this number larger; obviously when i is the same, the number with the smallest a[j] takes precedence.

We can swap i = 2,j = 4; i=3,j=4; to make this number larger; obviously when j is the same, the number with the largest i takes precedence.

If it is the smallest, find the optimal i,j, and sort [j+1,n].

Just find the rules.

class Solution {
public:
	int nextGreaterElement(long long  n) {
		long long a[15], l;
		stack<int> s;
		l = 0;
		while (n)
		{
			s.push(n % 10);
			n /= 10;
		}
		while (!s.empty())
		{
			a[l++] = s.top();
			s.pop();
		}
		long long  ans = 0xffffffff;
		int lasti = -1, lastj = -1;
		for (int i = l-1; i >= 0; i--)
			for (int j = i - 1; j >= 0; j--)
			{
				if (a[i] > a[j])
				{
					if (j > lastj)
					{
						lasti = i;
						lastj = j;
					}
					else if (j == lastj )
					{
						if (a[i] < a[lasti])
						{
							lasti = i;
							lastj = j;
						}
					}
				}
			}
		if (lasti == -1 && lastj == -1) return -1;
		//cout << lasti << '\t' << lastj << '\n';
		swap(a[lasti],a[lastj]);
		sort(a+lastj+1,a+l);
		long long num = 0;
		for (int i = 0; i < l; i++)
			num = num * 10 + a[i];
		if (num > INT_MAX) return - 1;
		return num;
	}
};
There is a pit that explodes the -1 of the int output! ! ! !

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324618835&siteId=291194637