classSolution { public: //插入排序法,小數量很穩 voidinsertSort(vector<int>& nums,int left , int right) { for(int i = left + 1; i <= right; i++) { int val = nums[i]; int j = i - 1; while(j >= left && nums[j] > val) { nums[j+1] = nums[j]; j--; } nums[j+1] = val; } }
//MergeSort,看網上TimSort資料這邊也有優化,似乎把一個一個檢查改成跳幾個檢查 voidmerge(vector<int>& nums,vector<int>& cpyBuff,int left , int mid , int right) { int leftn = 0,rightn; for(int i = left; i <= mid; i++) { cpyBuff[leftn] = nums[i]; leftn++; }
vector<int> sortArray(vector<int>& nums) { int n = nums.size(); int run = 32; //分割大小,稱為Run for(int i = 0 ; i < n; i += run) insertSort(nums,i,std::min(n - 1 , i + run - 1));
int cpySize = run; while(cpySize < n) { cpySize *= 2; } cpySize = cpySize >> 1; std::vector<int> cpyBuff(cpySize); for(int size = run; size < n ; size *= 2) { for(int i = 0; i < n; i += size * 2) { int mid = i + size - 1; if(mid >= n) continue; int right = std::min(n - 1 , mid + size);
You are given two arrays rowSum and colSum of non-negative integers where rowSum[i] is the sum of the elements in the ith row and colSum[j] is the sum of the elements of the jth column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column.
Find any matrix of non-negative integers of size rowSum.length x colSum.length that satisfies the rowSum and colSum requirements.
Return a 2D array representing any matrix that fulfills the requirements. It’s guaranteed that at least one matrix that fulfills the requirements exists.
Example 1:
Input: rowSum = [3,8], colSum = [4,7] Output: [[3,0], [1,7]] Explanation: 0th row: 3 + 0 = 3 == rowSum[0] 1st row: 1 + 7 = 8 == rowSum[1] 0th column: 3 + 1 = 4 == colSum[0] 1st column: 0 + 7 = 7 == colSum[1] The row and column sums match, and all matrix elements are non-negative. Another possible matrix is: [[1,2], [3,5]] Example 2:
Hint 1 Find the smallest rowSum or colSum, and let it be x. Place that number in the grid, and subtract x from rowSum and colSum. Continue until all the sums are satisfied.