【劍指offer-Java版】36數組中的逆序對__Java

來源:互聯網
上載者:User

數組中的逆序對:歸併排序的另類應用

數組中的逆序對:給定的數組,如果兩個數字中前面一個數字大於後面的一個,那麼稱為一個逆序對,數組中所有滿足此關係的逆序對總數就是這個數組的逆序對

此處的實現並不優雅,畢竟copy數組是不需要的,只需要一個局部的就可以
但是如果使用的是一個局部的空間複雜度是logn的輔助數組,會造成代碼有一點點難理解

另外,書上的明顯是錯誤的代碼,沒有運行過,但是從邏輯上來分析,應該會出現重複統計的問題

    public class _Q36<T> {    public int InversePairs(int nums[]){        if(nums == null) return 0;        int copy[] = Arrays.copyOf(nums, nums.length);        CommonUtils.PrintArray(copy);        return InversePairsCore(nums, copy, 0, nums.length - 1);    }    private int InversePairsCore(int nums[], int copy[], int indexL, int indexR){        if(nums == null || indexL > indexR) return 0;        if (indexL == indexR) {            //copy[indexL] = nums[indexL];            return 0;        }        int len = (indexR - indexL) / 2;        int leftCount = InversePairsCore(nums, copy, indexL, indexL + len);        int rightCount = InversePairsCore(nums, copy, indexL + len + 1, indexR);        int i = indexL + len;        int j = indexR;        int indexCopy = indexR;        int count = 0;        while(i >= indexL && j >= indexL + len + 1){            if(nums[i] > nums[j]){ // 出現逆序對                copy[indexCopy--] = nums[i--];                count = count + j - len - indexL;            }else{                copy[indexCopy--] = nums[j--];            }        }        while(i >= indexL) copy[indexCopy--] = nums[i--];        while(j >= indexL + len + 1) copy[indexCopy--] = nums[j--];        for(int k=indexL; k<=indexR; k++){            nums[k] = copy[k];        }        CommonUtils.PrintArray(copy);        return leftCount + count + rightCount;    }    }

測試代碼:

    public class _Q36Test extends TestCase {    _Q36 inversePair = new _Q36();    public void test(){        int array[] = {7, 5, 6, 4};        System.out.println(inversePair.InversePairs(array));    }    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.