美文网首页
leetcode-8

leetcode-8

作者: 爆炸的热水袋 | 来源:发表于2019-06-14 17:34 被阅读0次

Climbing Stairs

Just Fibonacci. Dynamic Programming's space complexity can be optimized by only store previous two value.


Sort Colors

  1. traverse one pass, counting all elements then rearrange.
  2. 3 pointers

    void swap(int &a, int &b){
        int temp = a;
        a=b;
        b=temp;
    }
public:
    void sortColors(vector<int>& nums) {
        int low = 0;
        int high = nums.size()-1;
        int mid = 0;
        while(mid<=high){
            if(nums[mid]==0){
                swap(nums[mid],nums[low]);
                low++;
                mid=low;
            }
            else if(nums[mid]==2){
                swap(nums[mid], nums[high]);
                high--;
            }
            else
            mid++;
        }
    }

When swap in place, one thing need to pay attention is that the swapped value will change to an unknown value, so mid cannot move, need to judge again.

  1. Still 3 pointers
void sortColors(int A[], int n) {
    int n0 = -1, n1 = -1, n2 = -1;
    for (int i = 0; i < n; ++i) {
        if (A[i] == 0) 
        {
            A[++n2] = 2; A[++n1] = 1; A[++n0] = 0;
        }
        else if (A[i] == 1) 
        {
            A[++n2] = 2; A[++n1] = 1;
        }
        else if (A[i] == 2) 
        {
            A[++n2] = 2;
        }
    }
}

All pointers begin at 0 and then add up.


相关文章

  • leetcode-8

    Climbing Stairs Just Fibonacci. Dynamic Programming's spa...

  • Leetcode-8 ATOI

    LeetCode这题的需求非常的怪。这次换了个做法。好像更快一些。

  • LeetCode-8 字符串转换整数

    题目:8. 字符串转换整数 难度:中等 分类:字符串 解决方案:字符串遍历 今天我们学习第8题字符串转换整数,这是...

网友评论

      本文标题:leetcode-8

      本文链接:https://www.haomeiwen.com/subject/kduufctx.html