[LeetCode] 556. Next Greater Element III

題目鏈接: https://leetcode.com/problems/next-greater-element-iii/description/

Description

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

解題思路

  1. 將整數拆分成一個個數字,從後往前尋找第一個比其後面數字小的位置,記爲keyPos
  2. 尋找keyPos後面數字中,比其大的最小的數字,與之交換;
  3. keyPos後面數字從小到大排序。

例子: 1346532

  1. 從後往前找 13**4**6532,找到keyPos爲下標2,即數字4;
  2. 將數字4與其後面的數字 6532 中比它大的最小的數字 5 交換,得到 13**5**6432;
  3. keyPos後面的數字,即 6432 從小到大排序得到結果,1352346

Code

class Solution {
public:
    int nextGreaterElement(int n) {
        vector<int> nums;
        int temp = n;
        long res = 0;

        while (temp != 0) {
            nums.push_back(temp % 10);
            temp /= 10;
        }

        int keyPos = 1;
        while (keyPos < nums.size() && nums[keyPos] >= nums[keyPos - 1]) keyPos++;
        if (keyPos >= nums.size()) return -1;        

        int firstBigPos = keyPos - 1;
        for (int i = firstBigPos - 1; i >= 0; --i) {
            if (nums[i] > nums[keyPos] && nums[i] < nums[firstBigPos]) firstBigPos = i;
        }

        temp = nums[keyPos];
        nums[keyPos] = nums[firstBigPos];
        nums[firstBigPos] = temp;

        sort(nums.begin(), nums.begin() + keyPos, [](int a, int b) {return a > b;});

        for (int i = nums.size() - 1; i >= 0; --i) res = res * 10 + nums[i];

        return res > INT_MAX ? -1 : res;
    }
};
發佈了60 篇原創文章 · 獲贊 18 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章