2026年3月6日 星期五

378. Kth Smallest Element in a Sorted Matrix

難度: Middle

類型: Array,Binary Search,Sorting,Heap (Priority Queue),Matrix,
CPP程式下載: 378.cpp

Topic:

Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the kth smallest element in the matrix.

Note that it is the kth smallest element in the sorted order, not the kth distinct element.

You must find a solution with a memory complexity better than O(n2).

 

Example 1:

Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
Output: 13
Explanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13

Example 2:

Input: matrix = [[-5]], k = 1
Output: -5

 

Constraints:

  • n == matrix.length == matrix[i].length
  • 1 <= n <= 300
  • -109 <= matrix[i][j] <= 109
  • All the rows and columns of matrix are guaranteed to be sorted in non-decreasing order.
  • 1 <= k <= n2

 

Follow up:

  • Could you solve the problem with a constant memory (i.e., O(1) memory complexity)?
  • Could you solve the problem in O(n) time complexity? The solution may be too advanced for an interview but you may find reading this paper fun.
Consideration:
1. No create new vector or multiset to save memory.
2. Binary search to save time/complexity. (mid value from left-smallest to right-largest)
3. left-upper corner is the smallest value, and right-bottom corner is the largest value.
4. When [left to middle] number counts are more than k, k smallest value is in the [left to middle] part. otherwise, it would be in the [middle+1 to right] part.
5. When matrix[i][j] < middle, it means all element at matrix(i, 0~j) will be less than middle. Then you may check next column matrix(i+1, 0~j).

Code:
class Solution {
public:
    int kthSmallest(vector<vector<int>>& matrix, int k) {
int n = matrix[0].size();
cout << "n = " << n << "\n";
        int left = matrix[0][0];
        int right = matrix[n-1][n-1];
        int mid;
        while (left<right)
        {
            mid = (left + right)>>1;
            if (left_check(matrix, mid, k, n))
            {
                right = mid;
            }
            else
            {
                left = mid + 1;
            }
        }
return left;
    }

private:
    bool left_check(vector<vector<int>>& matrix, int mid, int k, int n)
    {
        int count=0;
        int i=n-1;
        int j=0;

        while ((j<n) && (i>=0))
        {
            if (mid>=matrix[i][j])
            {
                count+=(i+1);
                ++j;
            }
            else
                --i;
        }
        return count >= k;
    }
};

Result:
Accepted
87 / 87 testcases passed
tendchen
tendchen
submitted at Mar 06, 2026 15:32
Runtime
0ms
Beats100.00%
Memory
17.06MB
Beats80.01%


2026年3月3日 星期二

977. Squares of a Sorted Array

 難度: Easy

類型: Array,Two Pointers,Sorting 
CPP程式下載: 977.cpp

Topic:

Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.

 

Example 1:

Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Explanation: After squaring, the array becomes [16,1,0,9,100].
After sorting, it becomes [0,1,9,16,100].

Example 2:

Input: nums = [-7,-3,2,3,11]
Output: [4,9,9,49,121]

 

Constraints:

  • 1 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • nums is sorted in non-decreasing order.
Consideration:
Integer has negative and positive integer. The larger element square should be located in the most left or most right position in a sorted vector. So, two pointers to check the most left and right elements. It could achieve O(n) complexity level.

Code:
class Solution {
public:
    vector<int> sortedSquares(vector<int>& nums) {
        int num = nums.size();
        //cout << "num = " << num << "\n";
        //if (num==0) return nullptr;
        vector<int> output_nums(nums);
        int i=0, j=num-1, k=num-1, x2, y2;

        for (;k>=0;k--)
        {
            if (j>=i)
            {
                x2 = nums.at(i) * nums.at(i);
                y2 = nums.at(j) * nums.at(j);
                if (y2 >= x2)
                {
                    output_nums.at(k) = y2;
                    j--;
                }
                else
                {
                    output_nums.at(k) = x2;
                    i++;
                }
            }
        }
        return output_nums;
    }
};

Result:
Accepted
137 / 137 testcases passed
tendchen
tendchen
submitted at Mar 03, 2026 21:53
Runtime
0ms
Beats100.00%
Analyze Complexity
Memory
30.27MB
Beats65.21%
Analyze Complexity