1. 程式人生 > >劍指offer 第九天

劍指offer 第九天

資源 OS etl 輸入一個數 strong com 判斷 new rt+

35.數組中的逆序對

在數組中的兩個數字,如果前面一個數字大於後面的數字,則這兩個數字組成一個逆序對。輸入一個數組,求出這個數組中的逆序對的總數P。並將P對1000000007取模的結果輸出。 即輸出P%1000000007

輸入描述:

題目保證輸入的數組中沒有的相同的數字

數據範圍:

對於%50的數據,size<=10^4
對於%75的數據,size<=10^5
對於%100的數據,size<=2*10^5

示例1

輸入1,2,3,4,5,6,7,0 輸出7

public class Solution {
    public int InversePairs(int [] array) {
        if(array == null||array.length == 0) return 0;
        int length = array.length;
        int[] copy = new int[length];
        for(int i = 0;i < length ;i++){
            copy[i] = array[i];
        }
        int count = InversePairsCore(array,copy,0,array.length-1);
        return count;
    }
    
    public int InversePairsCore(int[] array,int[] copy,int start,int end){
        if(start == end){
            return 0;
        }
        int count = 0;
        int length = (end-start)/2;
        //註意:這裏是故意將copy和array調換位置的,因為每次執行InversePairCore之後copy在[start,end]部分都是排好序的
        //隨意使用data作為array輸入,省去了來回復制的資源消耗。
        int left = InversePairsCore(copy,array,start,start+length);
        int right = InversePairsCore(copy,array,start+length+1,end);
        int p1 = start+length;
        int p2 = end;
        int copyIdx = end;
        while(p1 >= start && p2 >= start+length+1){
            if(array[p1]>array[p2]){
                count += p2-start-length;
                //此處先判斷一下,以免超出運算範圍。
                if(count > 1000000007)
                    count = count%1000000007;
                copy[copyIdx--] = array[p1--];
            }else{
                copy[copyIdx--] = array[p2--];
            }
        }
        while(p1 >= start){
            copy[copyIdx--] = array[p1--];
        }
        while(p2 >= start+length+1){
            copy[copyIdx--] = array[p2--];
        }
        return (count+left+right)%1000000007;
    } 
}

36.兩個連彪的第一個公共結點

輸入兩個鏈表,找出它們的第一個公共結點。技巧:不適用輔助Stack

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        if(pHead1 == null || pHead2 == null) return null;
        int L1 = getListLength(pHead1);
        int L2 = getListLength(pHead2);
        if(L1>L2)
            for(int i = 0 ;i<(L1-L2);i++)
                pHead1 = pHead1.next;
        else if(L2>L1)
            for(int i = 0 ;i<(L2-L1);i++)
                pHead2 = pHead2.next;
        
        while(pHead1!=null){
            if(pHead1 == pHead2)
                return pHead1;
            pHead1 = pHead1.next;
            pHead2 = pHead2.next;
        }
        return null;
    }
    public int getListLength(ListNode head){
        ListNode temp = head;
        int count = 1;
        while(temp.next != null){
            temp = temp.next;
            count++;
        }
        return count;
    }
}

劍指offer 第九天