[LeetCode question brushing diary] common question types of array questions

Posted by fiorelina21 on Sat, 20 Nov 2021 01:31:03 +0100

This article summarizes the leetcode problem about arrays, and basically finds out the problem-solving ideas and methods of array problems. So that you can quickly find ideas and solutions when you encounter similar problems later.

303. Region and retrieval - array immutable

Given an integer array nums, find the sum of the elements in the array from index i to j (i ≤ j), including i and j.

Implement NumArray class:

NumArray(int[] nums) initializes objects with array nums
int sumRange(int i, int j) returns the sum of the elements in the array num from index I to J (I ≤ J), including I and J (that is, sum (Num [i], Num [i + 1],..., Num [J])

Example:

Input:
["NumArray", "sumRange", "sumRange", "sumRange"]
[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]
Output:
[null, 1, -1, -3]

Explanation:
NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);
numArray.sumRange(0, 2); // return 1 ((-2) + 0 + 3)
numArray.sumRange(2, 5); // return -1 (3 + (-5) + 2 + (-1))
numArray.sumRange(0, 5); // return -3 ((-2) + 0 + 3 + (-5) + 2 + (-1))

Tips:

0 <= nums.length <= 104
-105 <= nums[i] <= 105
0 <= i <= j < nums.length
The sumRange method can be called up to 104 times

C language solution

typedef struct {
    int* sums;
} NumArray;

NumArray* numArrayCreate(int* nums, int numsSize) {
    NumArray* ret = malloc(sizeof(NumArray));
    ret->sums = malloc(sizeof(int) * (numsSize + 1));
    ret->sums[0] = 0;
    for (int i = 0; i < numsSize; i++) {
        ret->sums[i + 1] = ret->sums[i] + nums[i];
    }
    return ret;
}

int numArraySumRange(NumArray* obj, int i, int j) {
    return obj->sums[j + 1] - obj->sums[i];
}

void numArrayFree(NumArray* obj) {
    free(obj->sums);
}

C + + version

class NumArray {
public:
    vector<int> sums;

    NumArray(vector<int>& nums) {
        int n = nums.size();
        sums.resize(n + 1);
        for (int i = 0; i < n; i++) {
            sums[i + 1] = sums[i] + nums[i];
        }
    }

    int sumRange(int i, int j) {
        return sums[j + 1] - sums[i];
    }
};

304. Two dimensional area and retrieval - the matrix is immutable

Given a two-dimensional matrix, multiple requests of the following types:

Calculate the sum of the elements within its sub rectangle. The upper left corner of the sub matrix is (row1, col1) and the lower right corner is (row2, col2).
Implement the NumMatrix class:

NumMatrix(int[][] matrix) initializes the given integer matrix
int sumRegion(int row1, int col1, int row2, int col2) returns the sum of the elements of the submatrix in the upper left corner (row1, col1) and the lower right corner (row2, col2).

Example 1:

Input:
["NumMatrix","sumRegion","sumRegion","sumRegion"]
[[[[3,0,1,4,2],[5,6,3,2,1],[1,2,0,1,5],[4,1,0,1,7],[1,0,3,0,5]]],[2,1,4,3],[1,1,2,2],[1,2,2,4]]
Output:
[null, 8, 11, 12]

Explanation:
NumMatrix numMatrix = new NumMatrix([[3,0,1,4,2],[5,6,3,2,1],[1,2,0,1,5],[4,1,0,1,7],[1,0,3,0,5]]]);
numMatrix.sumRegion(2, 1, 4, 3); // return 8 (sum of elements in the red rectangle)
numMatrix.sumRegion(1, 1, 2, 2); // return 11 (sum of elements in the green rectangle)
numMatrix.sumRegion(1, 2, 2, 4); // return 12 (sum of elements in the blue rectangle)

Tips:

m == matrix.length
n == matrix[i].length
1 <= m, n <= 200
-105 <= matrix[i][j] <= 105
0 <= row1 <= row2 < m
0 <= col1 <= col2 < n
The sumRegion method can be called up to 104 times

C language

typedef struct {
    int** sums;
    int sumsSize;
} NumMatrix;

NumMatrix* numMatrixCreate(int** matrix, int matrixSize, int* matrixColSize) {
    NumMatrix* ret = malloc(sizeof(NumMatrix));
    ret->sums = malloc(sizeof(int*) * matrixSize);
    ret->sumsSize = matrixSize;
    for (int i = 0; i < matrixSize; i++) {
        ret->sums[i] = malloc(sizeof(int) * (matrixColSize[i] + 1));
        ret->sums[i][0] = 0;
        for (int j = 0; j < matrixColSize[i]; j++) {
            ret->sums[i][j + 1] = ret->sums[i][j] + matrix[i][j];
        }
    }
    return ret;
}

int numMatrixSumRegion(NumMatrix* obj, int row1, int col1, int row2, int col2) {
    int sum = 0;
    for (int i = row1; i <= row2; i++) {
        sum += obj->sums[i][col2 + 1] - obj->sums[i][col1];
    }
    return sum;
}

void numMatrixFree(NumMatrix* obj) {
    for (int i = 0; i < obj->sumsSize; i++) {
        free(obj->sums[i]);
    }
    free(obj->sums);
}

C++

class NumMatrix {
public:
    vector<vector<int>> sums;

    NumMatrix(vector<vector<int>>& matrix) {
        int m = matrix.size();
        if (m > 0) {
            int n = matrix[0].size();
            sums.resize(m, vector<int>(n + 1));
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    sums[i][j + 1] = sums[i][j] + matrix[i][j];
                }
            }
        }
    }

    int sumRegion(int row1, int col1, int row2, int col2) {
        int sum = 0;
        for (int i = row1; i <= row2; i++) {
            sum += sums[i][col2 + 1] - sums[i][col1];
        }
        return sum;
    }
};

C language

typedef struct {
    int** sums;
    int sumsSize;
} NumMatrix;

NumMatrix* numMatrixCreate(int** matrix, int matrixSize, int* matrixColSize) {
    NumMatrix* ret = malloc(sizeof(NumMatrix));
    ret->sums = malloc(sizeof(int*) * (matrixSize + 1));
    ret->sumsSize = matrixSize + 1;
    int n = matrixSize ? matrixColSize[0] : 0;
    for (int i = 0; i <= matrixSize; i++) {
        ret->sums[i] = malloc(sizeof(int) * (n + 1));
        memset(ret->sums[i], 0, sizeof(int) * (n + 1));
    }
    for (int i = 0; i < matrixSize; i++) {
        for (int j = 0; j < matrixColSize[i]; j++) {
            ret->sums[i + 1][j + 1] = ret->sums[i][j + 1] + ret->sums[i + 1][j] - ret->sums[i][j] + matrix[i][j];
        }
    }
    return ret;
}

int numMatrixSumRegion(NumMatrix* obj, int row1, int col1, int row2, int col2) {
    return obj->sums[row2 + 1][col2 + 1] - obj->sums[row1][col2 + 1] - obj->sums[row2 + 1][col1] + obj->sums[row1][col1];
}

void numMatrixFree(NumMatrix* obj) {
    for (int i = 0; i < obj->sumsSize; i++) {
        free(obj->sums[i]);
    }
    free(obj->sums);
}

C++

class NumMatrix {
public:
    vector<vector<int>> sums;

    NumMatrix(vector<vector<int>>& matrix) {
        int m = matrix.size();
        if (m > 0) {
            int n = matrix[0].size();
            sums.resize(m + 1, vector<int>(n + 1));
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    sums[i + 1][j + 1] = sums[i][j + 1] + sums[i + 1][j] - sums[i][j] + matrix[i][j];
                }
            }
        }
    }

    int sumRegion(int row1, int col1, int row2, int col2) {
        return sums[row2 + 1][col2 + 1] - sums[row1][col2 + 1] - sums[row2 + 1][col1] + sums[row1][col1];
    }
};

Sword finger Offer 04. Search in two-dimensional array

In an n * m two-dimensional array, each row is sorted in ascending order from left to right, and each column is sorted in ascending order from top to bottom. Please complete an efficient function, enter such a two-dimensional array and an integer, and judge whether the array contains the integer.

Example:

The existing matrix is as follows:

[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Given target = 5, return true.

Given target = 20, false is returned.

Limitations:

0 <= n <= 1000

0 <= m <= 1000

Note: this question is the same as the main station question 240: https://leetcode-cn.com/problems/search-a-2d-matrix-ii/

C

bool findNumberIn2DArray(int** matrix, int matrixSize, int* matrixColSize, int target){
    int row,col;
    row=0;
    col=*matrixColSize-1;
    if(matrixSize==0||*matrixColSize==0)
    return false;
    int flag;
    for(flag=1;flag!=0;)
    {
        if(target==matrix[row][col])
            break;
        else{
            if(target<matrix[row][col])
            col=col-1;
            else
            row=row+1;
        }
        if(col==-1||row==matrixSize)
        flag=0;
    }
    if(flag==0)
    return false;
    else
    return true;
}

C++

class Solution {
public:
    bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
        int i = matrix.size() - 1, j = 0;
        while(i >= 0 && j < matrix[0].size())
        {
            if(matrix[i][j] > target) i--;
            else if(matrix[i][j] < target) j++;
            else return true;
        }
        return false;
    }
};

4. Find the median of two positively ordered arrays

Give two positively ordered (from small to large) arrays nums1 and nums2 of sizes m and n, respectively. Please find and return the median of these two positive arrays.

Example 1:

Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merge array = [1,2,3], median 2
Example 2:

Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
Explanation: merged array = [1,2,3,4], median (2 + 3) / 2 = 2.5
Example 3:

Input: nums1 = [0,0], nums2 = [0,0]
Output: 0.00000
Example 4:

Input: nums1 = [], nums2 = [1]
Output: 1.00000
Example 5:

Input: nums1 = [2], nums2 = []
Output: 2.00000

Tips:

nums1.length == m
nums2.length == n
0 <= m <= 1000
0 <= n <= 1000
1 <= m + n <= 2000
-106 <= nums1[i], nums2[i] <= 106

Advanced: can you design an algorithm with time complexity O(log (m+n)) to solve this problem?

The most direct idea: sort after merging to find the median of the array

This idea does not use the original two arrays, which is already in positive order. Although this idea is simple and the space-time complexity will be very high, it is not meaningless to quickly solve a difficult problem.

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        // The space-time complexity is the highest when the arrays are combined and then sorted
        vector<int> v;
        v.insert(v.end(),nums1.begin(),nums1.end());
        v.insert(v.end(),nums2.begin(),nums2.end());
        sort(v.begin(),v.end());
        double n;
        if(v.size()%2==0)
            n = (double(v[v.size()/2])+double(v[(v.size()/2)-1]))/2;
        else
            n = v[v.size()/2];
        return n;
    }
};

Double pointer insertion sorting

Using the property that both arrays are in positive order and sorting with double pointers, the time complexity is improved

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        // Using the property of positive order of array, double pointer insertion sorting
        vector<int> v;
        int i = 0, j = 0;
        while (i < nums1.size() && j < nums2.size()) {
            if (nums1[i] < nums2[j]) {
                v.push_back(nums1[i]);
                i++;
            } else if (nums1[i] > nums2[j]) {
                v.push_back(nums2[j]);
                j++;
            } else {
                v.push_back(nums1[i]);
                v.push_back(nums2[j]);
                i++;
                j++;
            }
        }
        if (i < nums1.size()) {
            while (i < nums1.size()) {
                v.push_back(nums1[i]);
                i++;
            }
        } else if (j < nums2.size()){
            while (j < nums2.size()) {
                v.push_back(nums2[j]);
                j++;
            }
        }
        double n;
        if(v.size()%2==0)
            n = (double(v[v.size()/2])+double(v[(v.size()/2)-1]))/2;
        else
            n = v[v.size()/2];
        return n;
    }
};

Double pointer optimized version

In fact, you don't have to calculate all the arrays before making a judgment. You just need to calculate the array to the middle position and then make a judgment. In theory, half the time complexity will be left.

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        // Using the property of positive order of array, double pointer insertion sorting
        // In fact, we don't have to sort them all. We just need the middle number to terminate the program
        length = nums1.size() + nums2.size();
        double n;
        vector<int> v;
        int i = 0, j = 0;
        while (i < nums1.size() && j < nums2.size()) {
            if (nums1[i] < nums2[j]) {
                v.push_back(nums1[i]);
                i++;
            } else if (nums1[i] > nums2[j]) {
                v.push_back(nums2[j]);
                j++;
            } else {
                v.push_back(nums1[i]);
                v.push_back(nums2[j]);
                i++;
                j++;
            }
            // Only half the calculation is enough
            if (v.size() >= length/2 + 1) 
                return help(v);
        }
        if (i < nums1.size()) {
            while (i < nums1.size()) {
                v.push_back(nums1[i]);
                i++;
                if (v.size() >= length/2 + 1) {
                    return help(v);
                }
            }
        } else if (j < nums2.size()){
            while (j < nums2.size()) {
                v.push_back(nums2[j]);
                j++;
                if (v.size() >= length/2 + 1)
                    return help(v);
            }
        }
        return 0;
    }
private:
    int length;
    double help(vector<int> v) {
        double ans;
        if (length%2 == 0) {
            ans = (double(v[length/2])+double(v[length/2 - 1]))/2;
        } else {
            ans = v[length/2];
        }
        return ans;
    }
};

Official solution: binary search

Theoretically, the time complexity is the same, and the space complexity will be improved

class Solution {
public:
    int getKthElement(const vector<int>& nums1, const vector<int>& nums2, int k) {
        /* Main idea: to find the element with the smallest K (k > 1), take pivot 1 = nums1 [K / 2-1] and pivot 2 = nums2 [K / 2-1] for comparison
         * "/" here means division
         * nums1 There are nums1 [0.. K / 2-2] elements smaller than or equal to pivot 1, k/2-1 in total
         * nums2 There are nums2 [0.. K / 2-2] elements smaller than or equal to pivot 2, k/2-1 in total
         * Take pivot = min (pivot 1, pivot 2), and the total number of elements less than or equal to pivot in the two arrays will not exceed (K / 2-1) + (K / 2-1) < = K-2
         * In this way, pivot itself can only be the k-1 smallest element
         * If pivot = pivot 1, nums1 [0.. K / 2-1] cannot be the k-th smallest element. All these elements are "deleted" and the rest are used as a new nums1 array
         * If pivot = pivot 2, nums2 [0.. K / 2-1] cannot be the k-th smallest element. All these elements are "deleted" and the rest are used as a new nums2 array
         * Because we "deleted" some elements (these elements are smaller than the element smaller than k), we need to modify the value of K and subtract the number of deleted elements
         */
 
        int m = nums1.size();
        int n = nums2.size();
        int index1 = 0, index2 = 0;
 
        while (true) {
            // Boundary condition
            if (index1 == m) {
                return nums2[index2 + k - 1];
            }
            if (index2 == n) {
                return nums1[index1 + k - 1];
            }
            if (k == 1) {
                return min(nums1[index1], nums2[index2]);
            }
 
            // Normal condition
            int newIndex1 = min(index1 + k / 2 - 1, m - 1);
            int newIndex2 = min(index2 + k / 2 - 1, n - 1);
            int pivot1 = nums1[newIndex1];
            int pivot2 = nums2[newIndex2];
            if (pivot1 <= pivot2) {
                k -= newIndex1 - index1 + 1;
                index1 = newIndex1 + 1;
            }
            else {
                k -= newIndex2 - index2 + 1;
                index2 = newIndex2 + 1;
            }
        }
    }
 
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int totalLength = nums1.size() + nums2.size();
        if (totalLength % 2 == 1) {
            return getKthElement(nums1, nums2, (totalLength + 1) / 2);
        }
        else {
            return (getKthElement(nums1, nums2, totalLength / 2) + getKthElement(nums1, nums2, totalLength / 2 + 1)) / 2.0;
        }
    }
};

26. Delete duplicates in the ordered array

Give you an ordered array nums, please delete the repeated elements in place, make each element appear only once, and return the new length of the deleted array.

Do not use additional array space. You must modify the input array in place and complete it with O(1) additional space.

explain:

Why is the returned value an integer, but the output answer is an array?

Note that the input array is passed by reference, which means that modifying the input array in the function is visible to the caller.

You can imagine the internal operation as follows:

//nums is passed by reference. That is, no copy of the arguments is made
int len = removeDuplicates(nums);

//Modifying the input array in the function is visible to the caller.
//According to the length returned by your function, it will print all elements within that length range in the array.
for (int i = 0; i < len; i++) {
print(nums[i]);
}

Example 1:

Input: num = [1,1,2]
Output: 2, Num = [1,2]
Explanation: the function should return a new length of 2, and the first two elements of the original array num are modified to 1 and 2. There is no need to consider the elements in the array that exceed the new length.
Example 2:

Input: num = [0,0,1,1,1,2,2,3,3,4]
Output: 5, Num = [0,1,2,3,4]
Explanation: the function should return a new length of 5, and the first five elements of the original array num are modified to 0, 1, 2, 3 and 4. There is no need to consider the elements in the array that exceed the new length.

Tips:

0 <= nums.length <= 3 * 104
-104 <= nums[i] <= 104
nums is arranged in ascending order

Double finger needling

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ntJG4jXp-1631407998734)(C:\Users521\Desktop\GIF.gif)]

C

int removeDuplicates(int* nums, int numsSize) {
    if (numsSize == 0) {
        return 0;
    }
    int fast = 1, slow = 1;
    while (fast < numsSize) {
        if (nums[fast] != nums[fast - 1]) {
            nums[slow] = nums[fast];
            ++slow;
        }
        ++fast;
    }
    return slow;
}

C++

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

In situ deletion method:

Using erase in the same way as the LeetCode27 question below will not have the risk of memory leakage, but the time complexity measured in the sample will be higher than that in the following way. It is obvious to compare the time:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        // In situ deletion method
        if (nums.size() < 2)
            return nums.size();
        for (int i = 1; i < nums.size(); i++) {
            if (nums[i - 1] == nums[i]) {
                nums.erase(nums.begin() + i);
                i--;
            }
        }
        return nums.size();
    }
};

Manual deletion method: there is a risk of memory leakage

We only return arrays of length + + i here. What will happen? We don't return or control the latter length arrays, and OJ will only read the arrays of length we return. Therefore, although the time complexity is optimized a lot here, i don't think this method is good

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.size() < 2)
            return nums.size();
        // The method of manual deletion is to constantly exchange and delete the method that has not been deleted in front
        // Although the pressure of time complexity caused by each erase is avoided, there is a risk of memory leakage
        int i = 0;
        for(int j = 1; j < nums.size(); j++) {
            if(nums[i] != nums[j]){
                i++;
                nums[i] = nums[j];
            }
        }
        return ++i;
    }
};

27. Remove element

Give you an array num and a value val. you need to remove all elements with a value equal to Val in place and return the new length of the removed array.

Instead of using extra array space, you must use only O(1) extra space and modify the input array in place.

The order of elements can be changed. You don't need to consider the elements in the array that exceed the new length.

explain:

Why is the returned value an integer, but the output answer is an array?

Note that the input array is passed by reference, which means that modifying the input array in the function is visible to the caller.

You can imagine the internal operation as follows:

//nums is passed by reference. That is, no copy of the arguments is made
int len = removeElement(nums, val);

//Modifying the input array in the function is visible to the caller.
//According to the length returned by your function, it will print all elements within that length range in the array.
for (int i = 0; i < len; i++) {
print(nums[i]);
}

Example 1:

Input: num = [3,2,2,3], Val = 3
Output: 2, Num = [2,2]
Explanation: the function should return a new length of 2, and the first two elements in num are 2. You don't need to consider the elements in the array that exceed the new length. For example, if the new length returned by the function is 2, and num = [2,2,3,3] or num = [2,2,0,0], it will also be regarded as the correct answer.
Example 2:

Input: num = [0,1,2,2,3,0,4,2], Val = 2
Output: 5, Num = [0,1,4,0,3]
Explanation: the function should return a new length of 5, and the first five elements in num are 0, 1, 3, 0 and 4. Note that these five elements can be in any order. You don't need to consider the elements in the array that exceed the new length.

Tips:

0 <= nums.length <= 100
0 <= nums[i] <= 50
0 <= val <= 100

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (IMG vetlndhh-1631407998734)( https://raw.githubusercontent.com/xkyvvv/blogpic/main/pic1/image-20210905103459501.png )]

C language version

int removeElement(int* nums, int numsSize, int val) {
    int left = 0;
    for (int right = 0; right < numsSize; right++) {
        if (nums[right] != val) {
            nums[left] = nums[right];
            left++;
        }
    }
    return left;
}

C + + version

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

C language version

int removeElement(int* nums, int numsSize, int val) {
    int left = 0, right = numsSize;
    while (left < right) {
        if (nums[left] == val) {
            nums[left] = nums[right - 1];
            right--;
        } else {
            left++;
        }
    }
    return left;
}

C + + version

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

33. Search rotation sort array

The integer array nums is arranged in ascending order, and the values in the array are different from each other.

Before passing to the function, Num rotates on a previously unknown subscript k (0 < = k < num.length), making the array [num [k], Num [K + 1],..., Num [n-1], Num [0], Num [1],..., Num [k-1]] (subscripts count from 0). For example, [0,1,2,4,5,6,7] may become [4,5,6,7,0,1,2] after rotation at subscript 3.

Give you the rotated array num and an integer target. If the target value target exists in num, return its subscript, otherwise return - 1.

Example 1:

Input: num = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:

Input: num = [4,5,6,7,0,1,2], target = 3
Output: - 1
Example 3:

Input: num = [1], target = 0
Output: - 1

Tips:

1 <= nums.length <= 5000
-10^4 <= nums[i] <= 10^4
Each value in num is unique
The title data ensures that nums rotates on a subscript unknown in advance
-10^4 <= target <= 10^4

Advanced: can you design a solution with time complexity of O(log n)?

[if the external link image transfer fails, the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-GgPvMDxl-1631407998736)([if the external link image transfer fails, the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-pcuomgsj-16314081358)( https://raw.githubusercontent.com/xkyvvv/blogpic/main/pic1/image-20210905105535173.png#pic_center )]
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (IMG akefixg2-1631407998737)( https://raw.githubusercontent.com/xkyvvv/blogpic/main/pic1/image-20210905105553366.png )]

C + + version

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

53. Maximum subsequence sum

Given an integer array nums, find a continuous sub array with the largest sum (the sub array contains at least one element) and return its maximum sum.

Example 1:

Input: num = [- 2,1, - 3,4, - 1,2,1, - 5,4]
Output: 6
Explanation: the maximum sum of continuous subarray [4, - 1,2,1] is 6.
Example 2:

Input: num = [1]
Output: 1
Example 3:

Input: num = [0]
Output: 0
Example 4:

Input: num = [- 1]
Output: - 1
Example 5:

Input: num = [- 100000]
Output: - 100000

Tips:

1 <= nums.length <= 3 * 104
-105 <= nums[i] <= 105

Advanced: if you have implemented a solution with complexity O(n), try using a more sophisticated divide and conquer method.

C language

int maxSubArray(int* nums, int numsSize) {
    int pre = 0, maxAns = nums[0];
    for (int i = 0; i < numsSize; i++) {
        pre = fmax(pre + nums[i], nums[i]);
        maxAns = fmax(maxAns, pre);
    }
    return maxAns;
}

C + + language

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int pre = 0, maxAns = nums[0];
        for (const auto &x: nums) {
            pre = max(pre + x, x);
            maxAns = max(maxAns, pre);
        }
        return maxAns;
    }
};

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-b3vqrl2q-1631407998738)( https://raw.githubusercontent.com/xkyvvv/blogpic/main/pic1/image-20210905112816474.png )]

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (IMG herwfssx-1631407998738)( https://raw.githubusercontent.com/xkyvvv/blogpic/main/pic1/image-20210905112845212.png )]

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-ykuc3np5-1631407998739)( https://raw.githubusercontent.com/xkyvvv/blogpic/main/pic1/image-20210905112903644.png )]

C language

struct Status {
    int lSum, rSum, mSum, iSum;
};

struct Status pushUp(struct Status l, struct Status r) {
    int iSum = l.iSum + r.iSum;
    int lSum = fmax(l.lSum, l.iSum + r.lSum);
    int rSum = fmax(r.rSum, r.iSum + l.rSum);
    int mSum = fmax(fmax(l.mSum, r.mSum), l.rSum + r.lSum);
    return (struct Status){lSum, rSum, mSum, iSum};
};

struct Status get(int* a, int l, int r) {
    if (l == r) {
        return (struct Status){a[l], a[l], a[l], a[l]};
    }
    int m = (l + r) >> 1;
    struct Status lSub = get(a, l, m);
    struct Status rSub = get(a, m + 1, r);
    return pushUp(lSub, rSub);
}

int maxSubArray(int* nums, int numsSize) {
    return get(nums, 0, numsSize - 1).mSum;
}

C++

class Solution {
public:
    struct Status {
        int lSum, rSum, mSum, iSum;
    };

    Status pushUp(Status l, Status r) {
        int iSum = l.iSum + r.iSum;
        int lSum = max(l.lSum, l.iSum + r.lSum);
        int rSum = max(r.rSum, r.iSum + l.rSum);
        int mSum = max(max(l.mSum, r.mSum), l.rSum + r.lSum);
        return (Status) {lSum, rSum, mSum, iSum};
    };

    Status get(vector<int> &a, int l, int r) {
        if (l == r) {
            return (Status) {a[l], a[l], a[l], a[l]};
        }
        int m = (l + r) >> 1;
        Status lSub = get(a, l, m);
        Status rSub = get(a, m + 1, r);
        return pushUp(lSub, rSub);
    }

    int maxSubArray(vector<int>& nums) {
        return get(nums, 0, nums.size() - 1).mSum;
    }
};

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (IMG bowjm4nr-1631407998740)( https://raw.githubusercontent.com/xkyvvv/blogpic/main/pic1/image-20210905113016998.png )]

152. Product maximum subarray

Give you an integer array nums. Please find the continuous sub array with the largest product in the array (the sub array contains at least one number) and return the product corresponding to the sub array.

Example 1:

Input: [2,3, - 2,4]
Output: 6
Explanation: subarray [2,3] has a maximum product of 6.
Example 2:

Input: [- 2,0, - 1]
Output: 0
Explanation: the result cannot be 2 because [- 2, - 1] is not a subarray.

C++

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        vector <int> maxF(nums), minF(nums);
        for (int i = 1; i < nums.size(); ++i) {
            maxF[i] = max(maxF[i - 1] * nums[i], max(nums[i], minF[i - 1] * nums[i]));
            minF[i] = min(minF[i - 1] * nums[i], min(nums[i], maxF[i - 1] * nums[i]));
        }
        return *max_element(maxF.begin(), maxF.end());
    }
};

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-thhu9yih-1631407998741)( https://raw.githubusercontent.com/xkyvvv/blogpic/main/pic1/image-20210905113311024.png )]

C++

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int maxF = nums[0], minF = nums[0], ans = nums[0];
        for (int i = 1; i < nums.size(); ++i) {
            int mx = maxF, mn = minF;
            maxF = max(mx * nums[i], max(nums[i], mn * nums[i]));
            minF = min(mn * nums[i], min(nums[i], mx * nums[i]));
            ans = max(maxF, ans);
        }
        return ans;
    }
};

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-qln7uaeb-1631407998741)( https://raw.githubusercontent.com/xkyvvv/blogpic/main/pic1/image-20210905113346264.png )]

238. Product of arrays other than itself

Give you an integer array num of length N, where n > 1, and return the output array output, where output[i] is equal to the product of all elements in num except num [i].

Example:

Input: [1,2,3,4]
Output: [24,12,8,6]

Tip: the title data ensures that the product of all prefix elements and suffixes (even the whole array) of any element in the array is within the range of 32-bit integers.

Note: please do not use division and complete the problem within O(n) time complexity.

Advanced:
Can you do this in constant space complexity? (for the purpose of spatial complexity analysis, the output array is not considered as additional space.)

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-oheogf49-1631407998742)( https://raw.githubusercontent.com/xkyvvv/blogpic/main/pic1/image-20210905115230964.png )]

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-svM95ICc-1631407998742)(C:\Users521\Desktop\GIF2.gif)]

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        int length = nums.size();

        // L and R represent the product list on the left and right sides respectively
        vector<int> L(length, 0), R(length, 0);

        vector<int> answer(length);

        // L[i] is the product of all elements to the left of index I
        // For the element with index '0', L[0] = 1 because there is no element on the left
        L[0] = 1;
        for (int i = 1; i < length; i++) {
            L[i] = nums[i - 1] * L[i - 1];
        }

        // R[i] is the product of all elements to the right of index I
        // For the element with index 'length-1', because there is no element on the right, R[length-1] = 1
        R[length - 1] = 1;
        for (int i = length - 2; i >= 0; i--) {
            R[i] = nums[i + 1] * R[i + 1];
        }

        // For index I, the product of all elements except num [i] is the product of all elements on the left multiplied by all elements on the right
        for (int i = 0; i < length; i++) {
            answer[i] = L[i] * R[i];
        }

        return answer;
    }
};

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-qr24ke4a-1631407998743) (C: \ users \ 10521 \ appdata \ roaming \ typora \ typora user images \ image-20210905115436395. PNG)]

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG lsasrppn-1631407998743) (C: \ users \ 10521 \ appdata \ roaming \ typora \ typora user images \ image-20210905115511822. PNG)]

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        int length = nums.size();
        vector<int> answer(length);

        // answer[i] represents the product of all elements to the left of index I
        // answer[0] = 1 because there is no element to the left of the element with index '0'
        answer[0] = 1;
        for (int i = 1; i < length; i++) {
            answer[i] = nums[i - 1] * answer[i - 1];
        }

        // R is the product of all elements on the right
        // At first there was no element on the right, so R = 1
        int R = 1;
        for (int i = length - 1; i >= 0; i--) {
            // For index I, the product on the left is answer[i], and the product on the right is R
            answer[i] = answer[i] * R;
            // R needs to include all products on the right, so the current value needs to be multiplied by r when calculating the next result
            R *= nums[i];
        }
        return answer;
    }
};

7. Integer inversion

Give you a 32-bit signed integer x and return the result after reversing the number part in X.

If the inverted integer exceeds the range of 32-bit signed integers [− 231, 231 − 1], 0 is returned.

Assume that the environment does not allow the storage of 64 bit integers (signed or unsigned).

Example 1:

Input: x = 123
Output: 321
Example 2:

Input: x = -123
Output: - 321
Example 3:

Input: x = 120
Output: 21
Example 4:

Input: x = 0
Output: 0

Tips:

-231 <= x <= 231 - 1

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-xhvjm98o-1631407998743)( https://raw.githubusercontent.com/xkyvvv/blogpic/main/pic1/image-20210905120808894.png )]

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-jls8sudo-1631407998745)( https://raw.githubusercontent.com/xkyvvv/blogpic/main/pic1/image-20210905120849830.png )]

C language

int reverse(int x) {
    int rev = 0;
    while (x != 0) {
        if (rev < INT_MIN / 10 || rev > INT_MAX / 10) {
            return 0;
        }
        int digit = x % 10;
        x /= 10;
        rev = rev * 10 + digit;
    }
    return rev;
}

C++

class Solution {
public:
    int reverse(int x) {
        int rev = 0;
        while (x != 0) {
            if (rev < INT_MIN / 10 || rev > INT_MAX / 10) {
                return 0;
            }
            int digit = x % 10;
            x /= 10;
            rev = rev * 10 + digit;
        }
        return rev;
    }
};

739. Daily temperature

According to the daily temperature list, please calculate how many days you need to wait for a higher temperature each day. If the temperature will not rise after that, please replace it with 0 in this position.

Example 1:

Input: temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]
Example 2:

Input: temperatures = [30,40,50,60]
Output: [1,1,1,0]
Example 3:

Input: temperatures = [30,60,90]
Output: [1,1,0]

Tips:

1 <= temperatures.length <= 105
30 <= temperatures[i] <= 100

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-lffz1q35-1631407998746)( https://raw.githubusercontent.com/xkyvvv/blogpic/main/pic1/image-20210905122304997.png )]

C++

class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        int n = temperatures.size();
        vector<int> ans(n), next(101, INT_MAX);
        for (int i = n - 1; i >= 0; --i) {
            int warmerIndex = INT_MAX;
            for (int t = temperatures[i] + 1; t <= 100; ++t) {
                warmerIndex = min(warmerIndex, next[t]);
            }
            if (warmerIndex != INT_MAX) {
                ans[i] = warmerIndex - i;
            }
            next[temperatures[i]] = i;
        }
        return ans;
    }
};

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-2o174puw-1631407998746)( https://raw.githubusercontent.com/xkyvvv/blogpic/main/pic1/image-20210905122344158.png )]

Method 2: monotone stack

A monotonic stack for storing subscripts can be maintained, and the temperature in the temperature list corresponding to the subscript from the bottom of the stack to the top of the stack decreases in turn. If a subscript is in the monotone stack, it means that the next subscript with higher temperature has not been found.

class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        int n = temperatures.size();
        vector<int> ans(n);
        stack<int> s;
        for (int i = 0; i < n; ++i) {
            while (!s.empty() && temperatures[i] > temperatures[s.top()]) {
                int previousIndex = s.top();
                ans[previousIndex] = i - previousIndex;
                s.pop();
            }
            s.push(i);
        }
        return ans;
    }
};

1. Sum of two numbers

Given an integer array nums and an integer target value target, please find the two integers with and as the target value target in the array and return their array subscripts.

You can assume that each input will correspond to only one answer. However, the same element in the array cannot be repeated in the answer.

You can return answers in any order.

Example 1:

Input: num = [2,7,11,15], target = 9
Output: [0,1]
Explanation: because num [0] + num [1] = = 9, return [0, 1].
Example 2:

Input: num = [3,2,4], target = 6
Output: [1,2]
Example 3:

Input: num = [3,3], target = 6
Output: [0,1]

Tips:

2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
There will only be one valid answer
Advanced: can you think of an algorithm with a time complexity less than O(n2)?

C

int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
    for (int i = 0; i < numsSize; ++i) {
        for (int j = i + 1; j < numsSize; ++j) {
            if (nums[i] + nums[j] == target) {
                int* ret = malloc(sizeof(int) * 2);
                ret[0] = i, ret[1] = j;
                *returnSize = 2;
                return ret;
            }
        }
    }
    *returnSize = 0;
    return NULL;
}

C++

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

code

struct hashTable {
    int key;
    int val;
    UT_hash_handle hh;
};

struct hashTable* hashtable;

struct hashTable* find(int ikey) {
    struct hashTable* tmp;
    HASH_FIND_INT(hashtable, &ikey, tmp);
    return tmp;
}

void insert(int ikey, int ival) {
    struct hashTable* it = find(ikey);
    if (it == NULL) {
        struct hashTable* tmp = malloc(sizeof(struct hashTable));
        tmp->key = ikey, tmp->val = ival;
        HASH_ADD_INT(hashtable, key, tmp);
    } else {
        it->val = ival;
    }
}

int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
    hashtable = NULL;
    for (int i = 0; i < numsSize; i++) {
        struct hashTable* it = find(target - nums[i]);
        if (it != NULL) {
            int* ret = malloc(sizeof(int) * 2);
            ret[0] = it->val, ret[1] = i;
            *returnSize = 2;
            return ret;
        }
        insert(nums[i], i);
    }
    *returnSize = 0;
    return NULL;
}
--------------------------------------------------------
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> hashtable;
        for (int i = 0; i < nums.size(); ++i) {
            auto it = hashtable.find(target - nums[i]);
            if (it != hashtable.end()) {
                return {it->second, i};
            }
            hashtable[nums[i]] = i;
        }
        return {};
    }
};

167. Sum of two II - input ordered array

Given an integer array numbers that has been arranged in non decreasing order, please find out that the sum of the two numbers in the array is equal to the target number target.

The function should return the subscript values of these two numbers as an array of integers of length 2. The subscript of numbers starts counting from 1, so the answer array should meet 1 < = answer [0] < answer [1] < = numbers.length.

You can assume that each input only corresponds to a unique answer, and you can't reuse the same elements.

Example 1:

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: the sum of 2 and 7 is equal to the target number 9. So index1 = 1, index2 = 2.
Example 2:

Input: numbers = [2,3,4], target = 6
Output: [1,3]
Example 3:

Input: numbers = [-1,0], target = -1
Output: [1,2]

Tips:

2 <= numbers.length <= 3 * 104
-1000 <= numbers[i] <= 1000
numbers are in non decreasing order
-1000 <= target <= 1000
Only one valid answer exists

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-r5rm0vqn-1631407998748)( https://raw.githubusercontent.com/xkyvvv/blogpic/main/pic1/image-20210905124055785.png )]

int* twoSum(int* numbers, int numbersSize, int target, int* returnSize) {
    int* ret = (int*)malloc(sizeof(int) * 2);
    *returnSize = 2;

    for (int i = 0; i < numbersSize; ++i) {
        int low = i + 1, high = numbersSize - 1;
        while (low <= high) {
            int mid = (high - low) / 2 + low;
            if (numbers[mid] == target - numbers[i]) {
                ret[0] = i + 1, ret[1] = mid + 1;
                return ret;
            } else if (numbers[mid] > target - numbers[i]) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
    }
    ret[0] = -1, ret[1] = -1;
    return ret;
}

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

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-91dzsjvx-1631407998749)( https://raw.githubusercontent.com/xkyvvv/blogpic/main/pic1/image-20210905124236932.png )]

int* twoSum(int* numbers, int numbersSize, int target, int* returnSize) {
    int* ret = (int*)malloc(sizeof(int) * 2);
    *returnSize = 2;

    int low = 0, high = numbersSize - 1;
    while (low < high) {
        int sum = numbers[low] + numbers[high];
        if (sum == target) {
            ret[0] = low + 1, ret[1] = high + 1;
            return ret;
        } else if (sum < target) {
            ++low;
        } else {
            --high;
        }
    }
    ret[0] = -1, ret[1] = -1;
    return ret;
}

--------------------------------------------------------------------
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};
    }
};

189. Rotate array

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-tbekvwbv-1631407998749)( https://raw.githubusercontent.com/xkyvvv/blogpic/main/pic1/image-20210905124531668.png )]

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-0ufkechv-1631407998750)( https://raw.githubusercontent.com/xkyvvv/blogpic/main/pic1/image-20210905124703619.png )]

void rotate(int* nums, int numsSize, int k) {
    int newArr[numsSize];
    for (int i = 0; i < numsSize; ++i) {
        newArr[(i + k) % numsSize] = nums[i];
    }
    for (int i = 0; i < numsSize; ++i) {
        nums[i] = newArr[i];
    }
}

-------------------------------------------------------------------------
    
class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        int n = nums.size();
        vector<int> newArr(n);
        for (int i = 0; i < n; ++i) {
            newArr[(i + k) % n] = nums[i];
        }
        nums.assign(newArr.begin(), newArr.end());
    }
};

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-y2feznwz-1631407998750)( https://raw.githubusercontent.com/xkyvvv/blogpic/main/pic1/image-20210905125247112.png )]

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-nrqskmcm-1631407998751)( https://raw.githubusercontent.com/xkyvvv/blogpic/main/pic1/image-20210905125306721.png )]

int gcd(int a, int b) {
    return b ? gcd(b, a % b) : a;
}

void swap(int* a, int* b) {
    int t = *a;
    *a = *b, *b = t;
}

void rotate(int* nums, int numsSize, int k) {
    k = k % numsSize;
    int count = gcd(k, numsSize);
    for (int start = 0; start < count; ++start) {
        int current = start;
        int prev = nums[start];
        do {
            int next = (current + k) % numsSize;
            swap(&nums[next], &prev);
            current = next;
        } while (start != current);
    }
}

--------------------------------------------------------
class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        int n = nums.size();
        k = k % n;
        int count = gcd(k, n);
        for (int start = 0; start < count; ++start) {
            int current = start;
            int prev = nums[start];
            do {
                int next = (current + k) % n;
                swap(nums[next], prev);
                current = next;
            } while (start != current);
        }
    }
};


[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-1hgasqsg-1631407998751)( https://raw.githubusercontent.com/xkyvvv/blogpic/main/pic1/image-20210905125410121.png )]

void swap(int* a, int* b) {
    int t = *a;
    *a = *b, *b = t;
}

void reverse(int* nums, int start, int end) {
    while (start < end) {
        swap(&nums[start], &nums[end]);
        start += 1;
        end -= 1;
    }
}

void rotate(int* nums, int numsSize, int k) {
    k %= numsSize;
    reverse(nums, 0, numsSize - 1);
    reverse(nums, 0, k - 1);
    reverse(nums, k, numsSize - 1);
}

----------------------------------------------------------------------
class Solution {
public:
    void reverse(vector<int>& nums, int start, int end) {
        while (start < end) {
            swap(nums[start], nums[end]);
            start += 1;
            end -= 1;
        }
    }

    void rotate(vector<int>& nums, int k) {
        k %= nums.size();
        reverse(nums, 0, nums.size() - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, nums.size() - 1);
    }
};

581. Shortest unordered continuous subarray

bool is_sorted(int* arr, int arrSize) {
    for (int i = 1; i < arrSize; i++) {
        if (arr[i - 1] > arr[i]) {
            return false;
        }
    }
    return true;
}

int cmp(int* a, int* b) {
    return *a - *b;
}

int findUnsortedSubarray(int* nums, int numsSize) {
    if (is_sorted(nums, numsSize)) {
        return 0;
    }
    int numsSorted[numsSize];
    memcpy(numsSorted, nums, sizeof(int) * numsSize);
    qsort(numsSorted, numsSize, sizeof(int), cmp);
    int left = 0;
    while (nums[left] == numsSorted[left]) {
        left++;
    }
    int right = numsSize - 1;
    while (nums[right] == numsSorted[right]) {
        right--;
    }
    return right - left + 1;
}

--------------------------------------------------------------------------
class Solution {
public:
    int findUnsortedSubarray(vector<int>& nums) {
        if (is_sorted(nums.begin(), nums.end())) {
            return 0;
        }
        vector<int> numsSorted(nums);
        sort(numsSorted.begin(), numsSorted.end());
        int left = 0;
        while (nums[left] == numsSorted[left]) {
            left++;
        }
        int right = nums.size() - 1;
        while (nums[right] == numsSorted[right]) {
            right--;
        }
        return right - left + 1;
    }
};


[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-vqnemk5f-1631407998753)( https://raw.githubusercontent.com/xkyvvv/blogpic/main/pic1/image-20210905125940251.png )]

int findUnsortedSubarray(int* nums, int numsSize) {
    int n = numsSize;
    int maxn = INT_MIN, right = -1;
    int minn = INT_MAX, left = -1;
    for (int i = 0; i < n; i++) {
        if (maxn > nums[i]) {
            right = i;
        } else {
            maxn = nums[i];
        }
        if (minn < nums[n - i - 1]) {
            left = n - i - 1;
        } else {
            minn = nums[n - i - 1];
        }
    }
    return right == -1 ? 0 : right - left + 1;
}

--------------------------------------------------------------------------
class Solution {
public:
    int findUnsortedSubarray(vector<int>& nums) {
        int n = nums.size();
        int maxn = INT_MIN, right = -1;
        int minn = INT_MAX, left = -1;
        for (int i = 0; i < n; i++) {
            if (maxn > nums[i]) {
                right = i;
            } else {
                maxn = nums[i];
            }
            if (minn < nums[n - i - 1]) {
                left = n - i - 1;
            } else {
                minn = nums[n - i - 1];
            }
        }
        return right == -1 ? 0 : right - left + 1;
    }
};

For the time being

For the problems related to arrays, we need to start to do them as a similar mathematical problem. First, we have ideas and general problem-solving steps, and then we can find out what methods we need to use between each step (dichotomy, double pointer).

Topics: Algorithm data structure leetcode