剑指offer刷题笔记--Num51-60

1--数组中的逆序对(51)

剑指offer刷题笔记--Num51-60_第1张图片

主要思路:

        基于归并排序,视频讲解参考:数组中的逆序对

#include 
#include 

class Solution {
public:
    int reversePairs(std::vector& nums) {
        if(nums.size() <= 1) return 0;
        return mergeSort(nums, 0, nums.size() - 1);
    }

    int mergeSort(std::vector& nums, int left, int right){
        if(left >= right) return 0;
        int mid = left + (right - left) / 2;
        int count1 = mergeSort(nums, left, mid);
        int count2 = mergeSort(nums, mid+1, right);
        int count3 = merge(nums, left, mid, mid+1, right); 

        return count1 + count2 + count3;
    }

    int merge(std::vector& nums, int l1, int r1, int l2, int r2){
        std::vector tmp;
        int count = 0;
        int i = l1, j = l2;
        while(i <= r1 && j <= r2){
            if(nums[i] > nums[j]){
                count = count + l2 - i;
                tmp.push_back(nums[j]);
                j++;
            }
            else{
                tmp.push_back(nums[i]);
                i++;
            }
        }
        while(i <= r1){
            tmp.push_back(nums[i]);
            i++;
        } 
        while(j <= r2){
            tmp.push_back(nums[j]);
            j++;
        }

        for(int i = l1, k = 0; i <= r2; i++, k++){
            nums[i] = tmp[k];
        }

        return count;
    }

};

int main(int argc, char *argv[]){
    std::vector test = {7, 5, 6, 4};
    Solution S1;
    int Res = S1.reversePairs(test);
    std::cout << Res << std::endl;

    return 0;
}

2--两个链表的第一个公共结点

剑指offer刷题笔记--Num51-60_第2张图片

 

  

  

你可能感兴趣的:(c++)