【Lintcode】625. Partition Array II

題目地址:

https://www.lintcode.com/problem/partition-array-ii/description

給定一個數組,再給定兩個數lowlowhighhigh,要求重排數組,使得所有小於lowlow的數排在左邊,大於highhigh的數排在右邊,其餘數排在中間。要求in-place並且時間複雜度O(n)O(n)

思路是用三個指針l,r,il,r,i,其中保持A[0,l]<lowA[0,l]<lowA[r,len1]>highA[r,len-1]>high,並且A[l+1,i][low,high]A[l+1,i]\subset[low, high],不停右移ii指針直到與rr相撞即可。代碼如下:

public class Solution {
    /**
     * @param nums: an integer array
     * @param low: An integer
     * @param high: An integer
     * @return: nothing
     */
    public void partition2(int[] nums, int low, int high) {
        // write your code here
        if (nums == null ||  nums.length == 0) {
            return;
        }
        
        int l = -1, i = 0, r = nums.length;
        while (i < r) {
        	// 如果當前數字小於low,那麼就將其換到左邊;
        	// 由於我們已經保證了A(l, i]在low與high之間,所以交換完畢後,A[i]已經在low與high之間了,所以將i也右移
        	// 如果當前數字大於high,則將其換到右邊;如果當前數字在low與high直接,就直接右移i
            if (nums[i] < low) {
                swap(nums, i++, ++l);
            } else if (nums[i] > high) {
                swap(nums, i, --r);
            } else {
                i++;
            }
        }
    }
    
    private void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}

時間複雜度O(n)O(n),空間O(1)O(1)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章