LeetCode 【数据结构与算法专栏】【数组】

数组leetcode专栏

leetcode 704 二分查找

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int low = 0;
        int high = nums.size()-1;
        while(low <= high){
            int mid = low + (high-low) / 2;
            if(nums[mid] == target) {
                return mid;
            }
            else if (nums[mid] > target) {
                high = mid - 1;
            }
            else {
                low = mid + 1;
            }
        }
        return -1;
    }
};

leetcode 27 移除元素

用erase函数

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        sort(nums.begin(), nums.end());
        for(auto iter = nums.begin(); iter != nums.end();) {
            if(*(iter) == val) {
                iter = nums.erase(iter);
            }
            else {
                iter++;
            }
        }
        return nums.size();
    }
};

暴力解法

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int size = nums.size();
        for(int i = 0; i < size; i++) {
            if(nums[i] == val) {
                for(int j = i+1; j < size; j++) {
                    nums[j-1] = nums[j];
                }
                i--;
                size--;
            }
        }
        return size;
    }
};

双指针解法

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int slow = 0;
        for(int fast = 0; fast < nums.size(); fast++) {
            if(nums[fast] != val) {
                nums[slow++] = nums[fast];
            }
        }
        return slow;
    }
};

leetcode 26 删除有序数组中的重复项(slow fast 双指针)

我们让慢指针 slow 走在后面,快指针 fast 走在前面探路,找到一个不重复的元素就赋值给 slow 并让 slow 前进一步。

这样,就保证了 nums[0…slow] 都是无重复的元素,当 fast 指针遍历完整个数组 nums 后,nums[0…slow] 就是整个数组去重之后的结果。

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.size() <= 1) {
            return nums.size();
        }
        int slow = 0;
        for(int fast = 1; fast < nums.size(); fast++) {
            if(nums[slow] != nums[fast]) {
                slow++;
            }
            nums[slow] = nums[fast];
        }
        return slow+1;
    }
};

leetcode 80 删除有序数组中的重复项 II

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if (nums.size() <= 2) {
            return nums.size();
        }
        int slow = 2;
        for (int fast = 2; fast < nums.size(); fast++) {
            if (nums[fast] != nums[slow-2]) {
                nums[slow++] = nums[fast];
            }
        }
        return slow;
    }
};
class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        return work(nums, 2);
    }
    int work(vector<int>& nums, int k) {
        if (nums.size() <= k) return nums.size();
        int slow = k;
        for (int fast = k; fast < nums.size(); fast++) {
            if (nums[slow-k] != nums[fast]) {
                nums[slow++] = nums[fast];
            }
        }
        return slow;
    }
};

leetcode 283 移动零

类似 leetcode 27 移除元素,在不改变数组中其他元素的相对位置的情况下,将0移除掉

所以快慢指针得出的思路是这样的,一开始本就需要将所有的非零元素按顺序一次放入数组,那么不如直接放置一个慢指针,在快指针检测是否非零的同时,为非零元素放置的位置做规划。

作者:北枝
链接:https://leetcode-cn.com/leetbook/read/all-about-array/x9rbug/?discussion=xMi3wS

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int slow = 0;
        for(int fast = 0; fast < nums.size(); fast++) {
            if(nums[fast] != 0) {
                nums[slow++] = nums[fast];
            }
        }
        while(slow < nums.size()) {
            nums[slow] = 0;
            slow++;
        }
        return;
    }
};

leetcode 75 颜色分类

采用三指针的方法

class Solution {
public:
    void sortColors(vector<int>& nums) {
        int pZero = 0;
        int pTwo = nums.size();
        int p = 0;
        // [0, pZero]  store 0
        // [pZero, p] store 1
        // [pTwo, nums.size()-1] store 2
        while (p < pTwo) {
            if (nums[p] == 0) {
                swap(nums[p], nums[pZero]);
                p++;
                pZero++;
            }
            else if (nums[p] == 1) {
                p++;
            }
            else {
                pTwo--;
                swap(nums[p], nums[pTwo]);
            }
        }
    }
};

采用排序算法

class Solution {
public:
    void sortColors(vector<int>& nums) {
        quickSort(nums, 0, nums.size()-1);
    }

    void quickSort(vector<int>& nums, int low, int high) {
        if (low < high) {
            int pivotpos = partition(nums, low, high);
            quickSort(nums, low, pivotpos-1);
            quickSort(nums, pivotpos+1, high);
        } 
    }

    int partition(vector<int>& nums, int low, int high) {
        int pivot = nums[low];
        while (low < high) {
            while (low < high && nums[high] >= pivot) high--;
            nums[low] = nums[high];
            while (low < high && nums[low] <= pivot) low++;
            nums[high] = nums[low];       
        }
        nums[low] = pivot;
        return low;
    }
};
class Solution {
public:
    void sortColors(vector<int>& nums) {
        MergeSort(nums, 0, nums.size()-1);
    }
    void MergeSort(vector<int>& nums, int low, int high) {
        if (low < high) {
            int mid = low + (high-low) / 2;
            MergeSort(nums, low, mid);
            MergeSort(nums, mid+1, high);
            Merge(nums, low, mid, high);
        } 
    }
    void Merge(vector<int>& nums, int low, int mid, int high) {
        vector<int> tmpVec(nums.begin(), nums.end());
        int i = low;
        int j = mid+1;
        int index = low;
        while (i <= mid && j <= high) {
            if (tmpVec[i] <= tmpVec[j]) {
                nums[index++] = tmpVec[i++];
            }
            else {
                nums[index++] = tmpVec[j++];
            }
        }
        while (i <= mid) {
            nums[index++] = tmpVec[i++];
        }
        while (j <= high) {
            nums[index++] = tmpVec[j++];
        }
    }
};
class Solution {
public:
    void sortColors(vector<int>& nums) {
        heapSort(nums, nums.size());
    }
    void heapSort(vector<int>& nums, int len) {
        buildHeap(nums, len);
        for (int i = len-1; i > 0; i--) {
            swap(nums[i], nums[0]);
            adjustHeap(nums, 0, i);
        }
    }
    void buildHeap(vector<int>& nums, int len) {
        for (int i = len/2-1; i >= 0; i--) {
            adjustHeap(nums, i, len);
        }
    }
    void adjustHeap(vector<int>& nums, int k, int len) {
        int val = nums[k];
        int i = 2 * k + 1;
        while (i < len) {
            if (i < len-1 && nums[i] < nums[i+1]) {
                i++;
            }
            if (val >= nums[i]) {
                break;
            }
            else {
                nums[k] = nums[i];
                k = i; 
            }
            i = i * 2 + 1;
        }
        nums[k] = val;
    }
};

leetcode 215 数组中的第K个最大元素

//小顶堆 priority_queue <int,vector<int>,greater<int>> q;
//大顶堆 priority_queue <int,vector<int>,less<int>> q;
class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        priority_queue<int, vector<int>, greater<int>> minHeap;
        for (int i = 0; i < nums.size(); i++) {
            if (i < k) {
                minHeap.push(nums[i]);
            }
            else {
                int minEle = minHeap.top();
                if (nums[i] > minEle) {
                    minHeap.pop();
                    minHeap.push(nums[i]);
                }
            }
        }
        return minHeap.top();
    }
};
class Solution {
public:
	int findKthLargest(vector<int>& nums, int k) {

		vector<int> result(nums.begin(), nums.begin()+k);

		// for (int i = 0; i < k; i++)
		// {
		// 	heapInsert(result, nums[i], i);
		// }

        buildHeap(result); 

		for (int i = k; i < nums.size(); i++)
		{
			if (nums[i] > result[0])
			{
				result[0] = nums[i];
				heapModify(result, 0, result.size());
                //adjustHeap(result, 0);
			}
		}
		return result[0];
	}

	void heapModify(vector<int>& vec, int index, int heapSize)
	{
		int leftChild = index * 2 + 1;
		int rightChild = index * 2 + 2;
		int tmp = index;

		while (leftChild < heapSize)
		{
			if (rightChild < heapSize && COMPARE(&vec[rightChild], &vec[leftChild]) < 0)
			{
				tmp = rightChild;
			}
			else
			{
				tmp = leftChild;
			}
			if (COMPARE(&vec[index], &vec[tmp]) < 0)
			{
				break;
			}
				
			SWAP(vec, index, tmp);
				
			index = tmp;
			leftChild = index * 2 + 1;
			rightChild = index * 2 + 2;
		}
	}

	void heapInsert(vector<int>& vec, int value, int index)
	{
		vec[index] = value;

		while (index != 0)
		{
			int dad = (index - 1) / 2;

			if (COMPARE(&vec[index], &vec[dad]) < 0)
			{
				SWAP(vec, dad, index);
				index = dad;
			}
			else
			{
				break;
			}
		}
	}

    void buildHeap(vector<int>& vec) 
    {
        for (int i = vec.size() / 2 - 1; i >= 0; i--) 
        {
            //adjustHeap(vec, i);
            heapModify(vec, i, vec.size());
        }
    }

    void adjustHeap(vector<int>& vec, int idx) 
    {
        for (int i = idx; i * 2 + 1 < vec.size();) 
        {
            int t = i * 2 + 1;
            t += (t + 1 < vec.size() && COMPARE(&vec[t + 1], &vec[t]) < 0);
            if (COMPARE(&vec[i], &vec[t]) < 0) 
                break;
            //swap(hp[i], hp[t]);
	        SWAP(vec, i, t);

            i = t;
        }
    }


	void SWAP(vector<int>& vec, int index1, int index2)
	{
		int tmp = vec[index1];
		vec[index1] = vec[index2];
		vec[index2] = tmp;
	}

	int COMPARE(const void* lhs, const void* rhs)
	{
		int lhsValue = *((int*)lhs);
		int rhsValue = *((int*)rhs);
		return lhsValue - rhsValue;
	}

};

有一些 LeetCode 题目,我们可以采用对撞指针进行求解:指针 i 和 j 分别指向数组的第一个元素和最后一个元素,然后指针 i 不断向前, 指针 j 不断递减,直到 i = j(当然具体的逻辑操作根据题目的变化而变化)。

作者:力扣 (LeetCode)
链接:https://leetcode-cn.com/leetbook/read/all-about-array/x99ak2/

leetcode 167 两数之和 II

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        int left = 0;
        int right = numbers.size()-1;
        while (left < right) {
            if (numbers[left] + numbers[right] == target) {
                return vector<int>{left+1, right+1};
            }
            else if (numbers[left] + numbers[right] < target) {
                left++;
            }
            else {
                right--;
            }
        }
        return vector<int>();
    }
};

leetcode 11 盛最多水的容器

// area = min(height[j], height[i])*(j-i)
class Solution {
public:
    int maxArea(vector<int>& height) {
        int i = 0;
        int j = height.size()-1;
        int res = 0;
        while (i < j) {
            res = height[i] > height[j] ? max(res, (j-i)*height[j--]) : max(res, (j-i)*height[i++]);
        }
        return res;
    }
};

leetcode 125 验证回文串

// tolower() toupper()
// isalpha() isalnum()
class Solution {
public:
    bool isPalindrome(string s) {
        int left = 0;
        int right = s.size()-1;
        while (left < right) {
            char l = s[left];
            char r = s[right];
            if (isalnum(l) && isalnum(r)) {
                l = tolower(l);
                r = tolower(r);
                if (l != r) {
                    return false;
                }
                left++;
                right--;
            }  
            else if (!isalnum(l)) {
                left++;
            }
            else {
                right--;
            }
        }
        return true;
    }
};

leetcode 345 反转字符串中的元音字母

//string::npos == -1
class Solution {
public:
    string reverseVowels(string s) {
        int left = 0;
        int right = s.size()-1;
        string str = "aeiouAEIOU";
        while (left < right) {
            if (str.find(s[left]) == -1) {
                left++;
                continue;
            }
            if (str.find(s[right]) == -1) {
                right--;
                continue;
            }
            swap(s[left], s[right]);
            left++;
            right--;
        }
        return s;
    }
};

leetcode 844 比较含退格的字符串

解法1:使用两个栈来存储每个字符串的元素
步骤1:当我们遍历到一个字符时,我们直接把它压入栈中
步骤2:当我们遍历到‘#’字符时,我们需要判断栈是否为空,如果为空则直接忽略掉该退格字符,否则弹出栈顶字符元素
返回结果:我们遍历完两个字符串后,只需要对比两个栈剩下的元素是否相等,即可决定返回true还是false

class Solution {
public:
    bool backspaceCompare(string s, string t) {
        stack<char> sck1;
        stack<char> sck2;
        for (int i = 0; i < s.size(); i++) {
            if (s[i] >= 'a' && s[i] <= 'z') {
                sck1.push(s[i]);
            }
            else {
                if (!sck1.empty()) {
                    sck1.pop();
                }
            }
        }
        for (int j = 0; j < t.size(); j++) {
            if (t[j] >= 'a' && t[j] <= 'z') {
                sck2.push(t[j]);
            }
            else {
                if (!sck2.empty()) {
                    sck2.pop();
                }
            }
        }
        while (!sck1.empty() && !sck2.empty()) {
            char c1 = sck1.top();
            sck1.pop();
            char c2 = sck2.top();
            sck2.pop();
            if (c1 != c2) {
                return false;
            }
        }
        if (!sck1.empty() || !sck2.empty()) {
            return false;
        }
        return true;
    }
};

解法二:采用双指针,我们可以维护两个计数器,记录下退格的个数,然后倒序遍历字符串来决定当前字符是否需要跳过。
步骤一:我们维护两个计数器skips和skipt,然后倒序遍历字符串。
步骤二:当我们遇到‘#’时,将对应的计数器 + 1;当我们遇到字符时,会有如下的判断:
1、如果退格计数器为0,那么该字符无法跳过,此时应该比对当前的字符是否相同。
2、如果退格计数器 > 0,那么该字符需要跳过,需要让遍历指针往前移一位,同时让计数器 - 1。
步骤三:如果遍历过程中,发现两个位置上的字符并不相同,或者有其中一个字符串已经遍历完,那么直接返回 false,否则继续往前遍历剩下的字符。
最后,如果两个字符串都已经遍历完,那么证明它们经过退格的操作后是相等的字符串,返回 true;时间复杂度是 O(N),空间复杂度是O(1)

class Solution {
public:
    bool backspaceCompare(string s, string t) {
        int skips = 0;
        int skipt = 0;
        for (int i = s.size()-1, j = t.size()-1; i >= 0 || j >= 0; i--, j--) {
            while (i >= 0) {
                if (s[i] == '#') {     //遇到‘#’时,将对应的计数器 + 1,接着处理下一个字符
                    skips++;
                    i--;
                }
                else if (skips > 0) {  //遇到字符时,退格计数器 > 0,那么该字符需要跳过,遍历指针往前移一位,计数器 - 1
                    skips--;
                    i--;
                }
                else {            //遇到字符时,退格计数器 == 0,该字符不能跳过,所以需要和另一个字符串对应位置字符比较
                    break;
                }
            }
            while (j >= 0) {
                if (t[j] == '#') {
                    skipt++;
                    j--;
                }
                else if (skipt > 0) {
                    skipt--;
                    j--;
                }
                else {
                    break;
                }                
            }
            if (i >= 0 && j >= 0) {    //两个对应位置上的字符并不相等,或者有其中一个字符串已经遍历完,返回false
                if (s[i] != t[j]) return false;
            }
            else if (i >= 0 || j >= 0) {
                return false;
            }
        }
        return true;  //最后如果两个字符串都已经遍历完,那么证明它们经过退格的操作后是相等的字符串,返回 true
    }
};

leetcode 977 有序数组的平方

采用双指针法

class Solution {
public:
    vector<int> sortedSquares(vector<int>& nums) {
        int left = 0;
        int right = nums.size() - 1;
        vector<int> result;
        while (left <= right) {
            int leftValue = abs(nums[left]);
            int rightValue = abs(nums[right]);
            if (leftValue < rightValue) {
                right--;
                result.push_back(pow(rightValue, 2));
            } 
            else {
                left++;
                result.push_back(pow(leftValue, 2));
            }
        }
        reverse(result.begin(), result.end());
        return result;
    }
};

leetcode 189 轮转数组(双指针)

//考虑空间复杂度为O(1)的原地算法
class Solution {
public:
    void reverse(vector<int>& nums, int left, int right) {
        while (left < right) {
            swap(nums[left], nums[right]);
            left++;
            right--;
        }
    }
    void rotate(vector<int>& nums, int k) {
        if (nums.size() <= 1) return;
        k = k % nums.size();
        reverse(nums, 0, nums.size()-1);    //区间按照左闭右闭的原则
        reverse(nums, 0, k-1);
        reverse(nums, k, nums.size()-1);
    }
};

leetcode 557 反转字符串中的单词 III(双指针)

class Solution {
public:
    string reverse(string s) {
        int i = 0;
        int j = s.size()-1;
        while (i < j) {
            swap(s[i++], s[j--]);
        }
        return s;
    }
    string reverseWords(string s) {
        istringstream iss(s);
        string st;
        string result;
        while (iss >> st) {
            string tmp = reverse(st);
            result += (tmp + " ");
        }
        result.pop_back();
        return result;
    }
};

leetcode 209 长度最小的子数组

暴力搜索解法,O(n^2)的时间复杂度

class Solution {
public:
    int minSubArrayLen(int target, vector<int>& nums) {
        int result = INT_MAX;
        int subLen = 0;
        for (int i = 0; i < nums.size(); i++) {
            int sum = 0;
            for (int j = i; j < nums.size(); j++) {
                sum += nums[j];
                if (sum >= target) {
                    subLen = j - i + 1;
                    result = subLen < result ? subLen : result;
                    break;
                }
            }
        }
        return  result == INT_MAX ? 0 : result;
    }
};

采用双指针,题目给定一个含有n个元素的数组和一个正整数target,让我们找出该数组中其和≥target的长度最小的连续子数组。
我们定义两个 指针i和j指针,将区间[i,j]看成滑动窗口,那么两个指针就分别表示滑动窗口的开始位置和结束位置,同时我们再维护一个sum变量用来存贮区间[i,j]连续数组的和。如果当前滑动窗口维护的区间和sum大于等于target,就说明当前的窗口是可行的,可行中的长度最短的滑动窗口就是答案。
作者:lin-shen-shi-jian-lu-k
链接:https://leetcode-cn.com/problems/minimum-size-subarray-sum/solution/chang-du-zui-xiao-de-zi-shu-zu-tu-jie-sh-ae80/

class Solution {
public:
    int minSubArrayLen(int target, vector<int>& nums) {
        int result = INT_MAX;
        int subLen = 0;
        int i = 0;
        int sum = 0;
        for (int j = 0; j < nums.size(); j++) {
            sum += nums[j];
            while (sum >= target) {
                subLen = j - i + 1;
                result = subLen < result ? subLen : result;
                sum -= nums[i++];
            } 
        }
        return  result == INT_MAX ? 0 : result;
    }
};

leetcode 904 水果成篮

暴力搜索解法,O(n^2)的时间复杂度

class Solution {
public:
    int totalFruit(vector<int>& fruits) {
        set<int> st(fruits.begin(), fruits.end());
        if(st.size() <= 2) {
            return fruits.size();
        }
        int fru1 = 0;
        int fru2 = 0;
        int result = INT_MIN;
        int subLen = 0;
        for (int i = 0; i < fruits.size(); i++) {
            fru1 = fruits[i];
            for (int k = i; k < fruits.size(); k++) {
                if (fruits[k] != fru1) {
                    fru2 = fruits[k];
                    break;
                }
            }
            for (int j = i; j < fruits.size(); j++) {
                if (fruits[j] == fru1 || fruits[j] == fru2) {
                    subLen = j - i + 1;
                    result = subLen > result ? subLen : result;
                }
                else {
                    break;
                }
            } 
        }
        return result;
    }
};

这道题目是典型的滑动窗口解法
窗口扩展时寻找可行解,窗口收缩时优化可行解。
右移right指针,然后发现不满足情况开始收缩左指针
左指针收缩什么情况下停止是本题的关键。根据用例第三个实例。可以看出来,需要将数字出现的次数记录下来,然后不断减少。
直到有数字出现次数被减为0 ,此时就停止收缩了。
本算法思想概述如下:
1,使用map保存窗口中数字出现的次数,因为数字不是很大。可以使用数组模拟hash。
2,右指针移动时,如果发现是一个没有出现过的数字,就把cnt++
3,如果cnt个数超过了2. 则开始收缩窗口
4,直到窗口中数字被减少到0. 此时将cnt–,退出收缩流程

// 模板
for () {
    // 将新进来的右边的数据,计算进来
    // 更新数据

    // 判断窗口数据是否不满足要求了
    while (窗口数据不满要求 && left < arrSize) {
        // 移除left数据,更新窗口数据
        left++;    
    }
    right++;
}

作者:navy-5
链接:https://leetcode-cn.com/problems/fruit-into-baskets/solution/pang-hu-xue-suan-fa-hua-dong-chuang-kou-1zypm/

class Solution {
public:
    int totalFruit(vector<int>& fruits) {
        int result = INT_MIN;
        int subLen = 0;
        int vecHash[100001] = {0};
        int i = 0;
        int cnt = 0;
        for (int j = 0; j < fruits.size(); j++) {
            if (vecHash[fruits[j]] == 0) {
                cnt++;
            }
            vecHash[fruits[j]]++;
            if (cnt <= 2) {
                subLen = j - i + 1;
                result = subLen > result ? subLen : result;
            }
            while (cnt > 2 && i < fruits.size()) {
                vecHash[fruits[i]]--;
                if (vecHash[fruits[i]] == 0) {
                    i++;
                    cnt--;
                    break;
                }
                else {
                    i++;
                }
            }
        }
        return result;
    }
};

leetcode 76 最小覆盖子串

暴力搜索解法,超时

class Solution {
public:
    string minWindow(string s, string t) {
        vector<int> hashMap(128, 0);
        int result = INT_MAX;
        int left = 0;
        int right = 0;
        for (int i = 0; i < t.size(); i++) {
            hashMap[t[i]]++;
        }
        for (int i = 0; i < s.size(); i++) {
            int subLen = 0;
            vector<int> tmpHashMap(hashMap.begin(), hashMap.end());
            for(int j = i; j < s.size(); j++) {
                tmpHashMap[s[j]]--;   
                bool flag = true; 
                for (int k = 0; k < 128; k++) {
                    if (tmpHashMap[k] > 0) {
                        flag = false;
                    }
                }
                if (flag) {
                    subLen = j - i + 1;
                    if (subLen < result) {
                        result = subLen;
                        left = i;
                        right = j;
                    }
                    break;
                }
            }
        }
        if(result == INT_MAX) return string();
        string str = s.substr(left, right-left+1);
        return str;
    }
};

滑动窗口思想

用i,j表示滑动窗口的左边界和右边界,通过改变i,j来扩展和收缩滑动窗口,可以想象成一个窗口在字符串上游走,当这个窗口包含的元素满足条件,即包含字符串T的所有元素,记录下这个滑动窗口的长度j-i+1,这些长度中的最小值就是要求的结果。

步骤一
不断增加j使滑动窗口增大,直到窗口包含了T的所有元素

步骤二
不断增加i使滑动窗口缩小,因为是要求最小字串,所以将不必要的元素排除在外,使长度减小,直到碰到一个必须包含的元素,这个时候不能再扔了,再扔就不满足条件了,记录此时滑动窗口的长度,并保存最小值

步骤三
让i再增加一个位置,这个时候滑动窗口肯定不满足条件了,那么继续从步骤一开始执行,寻找新的满足条件的滑动窗口,如此反复,直到j超出了字符串S范围。

面临的问题:

如何判断滑动窗口包含了T的所有元素?

我们用一个哈希表hashMap来表示当前滑动窗口中需要的各元素的数量,一开始滑动窗口为空,用T中各元素来初始化这个hashMap,当滑动窗口扩展或者收缩的时候,去维护这个hashMap,例如当滑动窗口包含某个元素,我们就让hashMap中这个元素的数量减1,代表所需元素减少了1个;当滑动窗口移除某个元素,就让hashMap中这个元素的数量加1。

记住一点:hashMap始终记录着当前滑动窗口下,我们还需要的元素数量,我们在改变i,j时,需同步维护hashMap。

值得注意的是,只要某个元素包含在滑动窗口中,我们就会在hashMap中存储这个元素的数量,如果某个元素存储的是负数代表这个元素是多余的。比如当hashMap等于{‘A’:-2,‘C’:1}时,表示当前滑动窗口中,我们有2个A是多余的,同时还需要1个C。这么做的目的就是为了步骤二中,排除不必要的元素,数量为负的就是不必要的元素,而数量为0表示刚刚好

回到问题中来,那么如何判断滑动窗口包含了T的所有元素?结论就是当hashMap中所有元素的数量都小于等于0时,表示当前滑动窗口不再需要任何元素

作者:Mcdull0921
链接:https://leetcode-cn.com/problems/minimum-window-substring/solution/tong-su-qie-xiang-xi-de-miao-shu-hua-dong-chuang-k/

class Solution {
public:
    string minWindow(string s, string t) {
        vector<int> hashMap(128, 0);
        int result = INT_MAX;
        int left = 0;
        int right = 0;
        int subLen = 0;
        for (int i = 0; i < t.size(); i++) { //初始化在滑动窗口范围内可行解中我们需要的元素
            hashMap[t[i]]++;
        }
        int i = 0;
        for (int j = 0; j < s.size(); j++) {    // j为滑动窗口右边界,i为左边界
            hashMap[s[j]]--;           //将右边界的值加入进来,更新数据
            while (i < j && hashMap[s[i]] < 0) { 
                hashMap[s[i]]++;      //尝试在满足要求的条件下收缩左窗口,寻找最优解
                i++;
            }
            int flag = true;   //当最左侧元素hashMap值为0时,说明不能再收缩左侧窗口了
            for (int k = 0; k < 128; k++) {   //判断现在窗口中的元素是否满足要求
                if (hashMap[k] > 0) {
                    flag = false;
                    break;
                }
            }
            if (flag) {      //满足要求的情况下,记录我们需要的最小子串
                subLen = j - i + 1;
                if (subLen < result) {
                    result = subLen;
                    left = i;
                    right = j;
                }   
                hashMap[s[i]]++;  //左边界收缩一格,滑动窗口不满足条件了
                i++;              //寻找新的满足条件的滑动窗口
            }
        }
        if(result == INT_MAX) return string();
        string str = s.substr(left, right-left+1);
        return str;
    }
};

leetcode 59 螺旋矩阵 II

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> result(n, vector<int>(n, 0));
        int loop = n / 2;              //需要画的圈的循环次数
        int mid = n / 2;               //当n为奇数时,矩阵中间的位置
        int startx = 0, starty = 0;    //定义每循环一个圈的起始位置
        int offset = 1;                // 每一圈循环,需要控制每一条边遍历的长度
        int count = 1;                 // 用来给矩阵中每一个空格赋值
        int i, j;
        while (loop--) {
            int i = startx;
            int j = starty;
            for (j = starty; j < starty + n - offset; j++) {  //四个for就是模拟转一圈
                result[startx][j] = count++;
            }
            for (i = startx; i < startx + n - offset; i++) {
                result[i][j] = count++;
            }
            for (; j > starty; j--) {
                result[i][j] = count++;
            }
            for (; i > startx; i--) {
                result[i][j] = count++; 
            }
            startx++;  //第二圈开始的时候,起始位置要各自加1, 例如:第一圈起始位置是(0, 0),第二圈起始位置是(1, 1)
            starty++;
            offset = offset + 2;  //offset 控制每一圈里每一条边遍历的长度
        }
        if (n % 2) {
            result[mid][mid] = count;
        }
        return result;
    }
};

leetcode 54 螺旋矩阵

解法一:

这里的方法不需要记录已经走过的路径,所以执行用时和内存消耗都相对较小

首先设定上下左右边界
其次向右移动到最右,此时第一行因为已经使用过了,可以将其从图中删去,体现在代码中就是重新定义上边界
判断若重新定义后,上下边界交错,表明螺旋矩阵遍历结束,跳出循环,返回答案
若上下边界不交错,则遍历还未结束,接着向右向左向上移动,操作过程与第一,二步同理
不断循环以上步骤,直到某两条边界交错,跳出循环,返回答案

作者:youlookdeliciousc
链接:https://leetcode-cn.com/problems/spiral-matrix/solution/cxiang-xi-ti-jie-by-youlookdeliciousc-3/

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int up = 0;
        int down = matrix.size() - 1;
        int left = 0;
        int right = matrix[0].size() - 1;
        vector<int> result;
        while (true) {
            for (int i = left; i <= right; i++) {
                result.push_back(matrix[up][i]);
            }
            if (++up > down) break;  //重新设定上边界,若上边界大于下边界,则遍历遍历完成,下同
            for (int i = up; i <= down; i++) {
                result.push_back(matrix[i][right]);
            }
            if (--right < left) break;
            for (int i = right; i >= left; i--) {
                result.push_back(matrix[down][i]);
            }
            if (--down < up) break;
            for (int i = down; i >= up; i--) {
                result.push_back(matrix[i][left]);
            }
            if (++left > right) break;
        }
        return result;
    }
};

解法二:
while循环只遍历环,不成环就不遍历了
while loop 一loop一层
如果一条边从头遍历到底,则下一条边遍历的起点随之变化
选择不遍历到底,可以减小横向、竖向遍历之间的影响
一轮迭代结束时,4条边的两端同时收窄 1
一轮迭代所做的事情变得很清晰:遍历一个“圈”,遍历的范围收缩为内圈
一层层向里处理,按顺时针依次遍历:上、右、下、左。
不再形成“环”了,就会剩下:一行或一列,然后单独判断
四个边界
上边界 top : 0
下边界 bottom : matrix.length - 1
左边界 left : 0
右边界 right : matrix[0].length - 1
矩阵不一定是方阵
top < bottom && left < right 是循环的条件
无法构成“环”了,就退出循环,退出时可能是这 3 种情况之一:
top == bottom && left < right —— 剩一行
top < bottom && left == right —— 剩一列
top == bottom && left == right —— 剩一项(也算 一行/列)
处理剩下的单行或单列
因为是按顺时针推入结果数组的,所以
剩下的一行,从左至右 依次推入结果数组
剩下的一列,从上至下 依次推入结果数组
代码
在遍历过程中坚持左闭右开的原则
每个元素访问一次,时间复杂度 O(mn),m、n 分别是矩阵的行数和列数
空间复杂度 O(m
n)

作者:xiao_ben_zhu
链接:https://leetcode-cn.com/problems/spiral-matrix/solution/shou-hui-tu-jie-liang-chong-bian-li-de-ce-lue-kan-/

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int up = 0;
        int down = matrix.size() - 1;
        int left = 0;
        int right = matrix[0].size() - 1;
        vector<int> result;
        while (up < down && left < right) {
            for (int i = left; i < right; i++) {
                result.push_back(matrix[up][i]);
            }
            for (int i = up; i < down; i++) {
                result.push_back(matrix[i][right]);
            }
            for (int i = right; i > left; i--) {
                result.push_back(matrix[down][i]);
            }
            for (int i = down; i > up; i--) {
                result.push_back(matrix[i][left]);
            }
            up++;
            down--;
            left++;
            right--;
        }
        if (up == down) {
            for (int i = left; i <= right; i++) {
                result.push_back(matrix[up][i]);
            }
        }
        else if (left == right) {
            for (int i = up; i <= down; i++) {
                result.push_back(matrix[i][left]);
            }
        }
        return result;
    }
};

前缀和主要适用的场景是原始数组不会被修改的情况下,频繁查询某个区间的累加和。

leetcode 303 区域和检索 - 数组不可变(前缀和技巧)

class NumArray {
public:
    NumArray(vector<int>& nums) {
        this->data = vector<int>(nums.size()+1, 0);    // data[i]记录nums[0-i-1]的记录之和,data[0] == 0
        for (int i = 1; i < data.size(); i++) {        // 计算data[1]直到data[n]的值,代表nums[0-n-1]的前缀和
            data[i] = data[i-1] + nums[i-1];
        }
    }
    
    int sumRange(int left, int right) {
        return data[right+1] - data[left];
    }
public:
    vector<int> data;
};

leetcode 304 二维区域和检索 - 矩阵不可变(前缀和技巧)

class NumMatrix {
public:
    // 定义:preSum[i][j] 记录 matrix 中子矩阵 [0, 0, i-1, j-1] 的元素和
    NumMatrix(vector<vector<int>>& matrix) {
        int m = matrix.size();
        int n = matrix[0].size();
        // 构造前缀和矩阵
        preSum = vector<vector<int>>(m+1, vector<int>(n+1, 0));
        for(int i = 1; i <= m; i++) {         // 计算每个子矩阵 [0, 0, i-1, j-1] 的元素和
            for (int j = 1; j <= n; j++) {
                preSum[i][j] = preSum[i-1][j] + preSum[i][j-1] - preSum[i-1][j-1] + matrix[i-1][j-1];
            }
        }
    }
    // 目标矩阵之和由四个相邻矩阵运算获得
    int sumRegion(int row1, int col1, int row2, int col2) {
        return preSum[row2+1][col2+1] - preSum[row2+1][col1] - preSum[row1][col2+1] + preSum[row1][col1];
    }
public:
    vector<vector<int>> preSum;
};

leetcode 560 和为 K 的子数组(前缀和技巧)

暴力解法,超时

class Solution {
public:
    //前缀和数组preSum, preSum[i]表示nums[0-i-1]的和
    int subarraySum(vector<int>& nums, int k) {
        vector<int> preSum(nums.size()+1, 0);
        for (int i = 1; i < preSum.size(); i++) {
            preSum[i] = preSum[i-1] + nums[i-1];
        }
        int cnt = 0;
        for (int i = 0; i < preSum.size(); i++) {       //i从0开始,因为preSum[0]表示目前没有累加任何元素,前缀和为0
            for (int j = i+1; j < preSum.size(); j++) {
                if (preSum[j] - preSum[i] == k) {
                    cnt++;
                }
            }
        }
        return cnt;
    }
};

算法优化

class Solution {
public:
    //前缀和数组preSum, preSum[i]表示nums[0-i-1]的和
    // int subarraySum(vector<int>& nums, int k) {
    //     vector<int> preSum(nums.size()+1, 0);
    //     for (int i = 1; i < preSum.size(); i++) {
    //         preSum[i] = preSum[i-1] + nums[i-1];
    //     }
    //     int cnt = 0;
    //     for (int i = 0; i < preSum.size(); i++) {       //i从0开始,因为preSum[0]表示目前没有累加任何元素,前缀和为0
    //         for (int j = i+1; j < preSum.size(); j++) {
    //             if (preSum[j] - k == preSum[i]) {
    //                 cnt++;
    //             }
    //         }
    //     }
    //     return cnt;
    // }
    int subarraySum(vector<int>& nums, int k) {
        unordered_map<int, int> preSum;      // 存储前缀和,和该前缀和出现的次数
        preSum.insert(pair<int,int>(0,1));
        int cnt = 0;
        int sumj = 0;
        for (int i = 0; i < nums.size(); i++) {
            sumj += nums[i];        
            int sumi = sumj - k;   // 这是我们想找的前缀和 nums[0..i]  preSum[j] - k == preSum[i]
            if (preSum.find(sumi) != preSum.end()) {
                cnt += preSum[sumi];
            }
            preSum[sumj]++;// 把前缀和 nums[0..j] 加入并记录出现次数
        }
        return cnt++;
    }
};
# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-468%20%2F%20468-ff69b4.svg) Up to date (2016-12-18), there are `447` Algorithms / `13` Database / `4` Shell / `4` Draft questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. Here is the classification of all `468` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "馃摉" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions.) ## Algorithms * [Bit Manipulation](https://github.com/kamyu104/LeetCode#bit-manipulation) * [Array](https://github.com/kamyu104/LeetCode#array) * [String](https://github.com/kamyu104/LeetCode#string) * [Linked List](https://github.com/kamyu104/LeetCode#linked-list) * [Stack](https://github.com/kamyu104/LeetCode#stack) * [Queue](https://github.com/kamyu104/LeetCode#queue) * [Heap](https://github.com/kamyu104/LeetCode#heap) * [Tree](https://github.com/kamyu104/LeetCode#tree) * [Hash Table](https://github.com/kamyu104/LeetCode#hash-table) * [Data Structure](https://github.com/kamyu104/LeetCode#data-structure) * [Math](https://github.com/kamyu104/LeetCode#math) * [Two Pointers](https://github.com/kamyu104/LeetCode#two-pointers) * [Sort](https://github.com/kamyu104/LeetCode#sort) * [Recursion](https://github.com/kamyu104/LeetCode#recursion) * [Binary Search](https://github.com/kamyu104/LeetCode#binary-search) * [Binary Search Tree](https://github.com/kamyu104/LeetCode#binary-search-tree) * [Breadth-First Search](https://github.com/kamyu104/LeetCode#breadth-first-search) * [Depth-First Search](https://github.com/kamyu104/LeetCode#depth-first-search) * [Backtracking](https://github.com/kamyu104/LeetCode#backtracking) * [Dynamic Programming](https://github.com/kamyu104/LeetCode#dynamic-programming) * [Greedy](https://github.com/kamyu104/LeetCode#greedy) * [Design](https://github.com/kamyu104/LeetCode#design) ## Database * [SQL](https://github.com/kamyu104/LeetCode#sql) ## Shell * [Shell Script](https://github.com/kamyu104/LeetCode#shell-script) ## Bit Manipulation | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 136 | [Single Number](https://leetcode.com/problems/single-number/) | [C++](./C++/single-number.cpp) [Python](./Python/single-number.py) | _O(n)_ | _O(1)_ | Easy ||| 137 | [Single Number II](https://leetcode.com/problems/single-number-ii/) | [C++](./C++/single-number-ii.cpp) [Python](./Python/single-number-ii.py) | _O(n)_ | _O(1)_ | Medium ||| 190 | [Reverse Bits](https://leetcode.com/problems/reverse-bits/) | [C++](./C++/reverse-bits.cpp) [Python](./Python/reverse-bits.py) | _O(1)_ | _O(1)_ | Easy ||| 191 |[Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/) | [C++](./C++/number-of-1-bits.cpp) [Python](./Python/number-of-1-bits.py) | _O(1)_ | _O(1)_ | Easy ||| 201 | [Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range/) | [C++](./C++/bitwise-and-of-numbers-range.cpp) [Python](./Python/bitwise-and-of-numbers-range.py) | _O(1)_ | _O(1)_ | Medium || 231 | [Power of Two](https://leetcode.com/problems/power-of-two/) | [C++](./C++/power-of-two.cpp) [Python](./Python/power-of-two.py) | _O(1)_ | _O(1)_ | Easy | LintCode | 260 | [Single Number III](https://leetcode.com/problems/single-number-iii/) | [C++](./C++/single-number-iii.cpp) [Python](./Python/single-number-iii.py) | _O(n)_ | _O(1)_ | Medium || 268| [Missing Number](https://leetcode.com/problems/missing-number/) | [C++](./C++/missing-number.cpp) [Python](./Python/missing-number.py) | _O(n)_ | _O(1)_ | Medium | LintCode || 318| [Maximum Product of Word Lengths](https://leetcode.com/problems/maximum-product-of-word-lengths/) | [C++](./C++/maximum-product-of-word-lengths.cpp) [Python](./Python/maximum-product-of-word-lengths.py) | _O(n)_ ~ _O(n^2)_ | _O(n)_ | Medium || Bit Manipulation, Counting Sort, Pruning| 342 | [Power of Four](https://leetcode.com/problems/power-of-four/) | [C++](./C++/power-of-four.cpp) [Python](./Python/power-of-four.py) | _O(1)_ | _O(1)_ | Easy | | 371 | [Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers/) | [C++](./C++/sum-of-two-integers.cpp) [Python](./Python/sum-of-two-integers.py) | _O(1)_ | _O(1)_ | Easy | LintCode | 389 | [Find the Difference](https://leetcode.com/problems/find-the-difference/) | [C++](./C++/find-the-difference.cpp) [Python](./Python/find-the-difference.py) | _O(n)_ | _O(1)_ | Easy | | 393 | [UTF-8 Validation](https://leetcode.com/problems/utf-8-validation/) | [C++](./C++/utf-8-validation.cpp) [Python](./Python/utf-8-validation.py) | _O(n)_ | _O(1)_ | Medium | | 401 | [Binary Watch](https://leetcode.com/problems/binary-watch/) | [C++](./C++/binary-watch.cpp) [Python](./Python/binary-watch.py) | _O(1)_ | _O(1)_ | Easy | | 411 | [Minimum Unique Word Abbreviation](https://leetcode.com/problems/minimum-unique-word-abbreviation/) | [C++](./C++/minimum-unique-word-abbreviation.cpp) [Python](./Python/minimum-unique-word-abbreviation.py) | _O(2^n)_ | _O(n)_ | Hard | 馃摉 | 421 | [Maximum XOR of Two Numbers in an Array](https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/) | [C++](./C++/maximum-xor-of-two-numbers-in-an-array.cpp) [Python](./Python/maximum-xor-of-two-numbers-in-an-array.py) | _O(n)_ | _O(1)_ | Medium || 461 | [Hamming Distance](https://leetcode.com/problems/hamming-distance/) | [C++](./C++/hamming-distance.cpp) [Python](./Python/hamming-distance.py) | _O(1)_ | _O(1)_ | Easy || 462 | [Minimum Moves to Equal Array Elements II](https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/) | [C++](./C++/minimum-moves-to-equal-array-elements-ii.cpp) [Python](./Python/minimum-moves-to-equal-array-elements-ii.py) | _O(n)_ on average | _O(1)_ | Medium || 477 | [Total Hamming Distance](https://leetcode.com/problems/total-hamming-distance/) | [C++](./C++/total-hamming-distance.cpp) [Python](./Python/total-hamming-distance.py) | _O(n)_ | _O(1)_ | Medium || ## Array | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 15 | [3 Sum](https://leetcode.com/problems/3sum/) | [C++](./C++/3sum.cpp) [Python](./Python/3sum.py) | _O(n^2)_ | _O(1)_ | Medium || Two Pointers 16 | [3 Sum Closest](https://leetcode.com/problems/3sum-closest/) | [C++](./C++/3sum-closest.cpp) [Python](./Python/3sum-closest.py) | _O(n^2)_ | _O(1)_ | Medium || Two Pointers 18| [4 Sum](https://leetcode.com/problems/4sum/) | [C++](./C++/4sum.cpp) [Python](./Python/4sum.py) | _O(n^3)_ | _O(1)_ | Medium || Two Pointers 26 | [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/)| [C++](./C++/remove-duplicates-from-sorted-array.cpp) [Python](./Python/remove-duplicates-from-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || Two Pointers 27 | [Remove Element](https://leetcode.com/problems/remove-element/) | [C++](./C++/remove-element.cpp) [Python](./Python/remove-element.py) | _O(n)_ | _O(1)_ | Easy || 31 | [Next Permutation](https://leetcode.com/problems/next-permutation/)| [C++](./C++/next-permutation.cpp) [Python](./Python/next-permutation.py) | _O(n)_ | _O(1)_ | Medium || Tricky 41 | [First Missing Positive](https://leetcode.com/problems/first-missing-positive/)| [C++](./C++/first-missing-positive.cpp) [Python](./Python/first-missing-positive.py) | _O(n)_ | _O(1)_ | Hard || Tricky 48 | [Rotate Image](https://leetcode.com/problems/rotate-image/) | [C++](./C++/rotate-image.cpp) [Python](./Python/rotate-image.py) | _O(n^2)_ | _O(1)_ | Medium || 54 | [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) | [C++](./C++/spiral-matrix.cpp) [Python](./Python/spiral-matrix.py) | _O(m * n)_ | _O(1)_ | Medium || 59 | [Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/) | [C++](./C++/spiral-matrix-ii.cpp) [Python](./Python/spiral-matrix-ii.py) | _O(n^2)_ | _O(1)_ | Medium || 66 | [Plus One](https://leetcode.com/problems/plus-one/) | [C++](./C++/plus-one.cpp) [Python](./Python/plus-one.py) | _O(n)_ | _O(1)_ | Easy || 73 | [Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/) | [C++](./C++/set-matrix-zeroes.cpp) [Python](./Python/set-matrix-zeroes.py) | _O(m * n)_ | _O(1)_ | Medium || 80 | [Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/)| [C++](./C++/remove-duplicates-from-sorted-array-ii.cpp) [Python](./Python/remove-duplicates-from-sorted-array-ii.py) | _O(n)_ | _O(1)_ | Medium || Two Pointers 118 | [Pascal's Triangle](https://leetcode.com/problems/pascals-triangle/)| [C++](./C++/pascals-triangle.cpp) [Python](./Python/pascals-triangle.py) | _O(n^2)_ | _O(1)_ | Easy || 119 | [Pascal's Triangle II](https://leetcode.com/problems/pascals-triangle-ii/)| [C++](./C++/pascals-triangle-ii.cpp) [Python](./Python/pascals-triangle-ii.py) | _O(n^2)_ | _O(1)_ | Easy || 121 | [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/)| [C++](./C++/best-time-to-buy-and-sell-stock.cpp) [Python](./Python/best-time-to-buy-and-sell-stock.py) | _O(n)_ | _O(1)_ | Easy || 128 | [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/)| [C++](./C++/longest-consecutive-sequence.cpp) [Python](./Python/longest-consecutive-sequence.py) | _O(n)_ | _O(n)_ | Hard || Tricky 157 | [Read N Characters Given Read4](https://leetcode.com/problems/read-n-characters-given-read4/) | [C++](./C++/read-n-characters-given-read4.cpp) [Python](./Python/read-n-characters-given-read4.py) | _O(n)_ | _O(1)_ | Easy |馃摉| 158 | [Read N Characters Given Read4 II - Call multiple times](https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/) | [C++](./C++/read-n-characters-given-read4-ii-call-multiple-times.cpp) [Python](./Python/read-n-characters-given-read4-ii-call-multiple-times.py) | _O(n)_ | _O(1)_ | Hard |馃摉| 163 | [Missing Ranges](https://leetcode.com/problems/missing-ranges/)| [C++](./C++/missing-ranges.cpp) [Python](./Python/missing-ranges.py) | _O(n)_ | _O(1)_ | Medium | 馃摉 | 169 | [Majority Element](https://leetcode.com/problems/majority-element/) | [C++](./C++/majority-element.cpp) [Python](./Python/majority-element.py) | _O(n)_ | _O(1)_ | Easy | 189 | [Rotate Array](https://leetcode.com/problems/rotate-array/) | [C++](./C++/rotate-array.cpp) [Python](./Python/rotate-array.py) | _O(n)_ | _O(1)_ | Easy || 209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | [C++](./C++/minimum-size-subarray-sum.cpp) [Python](./Python/minimum-size-subarray-sum.py) | _O(n)_ | _O(1)_ | Medium | | Binary Search 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [C++](./C++/kth-largest-element-in-an-array.cpp) [Python](./Python/kth-largest-element-in-an-array.py)| _O(n)_ ~ _O(n^2)_ | _O(1)_ | Medium | EPI| 228 | [Summary Ranges](https://leetcode.com/problems/summary-ranges/) | [C++](./C++/summary-ranges.cpp) [Python](./Python/summary-ranges.py)| _O(n)_ | _O(1)_ | Medium | | 229 | [Majority Element II](https://leetcode.com/problems/majority-element-ii/) | [C++](./C++/majority-element-ii.cpp) [Python](./Python/majority-element-ii.py) | _O(n)_ | _O(1)_ | Medium | | 238 | [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) | [C++](./C++/product-of-array-except-self.cpp) [Python](./Python/product-of-array-except-self.py) | _O(n)_ | _O(1)_ | Medium | LintCode | 240 | [Search a 2D Matrix II](https://leetcode.com/problems/search-a-2d-matrix-ii/) | [C++](./C++/search-a-2d-matrix-ii.cpp) [Python](./Python/search-a-2d-matrix-ii.py) | _O(m + n)_ | _O(1)_ | Medium | EPI, LintCode | 243| [Shortest Word Distance](https://leetcode.com/problems/shortest-word-distance/) | [C++](./C++/shortest-word-distance.cpp) [Python](./Python/shortest-word-distance.py) | _O(n)_ | _O(1)_ | Easy |馃摉|| 245| [Shortest Word Distance III](https://leetcode.com/problems/shortest-word-distance-iii/) | [C++](./C++/shortest-word-distance-iii.cpp) [Python](./Python/shortest-word-distance-iii.py) | _O(n)_ | _O(1)_ | Medium |馃摉|| 251| [Flatten 2D Vector](https://leetcode.com/problems/flatten-2d-vector/) | [C++](./C++/flatten-2d-vector.cpp) [Python](./Python/flatten-2d-vector.py) | _O(1)_ | _O(1)_ | Medium |馃摉|| 277| [Find the Celebrity](https://leetcode.com/problems/find-the-celebrity/) | [C++](./C++/find-the-celebrity.cpp) [Python](./Python/find-the-celebrity.py) | _O(n)_ | _O(1)_ | Medium |馃摉, EPI || 289| [Game of Life](https://leetcode.com/problems/game-of-life/) | [C++](./C++/game-of-life.cpp) [Python](./Python/game-of-life.py) | _O(m * n)_ | _O(1)_ | Medium ||| 293| [Flip Game](https://leetcode.com/problems/flip-game/) | [C++](./C++/flip-game.cpp) [Python](./Python/flip-game.py) | _O(n * (c+1))_ | _O(1)_ | Easy |馃摉|| 296| [Best Meeting Point](https://leetcode.com/problems/best-meeting-point/) | [C++](./C++/best-meeting-point.cpp) [Python](./Python/best-meeting-point.py) | _O(m * n)_ | _O(m + n)_ | Hard |馃摉|| 311| [Sparse Matrix Multiplication](https://leetcode.com/problems/sparse-matrix-multiplication/) | [C++](./C++/sparse-matrix-multiplication.cpp) [Python](./Python/sparse-matrix-multiplication.py) | _O(m * n * l)_ | _O(m * l)_ | Medium |馃摉|| 334| [Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/) | [C++](./C++/increasing-triplet-subsequence.cpp) [Python](./Python/increasing-triplet-subsequence.py) | _O(n)_ | _O(1)_ | Medium ||| 370| [Range Addition](https://leetcode.com/problems/range-addition/) | [C++](./C++/range-addition.cpp) [Python](./Python/range-addition.py) | _O(k + n)_ | _O(1)_ | Medium |馃摉|| 384| [Shuffle an Array](https://leetcode.com/problems/shuffle-an-array/) | [C++](./C++/shuffle-an-array.cpp) [Python](./Python/shuffle-an-array.py) | _O(n)_ | _O(n)_ | Medium | EPI || 396| [Rotate Function](https://leetcode.com/problems/rotate-function/) | [C++](./C++/rotate-function.cpp) [Python](./Python/rotate-function.py) | _O(n)_ | _O(1)_ | Easy ||| 412| [Fizz Buzz](https://leetcode.com/problems/fizz-buzz/) | [C++](./C++/fizz-buzz.cpp) [Python](./Python/fizz-buzz.py) | _O(n)_ | _O(1)_ | Easy ||| 414| [Third Maximum Number](https://leetcode.com/problems/third-maximum-number/) | [C++](./C++/third-maximum-number.cpp) [Python](./Python/third-maximum-number.py) | _O(n)_ | _O(1)_ | Easy ||| 419| [Battleships in a Board](https://leetcode.com/problems/battleships-in-a-board/) | [C++](./C++/battleships-in-a-board.cpp) [Python](./Python/battleships-in-a-board.py) | _O(m * n)_ | _O(1)_ | Medium ||| 422| [Valid Word Square](https://leetcode.com/problems/valid-word-square/) | [C++](./C++/valid-word-square.cpp) [Python](./Python/valid-word-square.py) | _O(m * n)_ | _O(1)_ | Easy |馃摉|| 442| [Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array/) | [C++](./C++/find-all-duplicates-in-an-array.cpp) [Python](./Python/find-all-duplicates-in-an-array.py) | _O(n)_ | _O(1)_ | Medium ||| 448| [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) | [C++](./C++/find-all-numbers-disappeared-in-an-array.cpp) [Python](./Python/find-all-numbers-disappeared-in-an-array.py) | _O(n)_ | _O(1)_ | Easy ||| ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 5| [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) | [C++](./C++/longest-palindromic-substring.cpp) [Python](./Python/longest-palindromic-substring.py) | _O(n)_ | _O(n)_ | Medium || `Manacher's Algorithm` 6| [ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/) | [C++](./C++/zigzag-conversion.cpp) [Python](./Python/zigzag-conversion.py) | _O(n)_ | _O(1)_ | Easy || 8| [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) | [C++](./C++/string-to-integer-atoi.cpp) [Python](./Python/string-to-integer-atoi.py) | _O(n)_ | _O(1)_ | Easy || 14| [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) | [C++](./C++/longest-common-prefix.cpp) [Python](./Python/longest-common-prefix.py) | _O(n * k)_ | _O(1)_ | Easy || 28| [Implement strStr()](https://leetcode.com/problems/implement-strstr/) | [C++](./C++/implement-strstr.cpp) [Python](./Python/implement-strstr.py) | _O(n + k)_ | _O(k)_ | Easy || `KMP Algorithm` 38| [Count and Say](https://leetcode.com/problems/count-and-say/) | [C++](./C++/count-and-say.cpp) [Python](./Python/count-and-say.py)| _O(n * 2^n)_ | _O(2^n)_ | Easy || 43| [Multiply Strings](https://leetcode.com/problems/multiply-strings/) | [C++](./C++/multiply-strings.cpp) [Python](./Python/multiply-strings.py) | _O(m * n)_ | _O(m + n)_ | Medium || 58| [Length of Last Word](https://leetcode.com/problems/length-of-last-word/) | [C++](./C++/length-of-last-word.cpp) [Python](./Python/length-of-last-word.py) | _O(n)_ | _O(1)_ | Easy || 67| [Add Binary](https://leetcode.com/problems/add-binary/) | [C++](./C++/add-binary.cpp) [Python](./Python/add-binary.py) | _O(n)_ | _O(1)_ | Easy || 68| [Text Justification](https://leetcode.com/problems/text-justification/) | [C++](./C++/text-justification.cpp) [Python](./Python/text-justification.py) | _O(n)_ | _O(1)_ | Hard || 125| [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) | [C++](./C++/valid-palindrome.cpp) [Python](./Python/valid-palindrome.py) | _O(n)_ | _O(1)_ | Easy || 151| [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/) | [C++](./C++/reverse-words-in-a-string.cpp) [Python](./Python/reverse-words-in-a-string.py) | _O(n)_ | _O(1)_ | Medium || 161| [One Edit Distance](https://leetcode.com/problems/one-edit-distance/) | [C++](./C++/one-edit-distance.cpp) [Python](./Python/one-edit-distance.py) | _O(m + n)_ | _O(1)_ | Medium |馃摉 | 165| [Compare Version Numbers](https://leetcode.com/problems/compare-version-numbers/) | [C++](./C++/compare-version-numbers.cpp) [Python](./Python/compare-version-numbers.py) | _O(n)_ | _O(1)_ | Easy || 186| [Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/) |[C++](./C++/reverse-words-in-a-string-ii.cpp) [Python](./Python/reverse-words-in-a-string-ii.py) | _O(n)_ | _O(1)_ | Medium | 馃摉 | 214| [Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/) | [C++](./C++/shortest-palindrome.cpp) [Python](./Python/shortest-palindrome.py) | _O(n)_ | _O(n)_ | Hard || `KMP Algorithm` `Manacher's Algorithm` 242| [Valid Anagram](https://leetcode.com/problems/valid-anagram/)| [C++](./C++/valid-anagram.cpp) [Python](./Python/valid-anagram.py) | _O(n)_ | _O(1)_ | Easy | LintCode | 271| [Encode and Decode Strings](https://leetcode.com/problems/encode-and-decode-strings/) | [C++](./C++/encode-and-decode-strings.cpp) [Python](./Python/encode-and-decode-strings.py) | _O(n)_ | _O(1)_ | Medium | 馃摉 | 273| [Integer to English Words](https://leetcode.com/problems/integer-to-english-words/) | [C++](./C++/integer-to-english-words.cpp) [Python](./Python/integer-to-english-words.py) | _O(logn)_ | _O(1)_ | Hard | | 306| [Addictive Number](https://leetcode.com/problems/additive-number/) | [C++](./C++/additive-number.cpp) [Python](./Python/additive-number.py) | _O(n^3)_ | _O(n)_ | Medium | | 383| [Ransom Note](https://leetcode.com/problems/ransom-note/) | [C++](./C++/ransom-note.cpp) [Python](./Python/ransom-note.py) | _O(n)_ | _O(1)_ | Easy | EPI | 405| [Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal/) | [C++](./C++/convert-a-number-to-hexadecimal.cpp) [Python](./Python/convert-a-number-to-hexadecimal.py) | _O(n)_ | _O(1)_ | Easy | | 408| [Valid Word Abbreviation](https://leetcode.com/problems/valid-word-abbreviation/) | [C++](./C++/valid-word-abbreviation.cpp) [Python](./Python/valid-word-abbreviation.py) | _O(n)_ | _O(1)_ | Easy | 馃摉 | 415| [Add Strings](https://leetcode.com/problems/add-strings/) | [C++](./C++/add-strings.cpp) [Python](./Python/add-strings.py) | _O(n)_ | _O(1)_ | Easy | | 420| [Strong Password Checker](https://leetcode.com/problems/strong-password-checker/) | [C++](./C++/strong-password-checker.cpp) [Python](./Python/strong-password-checker.py) | _O(n)_ | _O(1)_ | Hard | | 434| [Number of Segments in a String](https://leetcode.com/problems/number-of-segments-in-a-string/) | [C++](./C++/number-of-segments-in-a-string.cpp) [Python](./Python/number-of-segments-in-a-string.py) | _O(n)_ | _O(1)_ | Easy | | 459| [Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern/) | [C++](./C++/repeated-substring-pattern.cpp) [Python](./Python/repeated-substring-pattern.py) | _O(n)_ | _O(n)_ | Easy || `KMP Algorithm` | 468| [Validate IP Address](https://leetcode.com/problems/validate-ip-address/) | [C++](./C++/validate-ip-address.cpp) [Python](./Python/validate-ip-address.py) | _O(1)_ | _O(1)_ | Medium | | ## Linked List | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 2| [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | [C++](./C++/add-two-numbers.cpp) [Python](./Python/add-two-numbers.py) | _O(n)_ | _O(1)_ | Medium || 21| [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)| [C++](./C++/merge-two-sorted-lists.cpp) [Python](./Python/merge-two-sorted-lists.py) | _O(n)_ | _O(1)_ | Easy || 23| [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [C++](./C++/merge-k-sorted-lists.cpp) [Python](./Python/merge-k-sorted-lists.py) | _O(nlogk)_| _O(1)_| Hard | | Heap, Divide and Conquer 24| [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/)| [C++](./C++/swap-nodes-in-pairs.cpp) [Python](./Python/swap-nodes-in-pairs.py) | _O(n)_ | _O(1)_ | Easy || 25| [Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/)| [C++](./C++/reverse-nodes-in-k-group.cpp) [Python](./Python/reverse-nodes-in-k-group.py) | _O(n)_ | _O(1)_ | Hard || 61| [Rotate List](https://leetcode.com/problems/rotate-list/)| [C++](./C++/rotate-list.cpp) [Python](./Python/rotate-list.py) | _O(n)_ | _O(1)_ | Medium || 82| [Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)| [C++](./C++/remove-duplicates-from-sorted-list-ii.cpp) [Python](./Python/remove-duplicates-from-sorted-list-ii.py) | _O(n)_ | _O(1)_ | Medium || 83| [Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/)| [C++](./C++/remove-duplicates-from-sorted-list.cpp) [Python](./Python/remove-duplicates-from-sorted-list.py) | _O(n)_ | _O(1)_ | Easy || 92| [Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/)| [C++](./C++/reverse-linked-list-ii.cpp) [Python](./Python/reverse-linked-list-ii.py) | _O(n)_ | _O(1)_ | Medium || 138| [Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/) | [C++](./C++/copy-list-with-random-pointer.cpp) [Python](./Python/copy-list-with-random-pointer.py) | _O(n)_ | _O(1)_ | Hard || 160| [Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/)| [C++](./C++/intersection-of-two-linked-lists.cpp) [Python](./Python/intersection-of-two-linked-lists.py) | _O(m + n)_ | _O(1)_ | Easy || 203| [Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/)| [C++](./C++/remove-linked-list-elements.cpp) [Python](./Python/remove-linked-list-elements.py) | _O(n)_ | _O(1)_ | Easy || 206| [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/)| [C++](./C++/reverse-linked-list.cpp) [Python](./Python/reverse-linked-list.py) | _O(n)_ | _O(1)_ | Easy || 234| [Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/)| [C++](./C++/palindrome-linked-list.cpp) [Python](./Python/palindrome-linked-list.py) | _O(n)_ | _O(1)_ | Easy || 237| [Delete Node in a Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list/)| [C++](./C++/delete-node-in-a-linked-list.cpp) [Python](./Python/delete-node-in-a-linked-list.py) | _O(1)_ | _O(1)_ | Easy | LintCode | 328| [Odd Even Linked List](https://leetcode.com/problems/odd-even-linked-list/)| [C++](./C++/odd-even-linked-list.cpp) [Python](./Python/odd-even-linked-list.py) | _O(n)_ | _O(1)_ | Medium | | 369| [Plus One Linked List](https://leetcode.com/problems/plus-one-linked-list/)| [C++](./C++/plus-one-linked-list.cpp) [Python](./Python/plus-one-linked-list.py) | _O(n)_ | _O(1)_ | Medium | 馃摉 | Two Pointers | 445| [Add Two Numbers II](https://leetcode.com/problems/add-two-numbers-ii/)| [C++](./C++/add-two-numbers-ii.cpp) [Python](./Python/add-two-numbers-ii.py) | _O(m + n)_ | _O(m + n)_ | Medium ||| ## Stack | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 20| [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)| [C++](./C++/valid-parentheses.cpp) [Python](./Python/valid-parentheses.py) | _O(n)_ | _O(n)_ | Easy || 32| [Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses/)| [C++](./C++/longest-valid-parentheses.cpp) [Python](./Python/longest-valid-parentheses.py) | _O(n)_ | _O(1)_ | Hard || 71| [Simplify Path](https://leetcode.com/problems/simplify-path/)| [C++](./C++/simplify-path.cpp) [Python](./Python/simplify-path.py) | _O(n)_ | _O(n)_ | Medium || 84| [Largest Rectangle in Histogram](https://leetcode.com/problems/largest-rectangle-in-histogram/) | [C++](./C++/largest-rectangle-in-histogram.cpp) [Python](./Python/largest-rectangle-in-histogram.py) | _O(n)_ | _O(n)_ | Hard || Ascending Stack, DP 85| [Maximal Rectangle](https://leetcode.com/problems/maximal-rectangle/)| [C++](./C++/maximal-rectangle.cpp) [Python](./Python/maximal-rectangle.py)| _O(m * n)_ | _O(n)_ | Hard | EPI | Ascending Stack 101| [Symmetric Tree](https://leetcode.com/problems/symmetric-tree/)| [C++](./C++/symmetric-tree.cpp) [Python](./Python/symmetric-tree.py) | _O(n)_ | _O(h)_ | Easy || 150| [Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/)| [C++](./C++/evaluate-reverse-polish-notation.cpp) [Python](./Python/evaluate-reverse-polish-notation.py)| _O(n)_| _O(n)_| Medium || 155| [Min Stack](https://leetcode.com/problems/min-stack/) | [C++](./C++/min-stack.cpp) [Python](./Python/min-stack.py) | _O(n)_ | _O(1)_ | Easy || 173| [Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/) | [C++](./C++/binary-search-tree-iterator.cpp) [Python](./Python/binary-search-tree-iterator.py) | _O(1)_| _O(h)_| Medium || 224| [Basic Calculator](https://leetcode.com/problems/basic-calculator/) | [C++](./C++/basic-calculator.cpp) [Python](./Python/basic-calculator.py) | _O(n)_| _O(n)_| Hard || 227| [Basic Calculator II](https://leetcode.com/problems/basic-calculator-ii/) | [C++](./C++/basic-calculator-ii.cpp) [Python](./Python/basic-calculator-ii.py) | _O(n)_| _O(n)_| Medium || 232| [Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/) | [C++](./C++/implement-queue-using-stacks.cpp) [Python](./Python/implement-queue-using-stacks.py) | _O(1), amortized_| _O(n)_| Easy | EPI, LintCode | 255| [Verify Preorder Sequence in Binary Search Tree](https://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree/) | [C++](./C++/verify-preorder-sequence-in-binary-search-tree.cpp) [Python](./Python/verify-preorder-sequence-in-binary-search-tree.py) | _O(n)_| _O(1)_| Medium |馃摉|| 272| [Closest Binary Search Tree Value II](https://leetcode.com/problems/closest-binary-search-tree-value-ii/) | [C++](./C++/closest-binary-search-tree-value-ii.cpp) [Python](./Python/closest-binary-search-tree-value-ii.py) | _O(h + k)_| _O(h)_| Hard |馃摉|| 331| [Verify Preorder Serialization of a Binary Tree](https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/) | [C++](./C++/verify-preorder-serialization-of-a-binary-tree.cpp) [Python](./Python/verify-preorder-serialization-of-a-binary-tree.py) | _O(n)_| _O(1)_| Medium ||| 341| [Flatten Nested List Iterator](https://leetcode.com/problems/flatten-nested-list-iterator/)| [C++](./C++/flatten-nested-list-iterator.cpp) [Python](./Python/flatten-nested-list-iterator.py) | _O(n)_ | _O(h)_ | Medium |馃摉| Iterator | 385| [Mini Parser](https://leetcode.com/problems/mini-parser/)| [C++](./C++/mini-parser.cpp) [Python](./Python/mini-parser.py) | _O(n)_ | _O(h)_ | Medium ||| 394| [Decode String](https://leetcode.com/problems/decode-string/)| [C++](./C++/decode-string.cpp) [Python](./Python/decode-string.py) | _O(n)_ | _O(h)_ | Medium ||| 439| [Ternary Expression Parser](https://leetcode.com/problems/ternary-expression-parser/) | [C++](./C++/ternary-expression-parser.cpp) [Python](./Python/ternary-expression-parser.py) | _O(n)_ | _O(1)_ | Medium |馃摉| 456| [132 Pattern](https://leetcode.com/problems/132-pattern/) | [C++](./C++/132-pattern.cpp) [Python](./Python/132-pattern.py) | _O(n)_ | _O(n)_ | Medium || ## Queue | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 239| [Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/)| [C++](./C++/sliding-window-maximum.cpp) [Python](./Python/sliding-window-maximum.py) | _O(n)_ | _O(k)_ | Hard | EPI, LintCode | 281| [Zigzag Iterator](https://leetcode.com/problems/zigzag-iterator/)| [C++](./C++/zigzag-iterator.cpp) [Python](./Python/zigzag-iterator.py) | _O(n)_ | _O(k)_ | Medium |馃摉|| 346| [Moving Average from Data Stream](https://leetcode.com/problems/moving-average-from-data-stream/)| [C++](./C++/moving-average-from-data-stream.cpp) [Python](./Python/moving-average-from-data-stream.py) | _O(1)_ | _O(w)_ | Easy |馃摉|| ## Heap | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 264| [Ugly Number II](https://leetcode.com/problems/ugly-number-ii/) | [C++](./C++/ugly-number-ii.cpp) [Python](./Python/ugly-number-ii.py) | _O(n)_ | _O(1)_ | Medium | CTCI, LintCode | BST, Heap | 295| [Find Median from Data Stream](https://leetcode.com/problems/find-median-from-data-stream/) | [C++](./C++/find-median-from-data-stream.cpp) [Python](./Python/find-median-from-data-stream.py) | _O(nlogn)_ | _O(n)_ | Hard | EPI, LintCode | BST, Heap | 313| [Super Ugly Number](https://leetcode.com/problems/super-ugly-number/) | [C++](./C++/super-ugly-number.cpp) [Python](./Python/super-ugly-number.py) | _O(n * k)_ | _O(n + k)_ | Medium || BST, Heap | 358| [Rearrange String k Distance Apart](https://leetcode.com/problems/rearrange-string-k-distance-apart/)| [C++](./C++/rearrange-string-k-distance-apart.cpp) [Python](./Python/rearrange-string-k-distance-apart.py) | _O(n)_ | _O(n)_ | Hard |馃摉| Greedy, Heap | 373 | [Find K Pairs with Smallest Sums](https://leetcode.com/problems/find-k-pairs-with-smallest-sums/) | [C++](./C++/find-k-pairs-with-smallest-sums.cpp) [Python](./Python/find-k-pairs-with-smallest-sums.py) | _O(k * log(min(n, m, k)))_ | _O(min(n, m, k))_ | Medium ||| 378 | [Kth Smallest Element in a Sorted Matrix](https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/) | [C++](./C++/kth-smallest-element-in-a-sorted-matrix.cpp) [Python](./Python/kth-smallest-element-in-a-sorted-matrix.py) | _O(k * log(min(n, m, k)))_ | _O(min(n, m, k))_ | Medium | LintCode || 407 | [Trapping Rain Water II](https://leetcode.com/problems/trapping-rain-water-ii/) | [C++](./C++/trapping-rain-water-ii.cpp) [Python](./Python/trapping-rain-water-ii.py) | _O(m * n * (logm + logn))_ | _O(m * n)_ | Hard | LintCode || ## Tree | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 94 | [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) | [C++](./C++/binary-tree-inorder-traversal.cpp) [Python](./Python/binary-tree-inorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` | 99 | [Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree/) | [C++](./C++/recover-binary-search-tree.cpp) [Python](./Python/recover-binary-search-tree.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` 144 | [Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/) | [C++](./C++/binary-tree-preorder-traversal.cpp) [Python](./Python/binary-tree-preorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` 145 | [Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/) | [C++](./C++/binary-tree-postorder-traversal.cpp) [Python](./Python/binary-tree-postorder-traversal.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` 208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [C++](./C++/implement-trie-prefix-tree.cpp) [Python](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium || Trie 211 | [Add and Search Word - Data structure design](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | [C++](./C++/add-and-search-word-data-structure-design.cpp) [Python](./Python/add-and-search-word-data-structure-design.py) | _O(min(n, h))_ | _O(min(n, h))_ | Medium || Trie, DFS 226| [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/) | [C++](./C++/invert-binary-tree.cpp) [Python](./Python/invert-binary-tree.py) | _O(n)_ | _O(h)_, _O(w)_ | Easy || 297 | [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/) | [C++](./C++/serialize-and-deserialize-binary-tree.cpp) [Python](./Python/serialize-and-deserialize-binary-tree.py) | _O(n)_ | _O(h)_ | Hard | LintCode | DFS 307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [C++](./C++/range-sum-query-mutable.cpp) [Python](./Python/range-sum-query-mutable.py) | ctor: _O(n)_, update: _O(logn)_, query: _O(logn)_ | _O(n)_ | Medium | LintCode | DFS, Segment Tree, BIT 308 | [Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable/) | [C++](./C++/range-sum-query-2d-mutable.cpp) [Python](./Python/range-sum-query-2d-mutable.py) | ctor: _O(m * n)_, update: _O(logm + logn)_, query: _O(logm + logn)_ | _O(m * n)_ | Hard | 馃摉 | DFS, Segment Tree, BIT 315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/)| [C++](./C++/count-of-smaller-numbers-after-self.cpp) [Python](./Python/count-of-smaller-numbers-after-self.py)| _O(nlogn)_ | _O(n)_ | Hard | LintCode | BST, BIT, Divide and Conquer | ## Hash Table | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 1| [Two Sum](https://leetcode.com/problems/two-sum/) | [C++](./C++/two-sum.cpp) [Python](./Python/two-sum.py) | _O(n)_ | _O(n)_ | Easy || 3| [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | [C++](./C++/longest-substring-without-repeating-characters.cpp) [Python](./Python/longest-substring-without-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || 30| [Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/) | [C++](./C++/substring-with-concatenation-of-all-words.cpp) [Python](./Python/substring-with-concatenation-of-all-words.py) | _O(m * n * k)_ | _O(n * k)_ | Hard || 36| [Valid Sudoku](https://leetcode.com/problems/valid-sudoku/) | [C++](./C++/valid-sudoku.cpp) [Python](./Python/valid-sudoku.py) | _O(9^2)_ | _O(9)_ | Easy || 49| [Group Anagrams](https://leetcode.com/problems/anagrams/) | [C++](./C++/anagrams.cpp) [Python](./Python/anagrams.py) | _O(n * glogg)_ | _O(n)_ | Medium || 76| [Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/) | [C++](./C++/minimum-window-substring.cpp) [Python](./Python/minimum-window-substring.py) | _O(n)_ | _O(k)_ | Hard || 149| [Max Points on a Line](https://leetcode.com/problems/max-points-on-a-line/) | [C++](./C++/max-points-on-a-line.cpp) [Python](./Python/max-points-on-a-line.py) | _O(n^2)_ | _O(n)_ | Hard || 159| [Longest Substring with At Most Two Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/)| [C++](./C++/longest-substring-with-at-most-two-distinct-characters.cpp) [Python](./Python/longest-substring-with-at-most-two-distinct-characters.py) | _O(n)_ | _O(1)_ | Hard |馃摉| 170| [Two Sum III - Data structure design](https://leetcode.com/problems/two-sum-iii-data-structure-design/) | [C++](./C++/two-sum-iii-data-structure-design.cpp) [Python](./Python/two-sum-iii-data-structure-design.py) | _O(n)_ | _O(n)_ | Easy | 馃摉 | 187| [Repeated DNA Sequences](https://leetcode.com/problems/repeated-dna-sequences/) | [Python](./Python/repeated-dna-sequences.py) | _O(n)_ | _O(n)_ | Medium || 202| [Happy Number](https://leetcode.com/problems/happy-number/) | [C++](./C++/happy-number.cpp) [Python](./Python/happy-number.py) | _O(k)_ | _O(k)_ | Easy || 204| [Count Primes](https://leetcode.com/problems/count-primes/) | [C++](./C++/count-primes.cpp) [Python](./Python/count-primes.py) | _O(n)_ | _O(n)_ | Easy || 205| [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) | [C++](./C++/isomorphic-strings.cpp) [Python](./Python/isomorphic-strings.py) | _O(n)_ | _O(1)_ | Easy || 217| [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) | [C++](./C++/contains-duplicate.cpp) [Python](./Python/contains-duplicate.py) | _O(n)_ | _O(n)_ | Easy || 219| [Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/) | [C++](./C++/contains-duplicate-ii.cpp) [Python](./Python/contains-duplicate-ii.py) | _O(n)_ | _O(n)_ | Easy || 244| [Shortest Word Distance II](https://leetcode.com/problems/shortest-word-distance-ii/) | [C++](./C++/shortest-word-distance-ii.cpp) [Python](./Python/shortest-word-distance-ii.py) | ctor: _O(n)_, lookup: _O(a + b)_ | _O(n)_ | Medium |馃摉|| 246| [Strobogrammatic Number](https://leetcode.com/problems/strobogrammatic-number/) | [C++](./C++/strobogrammatic-number.cpp) [Python](./Python/strobogrammatic-number.py) | _O(n)_ | _O(1)_ | Easy |馃摉|| 249| [Group Shifted Strings](https://leetcode.com/problems/group-shifted-strings/) | [C++](./C++/group-shifted-strings.cpp) [Python](./Python/group-shifted-strings.py) | _O(nlogn)_ | _O(n)_ | Easy |馃摉|| 266| [Palindrome Permutation](https://leetcode.com/problems/palindrome-permutation/) | [C++](./C++/palindrome-permutation.cpp) [Python](./Python/palindrome-permutation.py) | _O(n)_ | _O(1)_ | Easy |馃摉|| 288| [Unique Word Abbreviation](https://leetcode.com/problems/unique-word-abbreviation/) | [C++](./C++/unique-word-abbreviation.cpp) [Python](./Python/unique-word-abbreviation.py) | ctor: _O(n)_, lookup: _O(1)_ | _O(k)_ | Easy |馃摉|| 290| [Word Pattern](https://leetcode.com/problems/word-pattern/) | [C++](./C++/word-pattern.cpp) [Python](./Python/word-pattern.py) | _O(n)_ | _O(c)_ | Easy | variant of [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) || 299| [Bulls and Cows](https://leetcode.com/problems/bulls-and-cows/) | [C++](./C++/bulls-and-cows.cpp) [Python](./Python/bulls-and-cows.py) | _O(n)_ | _O(1)_ | Easy ||| 305| [Number of Islands II](https://leetcode.com/problems/number-of-islands-ii/) | [C++](./C++/number-of-islands-ii.cpp) [Python](./Python/number-of-islands-ii.py) | _O(k)_ | _O(k)_| Hard | LintCode, 馃摉 | Union Find 314| [Binary Tree Vertical Order Traversal](https://leetcode.com/problems/binary-tree-vertical-order-traversal/) | [C++](./C++/binary-tree-vertical-order-traversal.cpp) [Python](./Python/binary-tree-vertical-order-traversal.py) | _O(n)_ | _O(n)_| Medium | 馃摉 | BFS 323| [Number of Connected Components in an Undirected Graph](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/) | [C++](./C++/number-of-connected-components-in-an-undirected-graph.cpp) [Python](./Python/number-of-connected-components-in-an-undirected-graph.py) | _O(n)_ | _O(n)_| Medium | 馃摉 | Union Find 325| [Maximum Size Subarray Sum Equals k](https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/) | [C++](./C++/maximum-size-subarray-sum-equals-k.cpp) [Python](./Python/maximum-size-subarray-sum-equals-k.py) | _O(n)_ | _O(n)_| Medium | 馃摉 | 336| [Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/) | [C++](./C++/palindrome-pairs.cpp) [Python](./Python/palindrome-pairs.py) | _O(n * k^2)_ | _O(n * k)_ | Hard | | | 340| [Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/)| [C++](./C++/longest-substring-with-at-most-k-distinct-characters.cpp) [Python](./Python/longest-substring-with-at-most-k-distinct-characters.py) | _O(n)_ | _O(1)_ | Hard |馃摉| 356| [Line Reflection](https://leetcode.com/problems/line-reflection/) | [C++](./C++/line-reflection.cpp) [Python](./Python/line-reflection.py) | _O(n)_| _O(n)_| Medium |馃摉| Hash, Two Pointers | 387| [First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/) | [C++](./C++/first-unique-character-in-a-string.cpp) [Python](./Python/first-unique-character-in-a-string.py) | _O(n)_| _O(n)_| Easy ||| 388| [Longest Absolute File Path](https://leetcode.com/problems/longest-absolute-file-path/) | [C++](./C++/longest-absolute-file-path.cpp) [Python](./Python/longest-absolute-file-path.py) | _O(n)_| _O(d)_| Medium || Stack | 409| [Longest Palindrome](https://leetcode.com/problems/longest-palindrome/) | [C++](./C++/longest-palindrome.cpp) [Python](./Python/longest-palindrome.py) | _O(n)_| _O(1)_| Easy ||| 424| [Longest Repeating Character Replacement](https://leetcode.com/problems/longest-repeating-character-replacement/) | [C++](./C++/longest-repeating-character-replacement.cpp) [Python](./Python/longest-repeating-character-replacement.py) | _O(n)_| _O(1)_| Medium ||| 438| [Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/) | [C++](./C++/find-all-anagrams-in-a-string.cpp) [Python](./Python/find-all-anagrams-in-a-string.py) | _O(n)_ | _O(1)_ | Easy || 447| [Number of Boomerangs](https://leetcode.com/problems/number-of-boomerangs/) | [C++](./C++/number-of-boomerangs.cpp) [Python](./Python/number-of-boomerangs.py) | _O(n^2)_ | _O(n)_ | Easy || 454| [4Sum II](https://leetcode.com/problems/4sum-ii/) | [C++](./C++/4sum-ii.cpp) [Python](./Python/4sum-ii.py) | _O(n^2)_ | _O(n^2)_ | Medium || 473| [Matchsticks to Square](https://leetcode.com/problems/matchsticks-to-square/) | [C++](./C++/matchsticks-to-square.cpp) [Python](./Python/matchsticks-to-square.py) | _O(n * s * 2^n)_ | _O(n * (2^n + s))_ | Medium || ## Data Structure | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 146| [LRU Cache](https://leetcode.com/problems/lru-cache/) | [C++](./C++/lru-cache.cpp) [Python](./Python/lru-cache.py) | _O(1)_ | _O(k)_ | Hard || 225| [Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/) | [C++](./C++/implement-stack-using-queues.cpp) [Python](./Python/implement-stack-using-queues.py) | push: _O(n)_, pop: _O(1)_, top: _O(1)_ | _O(n)_ | Easy || ## Math | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 7| [Reverse Integer](https://leetcode.com/problems/reverse-integer/) | [C++](./C++/reverse-integer.cpp) [Python](./Python/reverse-integer.py) | _O(1)_ | _O(1)_ | Easy || 9| [Palindrome Number](https://leetcode.com/problems/palindrome-number/) | [C++](./C++/palindrome-number.cpp) [Python](./Python/palindrome-number.py) | _O(1)_ | _O(1)_ | Easy || 12| [Integer to Roman](https://leetcode.com/problems/integer-to-roman/) | [C++](./C++/integer-to-roman.cpp) [Python](./Python/integer-to-roman.py) | _O(n)_ | _O(1)_ | Medium || 13| [Roman to Integer](https://leetcode.com/problems/roman-to-integer/) | [C++](./C++/roman-to-integer.cpp) [Python](./Python/roman-to-integer.py) | _O(n)_ | _O(1)_ | Easy || 29| [Divide Two Integers](https://leetcode.com/problems/divide-two-integers/) | [C++](./C++/divide-two-integers.cpp) [Python](./Python/divide-two-integers.py) | _O(1)_ | _O(1)_ | Medium || 50| [Pow(x, n)](https://leetcode.com/problems/powx-n/) | [C++](./C++/powx-n.cpp) [Python](./Python/powx-n.py) | _O(1)_ | _O(1)_ | Medium || 60| [Permutation Sequence](https://leetcode.com/problems/permutation-sequence/) | [C++](./C++/permutation-sequence.cpp) [Python](./Python/permutation-sequence.py) | _O(n^2)_ | _O(n)_ | Medium || `Cantor Ordering` 65| [Valid Number](https://leetcode.com/problems/valid-number/) | [C++](./C++/valid-number.cpp) [Python](./Python/valid-number.py) | _O(n)_ | _O(1)_ | Hard || `Automata` 89| [Gray Code](https://leetcode.com/problems/gray-code/) | [C++](./C++/gray-code.cpp) [Python](./Python/gray-code.py) | _O(2^n)_ | _O(1)_ | Medium || 166| [Fraction to Recurring Decimal](https://leetcode.com/problems/fraction-to-recurring-decimal/) | [C++](./C++/fraction-to-recurring-decimal.cpp) [Python](./Python/fraction-to-recurring-decimal.py) | _O(logn)_ | _O(1)_ | Medium || 168| [Excel Sheet Column Title](https://leetcode.com/problems/excel-sheet-column-title/) | [C++](./C++/excel-sheet-column-title.cpp) [Python](./Python/excel-sheet-column-title.py) | _O(logn)_ | _O(1)_ | Easy || 171| [Excel Sheet Column Number](https://leetcode.com/problems/excel-sheet-column-number/) | [C++](./C++/excel-sheet-column-number.cpp) [Python](./Python/excel-sheet-column-number.py) | _O(n)_ | _O(1)_ | Easy || 172| [Factorial Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes/) | [C++](./C++/factorial-trailing-zeroes.cpp) [Python](./Python/factorial-trailing-zeroes.py) | _O(1)_ | _O(1)_ | Easy || 223| [Rectangle Area](https://leetcode.com/problems/rectangle-area/) | [C++](./C++/rectangle-area.cpp) [Python](./Python/rectangle-area.py) | _O(1)_ | _O(1)_ | Easy || 233| [Number of Digit One](https://leetcode.com/problems/number-of-digit-one/) | [C++](./C++/number-of-digit-one.cpp) [Python](./Python/number-of-digit-one.py) | _O(1)_ | _O(1)_ | Hard | CTCI, LintCode| 248| [Strobogrammatic Number III](https://leetcode.com/problems/strobogrammatic-number-iii/) | [C++](./C++/strobogrammatic-number-iii.cpp) [Python](./Python/strobogrammatic-number-iii.py) | _O(5^(n/2))_ | _O(n)_ | Hard |馃摉|| 258| [Add Digits](https://leetcode.com/problems/add-digits/) | [C++](./C++/add-digits.cpp) [Python](./Python/add-digits.py) | _O(1)_ | _O(1)_ | Easy ||| 263| [Ugly Number](https://leetcode.com/problems/ugly-number/) | [C++](./C++/ugly-number.cpp) [Python](./Python/ugly-number.py) | _O(1)_ | _O(1)_ | Easy ||| 292| [Nim Game](https://leetcode.com/problems/nim-game/) | [C++](./C++/nim-game.cpp) [Python](./Python/nim-game.py) | _O(1)_ | _O(1)_ | Easy | LintCode || 319 | [Bulb Switcher](https://leetcode.com/problems/bulb-switcher/) | [C++](./C++/bulb-switcher.cpp) [Python](./Python/bulb-switcher.py) | _O(1)_ | _O(1)_ | Medium ||| 326 | [Power of Three](https://leetcode.com/problems/power-of-three/) | [C++](./C++/power-of-three.cpp) [Python](./Python/power-of-three.py) | _O(1)_ | _O(1)_ | Easy ||| 335 | [Self Crossing](https://leetcode.com/problems/self-crossing/) | [C++](./C++/self-crossing.cpp) [Python](./Python/self-crossing.py) | _O(n)_ | _O(1)_ | Hard ||| 338 | [Counting Bits](https://leetcode.com/problems/counting-bits/) | [C++](./C++/counting-bits.cpp) [Python](./Python/counting-bits.py) | _O(n)_ | _O(n)_ | Medium ||| 343 | [Integer Break](https://leetcode.com/problems/integer-break/) | [C++](./C++/integer-break.cpp) [Python](./Python/integer-break.py) | _O(logn)_ | _O(1)_ | Medium || Tricky, DP | 365 | [Water and Jug Problem](https://leetcode.com/problems/water-and-jug-problem/) | [C++](./C++/water-and-jug-problem.cpp) [Python](./Python/water-and-jug-problem.py) | _O(logn)_ | _O(1)_ | Medium || Euclidean Algorithm | 372 | [Super Pow](https://leetcode.com/problems/super-pow/) | [C++](./C++/super-pow.cpp) [Python](./Python/super-pow.py) | _O(n)_ | _O(1)_ | Medium ||| 382 | [Linked List Random Node](https://leetcode.com/problems/linked-list-random-node/) | [C++](./C++/linked-list-random-node.cpp) [Python](./Python/linked-list-random-node.py) | _O(n)_ | _O(1)_ | Medium || `Reservoir Sampling` | 386 | [Lexicographical Numbers](https://leetcode.com/problems/lexicographical-numbers/) | [C++](./C++/lexicographical-numbers.cpp) [Python](./Python/lexicographical-numbers.py) | _O(n)_ | _O(1)_ | Medium ||| 390 | [Elimination Game](https://leetcode.com/problems/elimination-game/) | [C++](./C++/elimination-game.cpp) [Python](./Python/elimination-game.py) | _O(logn)_ | _O(1)_ | Medium || 391 | [Perfect Rectangle](https://leetcode.com/problems/perfect-rectangle/) | [C++](./C++/perfect-rectangle.cpp) [Python](./Python/perfect-rectangle.py) | _O(n)_ | _O(n)_ | Hard | | 398 | [Random Pick Index](https://leetcode.com/problems/random-pick-index/) | [C++](./C++/random-pick-index.cpp) [Python](./Python/random-pick-index.py) | _O(n)_ | _O(1)_ | Medium || `Reservoir Sampling` | 400 | [Nth Digit](https://leetcode.com/problems/nth-digit/) | [C++](./C++/nth-digit.cpp) [Python](./Python/nth-digit.py) | _O(logn)_ | _O(1)_ | Easy ||| 413 | [Arithmetic Slices](https://leetcode.com/problems/arithmetic-slices/) | [C++](./C++/arithmetic-slices.cpp) [Python](./Python/arithmetic-slices.py) | _O(n)_ | _O(1)_ | Medium ||| 423 | [Reconstruct Original Digits from English](https://leetcode.com/problems/reconstruct-original-digits-from-english/) | [C++](./C++/reconstruct-original-digits-from-english.cpp) [Python](./Python/reconstruct-original-digits-from-english.py) | _O(n)_ | _O(1)_ | Medium | [GCJ2016 - Round 1B](https://code.google.com/codejam/contest/11254486/dashboard#s=p0)|| 441 | [Arranging Coins](https://leetcode.com/problems/arranging-coins/) | [C++](./C++/arranging-coins.cpp) [Python](./Python/arranging-coins.py) | _O(nlogn)_ | _O(1)_ | Easy || Binary Search| 453 | [Minimum Moves to Equal Array Elements](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/) | [C++](./C++/minimum-number-of-arrows-to-burst-balloons.cpp) [Python](./Python/minimum-number-of-arrows-to-burst-balloons.py) | _O(n)_ | _O(1)_ | Easy ||| 458 | [Poor Pigs](https://leetcode.com/problems/poor-pigs/) | [C++](./C++/poor-pigs.cpp) [Python](./Python/poor-pigs.py) | _O(n)_ | _O(1)_ | Easy ||| 469 | [Convex Polygon](https://leetcode.com/problems/convex-polygon/) | [C++](./C++/convex-polygon.cpp) [Python](./Python/convex-polygon.py) | _O(n)_ | _O(1)_ | Medium |馃摉|| ## Sort | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 56| [Merge Intervals](https://leetcode.com/problems/merge-intervals/)| [C++](./C++/merge-intervals.cpp) [Python](./Python/merge-intervals.py) | _O(nlogn)_ | _O(1)_ | Hard || 57| [Insert Interval](https://leetcode.com/problems/insert-interval/)| [C++](./C++/insert-interval.cpp) [Python](./Python/insert-interval.py) | _O(n)_ | _O(1)_ | Hard || 75| [Sort Colors](https://leetcode.com/problems/sort-colors/) | [C++](./C++/sort-colors.cpp) [Python](./Python/sort-colors.py) | _O(n)_ | _O(1)_ | Medium || Tri Partition 88| [Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/)| [C++](./C++/merge-sorted-array.cpp) [Python](./Python/merge-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || 147| [Insertion Sort List](https://leetcode.com/problems/insertion-sort-list/)|[C++](./C++/insertion-sort-list.cpp) [Python](./Python/insertion-sort-list.py) | _O(n^2)_ | _O(1)_ | Medium || 148| [Sort List](https://leetcode.com/problems/sort-list/) | [C++](./C++/sort-list.cpp) [Python](./Python/sort-list.py) | _O(nlogn)_ | _O(logn)_ | Medium || 164| [Maximum Gap](https://leetcode.com/problems/maximum-gap/) | [C++](./C++/maximum-gap.cpp) [Python](./Python/maximum-gap.py)| _O(n)_ | _O(n)_ | Hard || Tricky 179| [Largest Number](https://leetcode.com/problems/largest-number/) | [C++](./C++/largest-number.cpp) [Python](./Python/largest-number.py) | _O(nlogn)_ | _O(1)_ | Medium || 218| [The Skyline Problem](https://leetcode.com/problems/the-skyline-problem/) | [C++](./C++/the-skyline-problem.cpp) [Python](./Python/the-skyline-problem.py) | _O(nlogn)_ | _O(n)_ | Hard || Sort, BST| 252| [Meeting Rooms](https://leetcode.com/problems/meeting-rooms/) | [C++](./C++/meeting-rooms.cpp) [Python](./Python/meeting-rooms.py) | _O(nlogn)_ | _O(n)_ | Easy |馃摉| | 253| [Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii/) | [C++](./C++/meeting-rooms-ii.cpp) [Python](./Python/meeting-rooms-ii.py) | _O(nlogn)_ | _O(n)_ | Medium |馃摉| | 274| [H-Index](https://leetcode.com/problems/h-index/) | [C++](./C++/h-index.cpp) [Python](./Python/h-index.py) | _O(n)_ | _O(n)_ | Medium || Counting Sort | 280| [Wiggle Sort](https://leetcode.com/problems/wiggle-sort/) | [C++](./C++/wiggle-sort.cpp) [Python](./Python/wiggle-sort.py) | _O(n)_ | _O(1)_ | Medium |馃摉| | 324| [Wiggle Sort II](https://leetcode.com/problems/wiggle-sort-ii/) | [C++](./C++/wiggle-sort-ii.cpp) [Python](./Python/wiggle-sort-ii.py) | _O(n)_ on average | _O(1)_ | Medium | variant of [Sort Colors](https://leetcode.com/problems/sort-colors/) | Tri Partition | 347| [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./C++/top-k-frequent-elements.cpp) [Python](./Python/top-k-frequent-elements.py) | _O(n)_ on average | _O(n)_ | Medium | | Quick Select, Heap | 406| [Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height/) | [C++](./C++/queue-reconstruction-by-height.cpp) [Python](./Python/queue-reconstruction-by-height.py) | _O(n * sqrt(n))_ | _O(n)_ | Medium | | | 451| [Sort Characters By Frequency](https://leetcode.com/problems/sort-characters-by-frequency/) | [C++](./C++/sort-characters-by-frequency.cpp) [Python](./Python/sort-characters-by-frequency.py) | _O(n)_ | _O(n)_ | Medium | | | ## Two Pointers | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 19| [Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/)| [C++](./C++/remove-nth-node-from-end-of-list.cpp) [Python](./Python/remove-nth-node-from-end-of-list.py) | _O(n)_ | _O(1)_ | Easy || 86| [Partition List](https://leetcode.com/problems/partition-list/)| [C++](./C++/partition-list.cpp) [Python](./Python/partition-list.py) | _O(n)_ | _O(1)_ | Medium || 141| [Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/)| [C++](./C++/linked-list-cycle.cpp) [Python](./Python/linked-list-cycle.py) | _O(n)_ | _O(1)_ | Easy || 142| [Linked List Cycle II](https://leetcode.com/problems/linked-list-cycle-ii/)| [C++](./C++/linked-list-cycle-ii.cpp) [Python](./Python/linked-list-cycle-ii.py) | _O(n)_ | _O(1)_ | Medium || 143| [Reorder List](https://leetcode.com/problems/reorder-list/)| [C++](./C++/reorder-list.cpp) [Python](./Python/reorder-list.py) | _O(n)_ | _O(1)_ | Medium || 167| [Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) | [C++](./C++/two-sum-ii-input-array-is-sorted.cpp) [Python](./Python/two-sum-ii-input-array-is-sorted.py) | _O(n)_ | _O(1)_ | Medium | | 259 | [3Sum Smaller](https://leetcode.com/problems/3sum-smaller/) | [C++](./C++/3sum-smaller.cpp) [Python](./Python/3sum-smaller.py) | _O(n^2)_ | _O(1)_ | Medium | 馃摉, LintCode | 283 | [Move Zeroes](https://leetcode.com/problems/move-zeroes/) | [C++](./C++/move-zeroes.cpp) [Python](./Python/move-zeroes.py) | _O(n)_ | _O(1)_ | Easy | | 287| [Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/)| [C++](./C++/find-the-duplicate-number.cpp) [Python](./Python/find-the-duplicate-number.py) | _O(n)_ | _O(1)_ | Hard | | Binary Search, Two Pointers | 344| [Reverse String](https://leetcode.com/problems/reverse-string/) | [C++](./C++/reverse-string.cpp) [Python](./Python/reverse-string.py) | _O(n)_ | _O(1)_ | Easy | | 345| [Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [C++](./C++/reverse-vowels-of-a-string.cpp) [Python](./Python/reverse-vowels-of-a-string.py) | _O(n)_ | _O(1)_ | Easy | | 349| [Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [C++](./C++/intersection-of-two-arrays.cpp) [Python](./Python/intersection-of-two-arrays.py) | _O(m + n)_ | _O(min(m, n))_ | Easy | EPI | Hash, Binary Search 350| [Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./C++/intersection-of-two-arrays-ii.cpp) [Python](./Python/intersection-of-two-arrays-ii.py) | _O(m + n)_ | _O(1)_ | Easy | EPI | Hash, Binary Search 360| [Sort Transformed Array](https://leetcode.com/problems/sort-transformed-array/) | [C++](./C++/sort-transformed-array.cpp) [Python](./Python/sort-transformed-array.py) | _O(n)_ | _O(1)_ | Medium |馃摉| 457| [Circular Array Loop](https://leetcode.com/problems/circular-array-loop/) | [C++](./C++/circular-array-loop.cpp) [Python](./Python/circular-array-loop.py) | _O(n)_ | _O(1)_ | Medium || ## Recursion | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 95| [Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/) | [C++](./C++/unique-binary-search-trees-ii.cpp) [Python](./Python/unique-binary-search-trees-ii.py) | _O(4^n / n^(3/2)_ | _O(4^n / n^(3/2)_ | Medium || 98| [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/)|[C++](./C++/validate-binary-search-tree.cpp) [Python](./Python/validate-binary-search-tree.py)| _O(n)_ | _O(1)_ | Medium || 100| [Same Tree](https://leetcode.com/problems/same-tree/) |[C+](./C++/same-tree.cpp) [Python](./Python/same-tree.py) | _O(n)_ | _O(h)_ | Easy || 104| [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/)| [C++](./C++/maximum-depth-of-binary-tree.cpp) [Python](./Python/maximum-depth-of-binary-tree.py)| _O(n)_ | _O(h)_ | Easy || 105| [Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/) | [C++](./C++/construct-binary-tree-from-preorder-and-inorder-traversal.cpp) [Python](./Python/construct-binary-tree-from-preorder-and-inorder-traversal.py) | _O(n)_ | _O(n)_ | Medium || 106| [Construct Binary Tree from Inorder and Postorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/) | [C++](./C++/construct-binary-tree-from-inorder-and-postorder-traversal.cpp) [Python](./Python/construct-binary-tree-from-inorder-and-postorder-traversal.py) | _O(n)_ | _O(n)_ | Medium || 108| [Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/) | [C++](./C++/convert-sorted-array-to-binary-search-tree.cpp) [Python](./Python/convert-sorted-array-to-binary-search-tree.py) | _O(n)_ | _O(logn)_ | Medium || 109| [Convert Sorted List to Binary Search Tree](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/) | [C++](./C++/convert-sorted-list-to-binary-search-tree.cpp) [Python](./Python/convert-sorted-list-to-binary-search-tree.py) | _O(n)_ | _O(logn)_ | Medium || 110| [Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/) | [Python](./Python/balanced-binary-tree.py) | _O(n)_| _O(h)_ | Easy || 111| [Minimum Depth of Binary Tr
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值