day 2 medianOfTwoSorted & longestConsecutive & twoSum

  • todo


** 3】 Two Sum **
简单的开始,第一是暴力法,第二是one pass hash 如下:

    vector twoSum(vector& nums, int target) {
        vector ret;
        unordered_map mym;
        for (int i=0; i twoSum(vector& nums, int target) {
        if ( nums.empty() ) return {};

        unordered_map mym{};
        for ( int i=0; i& ar1, vector& ar2, int k) {
        int s1 = ar1.size(), s2 = ar2.size();
        if (s1+s2s2) return findKth(ar2, ar1, k);
        else if (!s1) return ar2[k-1];
        else if (k==1) return min(ar1[0], ar2[0]);
        else {
            //for two arrs, cut out left parts whose total size is k, na+nb=k
            int na = min(k/2, s1); //why wanted to use ceil(k/2-1) before?
            int nb = k-na;
            if (ar1[na-1]==ar2[nb-1]) return ar1[na-1];
            else if (ar1[na-1]>ar2[nb-1]) {
                vector newar{ar2.begin()+nb, ar2.end()};
                return findKth(ar1, newar, k-nb);
            } else {
                vector newar{ar1.begin()+na, ar1.end()};
                return findKth(newar, ar2, k-na);
            }
        }
    }

    double findMedianSortedArrays(vector& nums1, vector& nums2) {
        int total = nums1.size()+nums2.size();
        if ( total%2 == 1 ) return findKth(nums1, nums2, total/2+1);
        else {
            // cout<

说是hard都要半小时内bugfree呢。(⊙v⊙)嗯

你可能感兴趣的:(day 2 medianOfTwoSorted & longestConsecutive & twoSum)