1.29-。。。 数列

[ 80 questions / 3 ~= 27 a month..ok.. ]

1.29: remove_duplicatesI-III

  • focus on III
class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
        if (nums.empty()) return false;
        map<int, int> num2Idx;
        // j...i
        for (int i=0, j=0; i<nums.size(); ++i) {
            if (i-j>k && num2Idx[nums[j]]==j) {
                num2Idx.erase(nums[j++]);
            }    
            auto it=num2Idx.lower_bound(nums[i]-t); 
            if (it!=num2Idx.end() && abs(it->first - nums[i]) <= t) {//it->first <= nums[i]+t) {
                return true;
            }
            if (it!=num2Idx.end())
                cout<<"i: "<<i<<"; abs(it->first - nums[i])"<<it->first<<"-"<<nums[i]<<"="<<abs(it->first - nums[i])<<"?="<<t<<endl;
            num2Idx[nums[i]] = i;
            cout<<-2147483647-2147483647<<endl;
            
        }
        return false;
    }
};

blah

  • sort(it1, it2, comparator: default<, use std::greater<int>() for decending)
  • unordered_set<int> set1(nums1.begin(), nums1.end());

- 349] Intersection of Two Arrays

for look up operation

   vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
       unordered_set<int> set1(nums1.begin(), nums1.end());
       vector<int> ret;
       for (int i : nums2) 
           if (set1.erase(i)) 
               ret.push_back(i);
           
       return ret;
   }

- Longest Increasing Subsequence

  • basic dp: O(n^2)
  • w/ binary search to narrow down where to place each num[curr] O(nlogn)
    试着构建LIS array来找规律
    int lengthOfLIS(vector<int>& nums) {
        int n = nums.size();
        if (!n) return 0;
        vector<int> LIS(n, -1); // stores the actual LIS, initialize [0] to be 1
        int lasti = 0; // end pointer points to last char of LIS
        LIS[lasti] = nums[0];
        
        for (int curr=1; curr<n; ++curr) {
            if (LIS[lasti] < nums[curr]) {
                LIS[++lasti] = nums[curr];
            } else {
                //binary search to find a pos to push: s.t. leftmost pos that nums[pos] > nums[curr]
                int low = 0, high = lasti, mid = -1;
                while (low<high) {
                    mid = low + (high-low)/2;
                    if (LIS[mid] < nums[curr]) {
                        low = mid+1;
                    } else {
                        high = mid;
                    }
                }
                LIS[low] = nums[curr];
            }
        } // end for
        return lasti+1;
    }

- 26] Remove Duplicates from Sorted Array

  • don't forget corner cases
    int removeDuplicates(vector<int>& nums) {
        if (nums.size()<2) return nums.size();
        int writeri=1; // always point at next to write
        for (int readeri=1; readeri<nums.size();  ++readeri) {
            if (nums[readeri-1] != nums[readeri])
                nums[writeri++] = nums[readeri];
        }
        return writeri;
    }

- 88] Merge Sorted Array

  • 因为都要写到array1,所以只担心array2后排完的时候
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        int writei = m+n-1;
        int i=m-1, j=n-1;
        while (i>=0 && j>=0) 
            nums1[writei--] = nums1[i] > nums2[j]? nums1[i--] : nums2[j--];

        while (j>=0) nums1[writei--] = nums2[j--];
    }

- rotate array

通过不停的交换某两个数字的位置来实现旋转


Paste_Image.png
    void rotate(vector<int>& nums, int k) {
        int n = nums.size();
        if (n<2) return;
        k %= n;
       for (int step=0; step<k && starti<n-1; ++step) {
            swap(nums[starti+step], nums[n-k+starti+step]);
        }
        starti += k;
        n -= k;
    }

  • generate random num:
int randNum = rand()%(max-min + 1) + min;

- 384] Shuffle an Array

  • 洗牌算法

2.1,问题
很简单:给定一个数组,将其中的元素随机排列。比如给定数组arry=>[1,2,3,4,5]。有A5-5种结果即5!=120种结果

2.2,解决
也很简单,如果用白话来说就是:
a,选中第1个元素,将其与n个元素中的任意一个交换(包括第1个元素自己)。这时排序后的第1个元素已经确定。
b,选中第2个元素,将其与n-1个元素中作任意一个交换(包括第2个元素自己)。
c,重复上面步骤,直到剩1个元素为止。

1] Two sum I: better

    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> valToIndex;
        for (int i=0; i<nums.size(); ++i) {
            int diff = target-nums[i];
            if (valToIndex.find(diff) != valToIndex.end()) {
                return vector<int> {valToIndex[diff], i};
            }
            valToIndex[nums[i]] = i;
        }
        return vector<int>{};
    }

167] Two Sum II - Input array is sorted

use two pointers to narrow down, but also can use binary search to determine one of the bounds. e.g. find smallest num s.t. num + [0] >=target

53] Maximum Subarray

    int maxSubArray(vector<int>& nums) {
        int n = nums.size();
        int maxSum = nums[0];
        for (int i=1; i<nums.size(); ++i) {
            nums[i] = nums[i-1] < 0? nums[i] : nums[i] + nums[i-1];
            maxSum = max(maxSum, nums[i]);
        }
        return maxSum;
    }

153] Find Minimum in Rotated Sorted Array

  • don't forget when its not rotated
   int findMin(vector<int>& nums) {
        if (nums.empty()) return -1;
        if (nums[0] <= nums[nums.size()-1]) return nums[0];
        for (int starti=0, endi=nums.size()-1; starti<endi; ) {
            if (starti+1 == endi) 
                return min(nums[starti], nums[endi]);
            int midi = (endi - starti)/2 + starti;
            if (nums[starti] < nums[midi]) starti = midi;
            else endi = midi;
        }
        return -1;
    }

80] Remove Duplicates from Sorted Array II

  • how to avoid overwrite self
    int removeDuplicates(vector<int>& nums) {
        if (nums.size()<2) return nums.size();
        int writei = 2;
        for (int readi=2; readi<nums.size(); ++readi) {
            if (nums[readi] != nums[writei-2])
                nums[writei++] = nums[readi];
        }
        return writei;
    }

215] Kth Largest Element in an Array

  • ehhh don't like 1-indexed..
    int findKthLargest(vector<int>& nums, int k) { // k is 1-indexed
        if (k>nums.size() || k<1) return -1;
        priority_queue<int, std::vector<int>, std::greater<int>> minHeap(nums.begin(), nums.begin()+k);
        for (int i=k; i<nums.size(); ++i) {
            if (nums[i]>minHeap.top()) {
                minHeap.pop();
                minHeap.push(nums[i]);
            }
        }  
        return minHeap.top();
    }

81] Search in Rotated Sorted Array II

    int search(vector<int>& nums, int target) {
        if (nums.empty()) return -1;
        int l=0, r=nums.size()-1;
        for (; l<r; ) {
            int mid = l + (r-l)/2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[l] <= nums[mid]) {
                if (nums[l]<=target && target<nums[mid])
                    r = mid -1;
                else 
                    l = mid + 1;
            } else {
                if (nums[mid]<target && target<=nums[r])
                    l = mid + 1; 
                else
                    r = mid - 1;
            }
        }
        return l==r && nums[l]==target? l : -1;
    }

81] Search in Rotated Sorted Array II

设想一种情形1,1, 1,2,1,1,1,恰好左中右都是1,这时我们 ++左下标,--右下标,为什么这样我们不会将这个值跳过呢?

  • 多出了不能确定递增的情况:左=中 或 中=右
    bool search(vector<int>& nums, int target) {
        if (nums.empty()) return -1;
        int l=0, r=nums.size()-1;
        while (l<r) {
            int mid = l+(r-l)/2;
            if (nums[mid] == target) {
                return true;
            } else if (nums[l] < nums[mid]) {
                if (nums[l]<=target && target<nums[mid]) 
                    r = mid -1;
                else l = mid + 1;
            } else if (nums[mid] < nums[r]) {
                if (nums[mid]<target && target<=nums[r])
                    l = mid + 1;
                else 
                    r = mid - 1;
            } else if (nums[l] == nums[mid]) {
                ++l;
            } else {
                --r;
            }
        }
        return l==r && nums[l]==target;
    }

209] Minimum Size Subarray Sum

  • method1: O(n)
    because the left bound moves O(n) times in worst case
    int minSubArrayLen(int s, vector<int>& nums) {
        int minLen = INT_MAX;
        int acc = 0;
        for (int starti=0, endi=0; endi<nums.size(); ) {
            if (acc + nums[endi] >= s) {
                minLen = min(minLen, endi-starti+1);
                acc -= nums[starti];
                ++starti;
            } else {
                acc += nums[endi];
                ++endi;
            }
        }
        return minLen == INT_MAX? 0 : minLen;
    }
  • method2: O(nlogn) using binary search
    idea: keep a sums array that keep track of accumulated sum, search for lower bound for every qualifying upper bound
    // return biggest index i s.t. i<=uppderIndex && [i]<=upperVal
    int lowerBound(vector<int>& v, int upperIndex, int upperVal) {
        // try to find biggest num <= upperVal
        int ret = 0;
        for (int lefti=0, righti=upperIndex; lefti<=righti; ) {
            int midi = lefti + (righti-lefti)/2;
            if (v[midi] > upperVal) {
                righti = midi-1;
            } else {
                ret = max(ret, midi);
                lefti = midi + 1;
            }
        }
        return ret;
    }
    
    int minSubArrayLen(int s, vector<int>& nums) {
        if (nums.empty() || !s) return 0;
        vector<int> sums(nums.size()+1, 0);
        for (int i=1; i<sums.size(); ++i) sums[i] = sums[i-1] + nums[i-1];
        
        int minLen = INT_MAX;
        for (int i=1; i<sums.size(); ++i) {
            if (sums[i]>=s) {
                // find rightmost index j s.t. j<=i, sums[j]<=[i]-s
                int loweri = lowerBound(sums, i-1, sums[i]-s);
                // cout<<"search till ["<<i-1<<"]"<<" for sums[i]-s "<<sums[i]-s<<"--get ["<<loweri<<"] "<<sums[loweri]<<endl;
                int lefti = loweri+1; // easier to understand
                minLen = min(minLen, i-lefti+1);
            }
        }
        return minLen==INT_MAX? 0 : minLen;
    }

152] Maximum Product Subarray

写的时候分情况考虑了,如果碰到负数,正数,0?想要保证posPro>=0, negPro<=0, 越写越复杂因为初始什么值?要用上一轮值的时候?
其实每一步把可能答案先算出来,再compare和assign值。加入新值,新最大候选人:
1)最大负数 X 当前负数
2)最大正数 X 当前正数
3)当前数

    int maxProduct(vector<int>& nums) {
        if (nums.empty()) return 0;
        int posPro = nums[0], negPro = nums[0], ret = nums[0];
        for (int i=1; i<nums.size(); ++i) {
            int pro1 = posPro * nums[i];
            int pro2 = negPro * nums[i];
            posPro = max(max(pro1, pro2), nums[i]);
            negPro = min(min(pro1, pro2), nums[i]);
            ret = max(ret, posPro);
        }
        return ret;
    }
  • another method
int maxProduct(int A[], int n) { // store the result that is the max we have found so far int r = A[0]; // imax/imin stores the max/min product of // subarray that ends with the current number A[i] for (int i = 1, imax = r, imin = r; i < n; i++) { // multiplied by a negative makes big number smaller, small number bigger // so we redefine the extremums by swapping them if (A[i] < 0) swap(imax, imin); // max/min product for the current number is either the current number itself // or the max/min by the previous number times the current one imax = max(A[i], imax * A[i]); imin = min(A[i], imin * A[i]); // the newly computed max value is a candidate for our global result r = max(r, imax); } return r;}

[13] Roman to Integer

    int romanToInt(string s) {
        // Ⅰ(1)、X(10)、C(100)、M(1000)、V(5)、L(50)、D(500)
        // if smaller number (I, X, C) is left of bigger number, + bigger number - smaller number
        int ret = 0;
        for (int i=s.size()-1; i>=0; --i) {
            switch (s[i]) {
                case 'I':
                    ret += i+1<s.size() && s[i+1]!='I'? -1 : 1;
                    break;
                case 'X':
                    ret += i+1<s.size() && s[i+1]!='I' && s[i+1]!='V'  && s[i+1]!='X' ? -10 : 10;
                    break;
                case 'C':
                    ret += i+1<s.size() && (s[i+1]=='M' || s[i+1]=='D') ? -100 : 100;
                    break; 
                case 'M':
                    ret += 1000;
                    break;
                case 'V':
                    ret += 5;
                    break;
                case 'L':
                    ret += 50;
                    break;
                case 'D':
                    ret += 500;
                    break;
            }
        }
        return ret;
    }

[322] Coin Change

O(amount*n)

  • instead of init dp arr as -1, use amount+1 as the invalid state, easier to take min later
    int coinChange(vector<int>& coins, int amount) {
        if (amount<0) return -1;
        
        // minCoins[amount] gives min #coins
        vector<int> minCoins(amount+1, amount+1);
        minCoins[0] = 0;
        for (int i=1; i<amount+1; ++i) {
            for (int& coin : coins) {
                // continue if cannot break the change using this coin
                if (i-coin<0) continue;
                minCoins[i] = min(minCoins[i], minCoins[i-coin]+1);
            }
        }
        return minCoins[amount]==amount+1? -1 : minCoins[amount];
    }

quick sort

int partition(vector<int>& v, int l, int r) {
  int pivot = v[(l+r)/2];
  swap(v[l], v[(l+r)/2]);
  int i=l+1, j=r;
  while (i<=j) {
    if (v[i]<pivot) {
      ++i;
    } else if (v[j]>pivot) {
      --j;
    } else {
      if (i<j) swap(v[i++], v[j--]);
    }
  }
  swap(v[i-1], v[l]);
  return i-1;
}

void quickSort(vector<int>& v, int l, int r) {
  if (l>=r) return;
  int pivoti = partition(v, l, r);
  quickSort(v, l, pivoti-1);
  quickSort(v, pivoti+1, r);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,324评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,303评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,192评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,555评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,569评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,566评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,927评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,583评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,827评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,590评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,669评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,365评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,941评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,928评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,159评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,880评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,399评论 2 342

推荐阅读更多精彩内容