Analysis of Leetcode Problem Solving Ideas (23) 155-167

  1. Minimal stack
    Realize a stack and return to the minimum value in constant time

A very simple question, nothing to say

class MinStack {
    
    
public:
    /** initialize your data structure here. */
    MinStack() {
    
    }
    
    void push(int x) {
    
    
        if(x < min) {
    
    
            min = x;
        }

        minStack.push(make_pair(min, x));
    }
    
    void pop() {
    
    
        minStack.pop();
        if (minStack.empty()) {
    
    
            min = INT_MAX;
        } else {
    
    
            min = minStack.top().first;
        }
    }
    
    int top() {
    
    
        return minStack.top().second;
    }
    
    int getMin() {
    
    
        return minStack.top().first;
    }

private:
    int min = INT_MAX;
    stack<pair<int, int>> minStack;
};

  1. Intersecting linked list

The main idea of ​​this question is to use two pointers to point to the head of A/B respectively, slide backward at the same speed, and slide to the other linked list again after sliding to the tail. If the two intersect and are not NULL, it means there is an intersection, otherwise it means that they do not intersect.
The main mathematical thinking is: ptrA walks a unique + public part + b unique, while ptrB walks b unique + public part + a unique, the same speed must be intersected by the same distance. If the intersection is NULL, the common part is 0

class Solution {
    
    
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
    
    
        ListNode *ptrA = headA, *ptrB = headB;
        while (ptrA != ptrB)
        {
    
    
            ptrA = ptrA ? ptrA->next: headB;
            ptrB = ptrB ? ptrB->next: headA;
        }
        return ptrA;      
    }
};
  1. Finding the peak The
    peak element refers to the element whose value is greater than the adjacent value on the left and right.
    Given an input array nums, where nums[i] ≠ nums[i+1], find the peak element and return its index.
    The array may contain multiple peaks. In this case, just return the location of any peak.

Take binary search, there must be a peak on the larger side

int findPeakElement(int* nums, int numsSize)
{
    
    
    int left = 0;
    int right = numsSize - 1;
    while(left < right)
    {
    
    
        int mid = left + (right - left) / 2;
        if(nums[mid] > nums[mid + 1])
        {
    
    
            right = mid;
        }
        else
        {
    
    
            left = mid + 1;
        }
    }
    return left;
}
  1. Maximum spacing
    Given an unordered array, find the largest difference between adjacent elements after the array is sorted.
    If the number of array elements is less than 2, it returns 0.

(1) The easiest way is to call the sort that comes with stl, and then traverse to get the maximum value.

class Solution 
{
    
    
public:
    int maximumGap(vector<int>& nums)
     {
    
    
        if (nums.size() < 2)
            return 0;

        sort(nums.begin(), nums.end());
        int max = 0;
        for (int i = 1; i < nums.size(); i++)
        {
    
    
            int tmp = nums[i] - nums[i - 1];
            if (tmp > max)
                max = tmp;
        }
        return max;
    }
};

(2) Solve by bucket sorting

class Solution {
    
    
public:
class Bucket
{
    
    
public:
    bool used = false;
    int minval = numeric_limits<int>::max();        // same as INT_MAX
    int maxval = numeric_limits<int>::min();        // same as INT_MIN
};

int maximumGap(vector<int>& nums)
{
    
    
    if (nums.empty() || nums.size() < 2)
        return 0;

    int mini = *min_element(nums.begin(), nums.end()),
        maxi = *max_element(nums.begin(), nums.end());

    int bucketSize = max(1, (maxi - mini) / ((int)nums.size() - 1));        // bucket size or capacity
    int bucketNum = (maxi - mini) / bucketSize + 1;                         // number of buckets
    vector<Bucket> buckets(bucketNum);

    for (auto&& num : nums) 
    {
    
    
        int bucketIdx = (num - mini) / bucketSize;                          // locating correct bucket
        buckets[bucketIdx].used = true;
        buckets[bucketIdx].minval = min(num, buckets[bucketIdx].minval);
        buckets[bucketIdx].maxval = max(num, buckets[bucketIdx].maxval);
    }

    int prevBucketMax = mini, maxGap = 0;
    for (auto&& bucket : buckets) 
    {
    
    
        if (!bucket.used)
            continue;

        maxGap = max(maxGap, bucket.minval - prevBucketMax);
        prevBucketMax = bucket.maxval;
    }

    return maxGap;
}


};
  1. Compare version numbers
    Compare two version numbers version1 and version2.
    If version1> version2 returns 1, if version1 <version2 returns -1, otherwise it returns 0.

Take two queues to read and compare

class Solution {
    
    
public:
    int compareVersion(string version1, string version2) {
    
    
        queue<int> v1, v2;

        //提取数字
        __getQueue(v1, version1);
        __getQueue(v2, version2);       

        //补齐
        if (v1.size() < v2.size())
        {
    
    
            while (v1.size() != v2.size())
                v1.push(0);
        }
        else if (v1.size() > v2.size())
        {
    
    
            while (v1.size() != v2.size())
                v2.push(0);
        }

        //逐个取出,判断大小
        while (!v1.empty())
        {
    
    
            if (v1.front() > v2.front())return 1;
            else if (v1.front() < v2.front()) return-1;
            v1.pop(); v2.pop();
        }
        return 0;
    }

private:
    void __getQueue(queue<int> &q, string s)
    {
    
    
        string tmp;

        for (auto c : s)
        {
    
    
            if (c != '.')
                tmp += c;
            else
            {
    
    
                q.push(stoi(tmp));
                tmp.clear();
            }
        }
        if (tmp != "") 
            q.push(stoi(tmp));

        return;
    }
};
  1. Fraction to decimal
class Solution {
    
    
public:
    //小数部分如果余数出现两次就表示该小数是循环小数了
    string fractionToDecimal(int numerator, int denominator) {
    
    
        if(denominator==0) return "";//边界条件,分母为0
        if(numerator==0) return "0";//边界条件,分子为0
        string result;
        
        //转换为longlong防止溢出
        long long num = static_cast<long long>(numerator);
        long long denom = static_cast<long long>(denominator);
        
        //处理正负号,一正一负取负号
        if((num>0)^(denom>0))result.push_back('-');
        
        //分子分母全部转换为正数
        num=llabs(num);denom=llabs(denom);
        
        //处理整数部分
        result.append(to_string(num/denom));
        
        //处理小数部分
        num%=denom;                         //获得余数
        if(num==0)return result;             //余数为0,表示整除了,直接返回结果
        result.push_back('.');              //余数不为0,添加小数点
        int index=result.size()-1;          //获得小数点的下标
        unordered_map<int,int> record;      //map用来记录出现重复数的下标,然后将'('插入到重复数前面就好了
        while(num&&record.count(num)==0){
    
       //小数部分:余数不为0且余数还没有出现重复数字
            record[num]=++index;
            num*=10;                        //余数扩大10倍,然后求商,和草稿本上运算方法是一样的
            result+=to_string(num/denom);
            num%=denom;
        }
        if(record.count(num)==1){
    
               //出现循环余数,我们直接在重复数字前面添加'(',字符串末尾添加')'
            result.insert(record[num],"(");
            result.push_back(')');
        }
        return result;
    }
};

  1. The sum of two numbers 2
    Given an ordered array that has been arranged in ascending order, find two numbers so that their sum is equal to the target number.
    The function should return the two subscript values ​​index1 and index2, where index1 must be less than index2.
    This question is solvable by brute force search, but the time complexity is high. A hash table can also be used, but the space complexity is high. The optimal solution is to adopt two-pointer sliding. Because the meaning of the question shows that it is a sorted array and there must be a unique solution, so this is the best solution
class Solution {
    
    
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
    
    
        int low = 0, high = numbers.size() - 1;
        while (low < high) {
    
    
            int sum = numbers[low] + numbers[high];
            if (sum == target)
                return {
    
    low + 1, high + 1};
            else if (sum < target)
                ++low;
            else
                --high;
        }
        return {
    
    -1, -1};
    }
};

Guess you like

Origin blog.csdn.net/u013354486/article/details/105728688