力扣算法 - 分割數(shù)組

題目

給定一個(gè)數(shù)組 A,將其劃分為兩個(gè)不相交(沒(méi)有公共元素)的連續(xù)子數(shù)組 left 和 right, 使得:

left 中的每個(gè)元素都小于或等于 right 中的每個(gè)元素。 left 和 right 都是非空的。 left 要盡可能小。 在完成這樣的分組后返回 left 的長(zhǎng)度。可以保證存在這樣的劃分方法。

力扣-分割數(shù)組

示例 1:
輸入:[5,0,3,8,6]
輸出:3
解釋:left = [5,0,3],right = [8,6]
示例 2:
輸入:[1,1,1,0,6,12]
輸出:4
解釋:left = [1,1,1,0],right = [6,12]
思路
  • 從左往右找出所有數(shù)組子集, 對(duì)應(yīng)子集的最大值 記錄在數(shù)組 maxLeft
  • 從右往做找出反向數(shù)組子集,對(duì)應(yīng)子集最小值 記錄在數(shù)組 minRight
  • 然后比較 maxLeft[i] 與 minRight[i+1]

例如:
數(shù)組 [5] 所有子集最大值為 5
數(shù)組 [5 ,0] 所有子集最大值為 5
數(shù)組 [5 ,0, 3] 所有子集最大值為 5
數(shù)組 [5 ,0, 3 , 8] 所有子集最大值為 8
數(shù)組 [5 ,0, 3, 8, 6] 所有子集最大值為 5
maxLeft = [ 5, 5, 5, 8, 8]
同理可得 minRight = [0, 0 ,3, 6, 6]
比較時(shí)候 maxLeft[0] 與 minRight[1] 相當(dāng)于是 [5] 在和 [0, 3, 8, 6] 數(shù)組中最大值和最小值進(jìn)行比較

Swift實(shí)現(xiàn)代碼
 func partitionDisjoint(_ A: [Int]) -> Int {
        
        let count = A.count
        
        var maxLeft = [Int](repeating: 0, count: count)
        var minRight = [Int](repeating: 0, count: count)
        
        var firstLeft = A[0]
        var leftIndex = 0
        while leftIndex < count {
            firstLeft = max(firstLeft, A[leftIndex])
            maxLeft[leftIndex] = firstLeft
            leftIndex = leftIndex + 1
        }
        
        var firstRight = A[count-1]
        var rightIndex = count-1
        while rightIndex > 0 {
            firstRight = min(firstRight, A[rightIndex])
            minRight[rightIndex] = firstRight
            rightIndex = rightIndex - 1
        }
        
        var tempIndex = 0
        while tempIndex < count - 1 {
            if maxLeft[tempIndex] <= minRight[tempIndex+1] {
                return tempIndex + 1
            }
            tempIndex = tempIndex + 1
        }
        return 0
    }
Java實(shí)現(xiàn)代碼
 public static int partitionDisjoint(int[] A) {
        int N = A.length;
        int[] maxleft = new int[N];
        int[] minRight = new int[N];

        int firstLeft = A[0];
        for (int i = 0; i < N; i++) {
            firstLeft = Math.max(firstLeft, A[i]);
            maxleft[i] = firstLeft;
        }

        int firstRight = A[N-1];
        for (int i = N-1; i > 0; i--) {
            firstRight = Math.min(firstRight, A[i]);
            minRight[i] = firstRight;
        }

        for (int i = 0; i < N -1; i++) {
            if (maxleft[i] <= minRight[i + 1]) {
                return i + 1;
            }
        }
       return 0;
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容