Data structure brushing questions: Day 16 (Basic)

 

Table of contents

1. Color classification

1, single pointer

Complexity Analysis

2, double pointer

Complexity Analysis

Second, the merge interval

1. Sort

train of thought

Look at the solution:

1. Color classification

75. Color classification - LeetCode https://leetcode.cn/problems/sort-colors/?plan=data-structures&plan_progress=zz5yyb3

1, single pointer

We can consider doing two passes over the array. In the first pass, we swap all the zeros in the array to the head of the array. In the second pass, we swap all the 1's in the array after the 0's at the head. At this point, all 2's appear at the end of the array, and we're done sorting.

Specifically, we use a pointer ptr to represent the range of the "head". An integer is stored in ptr, indicating that the array nums from position 0 to position ptr−1 belongs to the "head". The initial value of ptr is 0, which means that there is no number at the "head".

In the first traversal, we traverse the entire array from left to right. If we find 0, then we need to exchange 0 with the element at the "head" position, and expand the "head" backward by one position. After the traversal is complete, all 0's are swapped to the "head" range, and "head" contains only 0's.

In the second traversal, we start from the "head" and traverse the entire array from left to right. If 1 is found, then we need to exchange 1 with the element at the "head" position, and replace the "head" Expand backwards by one position. After the traversal ends, all 1s are swapped to the range of the "head", and all are after 0. At this time, 2 only appears outside the "head", so the sorting is complete.

class Solution {
public:
    void sortColors(vector<int>& nums) {
        int n = nums.size();
        int ptr = 0;
        for (int i = 0; i < n; ++i) {
            if (nums[i] == 0) {
                swap(nums[i], nums[ptr]);
                ++ptr;
            }
        }
        for (int i = ptr; i < n; ++i) {
            if (nums[i] == 1) {
                swap(nums[i], nums[ptr]);
                ++ptr;
            }
        }
    }
};

Complexity Analysis

  • Time complexity: O(n), where nn is the length of the array \textit{nums}nums.

  • Space complexity: O(1).

2, double pointer

Method 1 requires two traversals, so can we use only one traversal? We can use an additional pointer, that is, use two pointers to exchange 0 and 1 respectively.

Specifically, we use the pointer p_0 to exchange 0, p_1 to exchange 1, and the initial value is 0. As we traverse the entire array from left to right:

If 1 is found, exchange it with nums[p 1 ] and move p_1 back one position, which is the same as method one;

If 0 is found, it is swapped with [p_0]nums[p] and p_0 is shifted back one position. Is this the right thing to do? We can notice that since consecutive 0s are followed by consecutive 1s, if we swap 0s with nums[p 0], we might swap out a 1. When p_0 < p_1, we have put some 1s in the head continuously, and at this time, we must exchange a 1, resulting in an incorrect answer. Therefore, if p_0 < p_1, then we need to exchange nums[i] with nums[p 1], where i is the current traversed position, after the first exchange, the value of nums[i] is 1, we need to put this 1 at the end of the "head". At the end, we need to move both p_0 and p_1 back one position, not just p_0 one position, no matter if p_0 < p_1 or not.

class Solution {
public:
    void sortColors(vector<int>& nums) {
        int n = nums.size();
        int p0 = 0, p1 = 0;
        for (int i = 0; i < n; ++i) {
            if (nums[i] == 1) {
                swap(nums[i], nums[p1]);
                ++p1;
            } else if (nums[i] == 0) {
                swap(nums[i], nums[p0]);
                if (p0 < p1) {
                    swap(nums[i], nums[p1]);
                }
                ++p0;
                ++p1;
            }
        }
    }
};

Complexity Analysis

  • Time complexity: O(n), where nn is the length of the array \textit{nums}nums.

  • Space complexity: O(1).

Second, the merge interval

56. Merge Intervals - LeetCode https://leetcode.cn/problems/merge-intervals/?plan=data-structures&plan_progress=zz5yyb3

1. Sort

train of thought

If we sort according to the left endpoint of the interval, then in the sorted list, the intervals that can be merged must be continuous. As shown in the figure below, the intervals marked blue, yellow, and green can be merged into a large interval respectively, and they are continuous in the sorted list:

#define MAX_LEN 100000            // the amount of buckets

class MyHashMap {
private:
    vector<pair<int, int>> map[MAX_LEN];     
    
    /** 定义散列函数返回存储数据的下标 */
    int getIndex(int key) {
        return key % MAX_LEN;
    }
    /* 查找数据在哈希表中的位置 */
    int getPos(int key, int index) {
        for (int i = 0; i < map[index].size(); ++i) {
            if (map[index][i].first == key) {
                return i;
            }
        }
        return -1;
    }
    
public:
    
    MyHashMap() {   
    }
    /* 插入一个键值对key, value。如果key存在于映射中,则更新其对应的值value */
    void put(int key, int value) {
        int index = getIndex(key);
        int pos = getPos(key, index);
        if (pos < 0) {
            map[index].push_back(make_pair(key, value));
        } else {
            map[index][pos].second = value;
        }
    }
    /* 返回特定的key所映射的value;如果映射中不包含key的映射,返回 -1  */
    int get(int key) {
        int index = getIndex(key);
        int pos = getPos(key, index);
        if (pos < 0) {
            return -1;
        } else {
            return map[index][pos].second;
        }
    }
    
    /** 如果映射中存在key的映射,则移除key和它所对应的value  */
    void remove(int key) {
        int index = getIndex(key);
        int pos = getPos(key, index);
        if (pos >= 0) {
            map[index].erase(map[index].begin() + pos);
        }
    }
};

Look at the solution:

706. Design Hash Map (Detailed C++ Code Basic Questions) - Design Hash Map - LeetCode https://leetcode.cn/problems/design-hashmap/solution/by-nehzil-bhd2/

Guess you like

Origin blog.csdn.net/m0_63309778/article/details/127059963