LeetCode關(guān)于Next Greater Element的問(wèn)題

關(guān)于我的 Leetcode 題目解答谁鳍,代碼前往 Github:https://github.com/chenxiangcyr/leetcode-answers


LeetCode題目:496. Next Greater Element I
You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.

The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.

Example 1:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
For number 1 in the first array, the next greater number for it in the second array is 3.
For number 2 in the first array, there is no next greater number for it in the second array, so output -1.

Example 2:
Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3,-1]
Explanation:
For number 2 in the first array, the next greater number for it in the second array is 3.
For number 4 in the first array, there is no next greater number for it in the second array, so output -1.

Note:

  • All elements in nums1 and nums2 are unique.
  • The length of both nums1 and nums2 would not exceed 1000.
class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        
        /* Time Complexity O(m * n)
        int[] result = new int[nums1.length];
        Arrays.fill(result, -1);
        
        for(int i = 0; i < nums1.length; i++) {
            boolean foundEqual = false;
            
            for(int j = 0; j < nums2.length; j++) {
                
                if(nums1[i] == nums2[j]) {
                    foundEqual = true;
                }
                
                if(nums1[i] < nums2[j] && foundEqual == true) {
                    result[i] = nums2[j];
                    break;
                }
            }
        }
        
        return result;
        */
        
        /*
        Time Complexity O(m + n)
        */
        
        Stack<Integer> stack = new Stack<>();
        
        // key: 數(shù)字导帝,value:next Greater Element
        Map<Integer, Integer> map = new HashMap<>();
        
        for(int num : nums2) {
            while(!stack.isEmpty() && num > stack.peek()) {
                int t = stack.pop();
                map.put(t, num);
            }
            
            stack.push(num);
        }
        
        while(!stack.isEmpty()) {
            int t = stack.pop();
            map.put(t, -1);
        }
        
        int[] result = new int[nums1.length];
        for(int i = 0; i < nums1.length; i++) {
            result[i] = map.get(nums1[i]);
        }
        
        return result;
    }
}

LeetCode題目:503. Next Greater Element II
Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, output -1 for this number.

Example 1:
Input: [1,2,1]
Output: [2,-1,2]
Explanation: The first 1's next greater number is 2;
The number 2 can't find next greater number;
The second 1's next greater number needs to search circularly, which is also 2.

Note: The length of given array won't exceed 10000.

class Solution {
    public int[] nextGreaterElements(int[] nums) {
        if(nums == null || nums.length == 0) return nums;
        
        // 存儲(chǔ)數(shù)字idx
        Stack<Integer> stack = new Stack<>();
        
        // key: 數(shù)字idx毙籽,value:next Greater Element
        Map<Integer, Integer> map = new HashMap<>();
        
        for(int i = 0; i < 2 * nums.length; i++) {
            while(!stack.isEmpty() && nums[i % nums.length] > nums[stack.peek()]) {
                int t = stack.pop();
                map.put(t, nums[i % nums.length]);
            }
            
            if (i < nums.length) stack.push(i);
        }
        
        while(!stack.isEmpty()) {
            int t = stack.pop();
            map.put(t, -1);
        }
        
        int[] result = new int[nums.length];
        for(int i = 0; i < nums.length; i++) {
            result[i] = map.get(i);
        }
        
        return result;
    }
}

LeetCode題目: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

思路參見(jiàn) https://leetcode.com/problems/next-greater-element-iii/discuss/101824/Simple-Java-solution-(4ms)-with-explanation.

class Solution {
    public int nextGreaterElement(int n) {
        char[] number = (n + "").toCharArray();
        
        /*
        從右邊開(kāi)始,找到第一個(gè)比右邊元素小的
        例如:534976蔓搞,找到了數(shù)字4對(duì)應(yīng)的位置2
        */
        int i = number.length - 1;
        while(i > 0 && number[i-1] >= number[i]) {
            i--;
        }

        // 表明所有數(shù)字已經(jīng)是升序排列了,得不到結(jié)果
        if (i == 0) {
            return -1;
        }
        
        i--; // 4的位置
        
        // 找到4的右邊比4大的所有元素中,最小的一個(gè)金赦,此時(shí)找到了6
        int x = number[i];
        int smallest = i + 1;
        for (int j = i + 1; j < number.length; j++) {
            if (number[j] > x && number[j] <= number[smallest]) {
                smallest = j;
            }
        }
        
        // 交換 4 和 6,得到536974
        char temp = number[i];
        number[i] = number[smallest];
        number[smallest] = temp;
        
        // 將6的后半部分974重新排序对嚼,得到 536479
        Arrays.sort(number, i + 1, number.length);
        
        long val = Long.parseLong(new String(number));
        return (val <= Integer.MAX_VALUE) ? (int) val : -1;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末夹抗,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子纵竖,更是在濱河造成了極大的恐慌漠烧,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,490評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件靡砌,死亡現(xiàn)場(chǎng)離奇詭異已脓,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)通殃,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)度液,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人画舌,你說(shuō)我怎么就攤上這事堕担。” “怎么了骗炉?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,830評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵照宝,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我句葵,道長(zhǎng)厕鹃,這世上最難降的妖魔是什么兢仰? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,957評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮剂碴,結(jié)果婚禮上把将,老公的妹妹穿的比我還像新娘。我一直安慰自己忆矛,他們只是感情好察蹲,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,974評(píng)論 6 393
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著催训,像睡著了一般洽议。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上漫拭,一...
    開(kāi)封第一講書(shū)人閱讀 51,754評(píng)論 1 307
  • 那天亚兄,我揣著相機(jī)與錄音,去河邊找鬼采驻。 笑死审胚,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的礼旅。 我是一名探鬼主播膳叨,決...
    沈念sama閱讀 40,464評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼痘系!你這毒婦竟也來(lái)了菲嘴?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,357評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤碎浇,失蹤者是張志新(化名)和其女友劉穎临谱,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體奴璃,經(jīng)...
    沈念sama閱讀 45,847評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,995評(píng)論 3 338
  • 正文 我和宋清朗相戀三年城豁,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了苟穆。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,137評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡唱星,死狀恐怖雳旅,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情间聊,我是刑警寧澤攒盈,帶...
    沈念sama閱讀 35,819評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站哎榴,受9級(jí)特大地震影響型豁,放射性物質(zhì)發(fā)生泄漏僵蛛。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,482評(píng)論 3 331
  • 文/蒙蒙 一迎变、第九天 我趴在偏房一處隱蔽的房頂上張望充尉。 院中可真熱鬧,春花似錦衣形、人聲如沸驼侠。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,023評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)倒源。三九已至,卻和暖如春句狼,著一層夾襖步出監(jiān)牢的瞬間相速,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,149評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工鲜锚, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留突诬,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,409評(píng)論 3 373
  • 正文 我出身青樓芜繁,卻偏偏與公主長(zhǎng)得像旺隙,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子骏令,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,086評(píng)論 2 355