[Leetcode学习-c ++&java]次の大要素I〜III

问题:次の大要素I

難易度:簡単

説明:

タイトルは、配列Aが配列Bの部分文字列であることを示し、次にAの要素、Bの位置を検索し、次にBのその位置から、値が要素の値よりも大きい最初の要素を検索するように求めます。 、そしてすべての要素を返します大きな要素のコレクション。

件名リンク:https//leetcode.com/problems/next-greater-element-i/

入力範囲:

  • すべての要素 nums1 とは nums2 ユニークです。
  • 両方の長さ nums1 とは、  nums2 1000年を超えないであろう。

ケースを入力してください:

Example 1:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]  // 注意 1 在 nums2 是第一个,右边比他大第一个是 3
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.

私のコード:

単純で暴力的な場合は、トリプルループになり、Aセットをトラバースしてから、Bセットの同等の要素を見つけ、その位置からBセットをトラバースして、右側の最初の要素を見つけます。

ただし、Aで要素が重複しないように、マップをキャッシュとして追加できます。

次に、Bのすべての要素をマップにしてから、Aを直接トラバースして高速化します。

Java:

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        int[] greater = new int[nums1.length];
        HashMap<Integer, Integer> cache = new HashMap<Integer, Integer>();
        for(int j = 0;j < nums2.length;j ++) 
            for(int t = j + 1;t < nums2.length;t ++) 
                if(nums2[j] < nums2[t]) {
                    cache.put(nums2[j], nums2[t]);
                    break;
                }
        for(int i = 0;i < nums1.length;i ++) {
           if(cache.containsKey(nums1[i])) greater[i] = cache.get(nums1[i]);
           else greater[i] = -1;
        }
        return greater;
    }
}

C ++:

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
        map<int, int> cache;
        vector<int> greater;
        for(int i = 0;i < nums2.size();i ++) 
            for(int j = i + 1;j < nums2.size();j ++) 
                if(nums2[j] > nums2[i]) {
                    cache[nums2[i]] = nums2[j];
                    break;
                }
        for(int i = 0;i < nums1.size();i ++)
            if(cache.count(nums1[i])) greater.push_back(cache[nums1[i]]);
            else greater.push_back(-1);
        return greater;
    }
};

質問:次の大要素II

難易度:中

説明:

タイトルに配列が与えられ、配列が端から端まで接続されます。その中のすべての要素の右側にある最初の大きな要素を見つける必要があります。

件名リンク:https//leetcode.com/problems/next-greater-element-ii/

入力範囲:

  • 指定された配列の長さは10000を超えません。

ケースを入力してください:

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.

私のコード:

暴力は簡単に解決できませんが、これにより実行時間が遅くなります。

暴力(線を抑える):

Java:

class Solution {
    public int[] nextGreaterElements(int[] nums) {
        int[] greater = new int[nums.length];
        for(int i = 0, len = nums.length, j, t;i < len;greater[i] = j < len ? nums[t] : -1, i ++)
            for(j = 1, t = (i + j) % len;j < len && nums[t] <= nums[i];j ++, t = (i + j) % len);
        return greater;
    }
}

O(m * n)の時間計算量で、非常に満足のいく単調なスタックを作成することもできます。

Java:

class Solution {
    public int[] nextGreaterElements(int[] nums) {
        int top = 0, len = nums.length, i;
        int[] greater = new int[len];
        if(nums.length == 0) return greater;
        int[][] mStack = new int[len][2];
        for(i = 1, mStack[top][0] = nums[0];i < len;i ++) {
            while(top >= 0 && nums[i] > mStack[top][0]) {
                greater[mStack[top][1]] = nums[i]; top --;
            }
            mStack[++ top][0] = nums[i];
            mStack[top][1] = i;
        }
        while(top >= 0) {
            for(i = 0;i < len;i ++) {
                while(top >= 0 && nums[i] > mStack[top][0]) {
                    greater[mStack[top][1]] = nums[i]; top --;
                }
            }
            greater[mStack[top --][1]] = -1;
        }
        return greater;
    }
}

C ++:

class Solution {
public:
    vector<int> nextGreaterElements(vector<int>& nums) {
		int len = nums.size(), top = 0, i;
		vector<int> greater(len);
		if (!len) return greater;
		int (*mStack)[2] = new int[len][2];
		for (i = 1, mStack[top][0] = nums[0], mStack[top][1] = 0; i < len; i++) {
			while (top >= 0 && nums[i] > mStack[top][0]) {
				greater[mStack[top][1]] = nums[i]; top--;
			}
			mStack[++top][0] = nums[i];
			mStack[top][1] = i;
		}
		for (i = 0; i < len; i++) {
			while (top >= 0 && nums[i] > mStack[top][0]) {
				greater[mStack[top][1]] = nums[i]; top--;
			}
		}
		while (top >= 0) greater[mStack[top--][1]] = -1;
		return greater;
	}
};

问题:次の大要素III

難易度:中

説明:

質問は数値Nを与え、桁数は同じであり、各桁で結合された新しい数値は最小で、Nより大きい数だけです。存在しないか、intを超える場合は、-1を返します。

タイトルリンク:https//leetcode.com/problems/next-greater-element-iii/

入力範囲:

  • 1 <= n <= 231 - 1

ケースを入力してください:

Example 1:
Input: n = 12
Output: 21

Example 2:
Input: n = 21
Output: -1

私のコード:

Nより少し大きく、次に最小のもの

1.尾から最初のN [i-1] <N [i]を見つけます。

2. N [i] 〜N [len]> N [i-1]とN [i-1]の最小数を交換します。

3.最後に、N [i + 1] 〜N [len]を並べ替えます

C ++とJavaは異なる順序で比較するだけです

Java:

class Solution {
    public int nextGreaterElement(int n) {
        char[] chs = String.valueOf(n).toCharArray();
            int[] nums = new int[chs.length];
            for(int i = chs.length; i -- > 0;) nums[i] = chs[i] - '0';
            for(int i = nums.length; i -- > 1;) {
                if(nums[i - 1] < nums[i]) { // 先找出 下降的数字
                    int ti = i;
                    // 从 i 开始找出最小的 > nums[i - 1]的数
                    while(ti + 1 < nums.length && nums[i - 1] < nums[ti + 1]) ti ++;
                    // 然后置换 
                    nums[i - 1] ^= nums[ti];
                    nums[ti] ^= nums[i - 1];
                    nums[i - 1] ^= nums[ti];
                    // 最后重排序一遍
                    for(int j = i, end = chs.length - 1; j < end; j ++, end --) {
                        int tj = j;
                        while(tj + 1 <= end && nums[j] >= nums[tj + 1]) tj ++;
                        nums[tj] ^= nums[j];
                        nums[j] ^= nums[tj];
                        nums[tj] ^= nums[j];
                    }
                    // 转为数字输出
                    for(int j = nums.length;j -- > 0;) chs[j] = (char)(nums[j] + '0');
                    try { // 我决定用 try...catch 这个奇淫技巧
                        return Integer.valueOf(new String(chs));
                    } catch (Exception e) {
                        return -1;
                    }
                }
            }
            return -1;
    }
}

C ++:

class Solution {
public:
	int nextGreaterElement(int n) {
		int index = 0, tens = 10, nums[32];
		long long res = 0;
		for (; n; n /= tens) 
			nums[index++] = n % tens;
		for (int i = 0; i < index - 1; i++) {
			if (nums[i] > nums[i + 1]) {
				int ti = i + 1, begin = 0;
				for (; ti - 1 >= 0 && nums[ti - 1] > nums[i + 1]; ti--);
				swap(nums[ti], nums[i + 1]);
				for (int j = i; j > begin; j--, begin ++) {
					int tj = j;
					while (tj - 1 >= begin && nums[j] >= nums[tj - 1]) tj--;
					swap(nums[tj], nums[j]);
				}
				for (int j = index; j -- > 0;) 
					if(res * tens <= INT_MAX) res = res * tens + nums[j];
					else return -1;
				return res;
			}
		}
		return - 1;
	}
};

 

おすすめ

転載: blog.csdn.net/qq_28033719/article/details/111604585