You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].
Example:
Given nums = [5, 2, 6, 1]
To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.
accepted
Example:
Given nums = [5, 2, 6, 1]
To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.
Return the array [2, 1, 1, 0].
尼玛,这不就是算积分图嘛
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<vector>
#include<iostream>
using namespace std;
class NumMatrix {
private:
vector<vector<int>>regionsum;
public:
NumMatrix(vector<vector<int>> &matrix) {
regionsum.resize(matrix.size()+1);
if(matrix.empty())
return;
for(int i=0;i<matrix.size()+1;i++)
regionsum[i].resize(matrix[0].size()+1);
for(int i=1;i<matrix.size()+1;i++)
for(int j=1;j<matrix[0].size()+1;j++)
{
regionsum[i][j]=regionsum[i-1][j]+regionsum[i][j-1]-regionsum[i-1][j-1]+matrix[i-1][j-1];
}
}
int sumRegion(int row1, int col1, int row2, int col2) {
if(regionsum.size()==1)
return 0;
if(regionsum[0].size()==1)
return 0;
if(row2>=regionsum.size()-1)
row2=regionsum.size()-2;
if(col2>=regionsum[0].size()-1)
col2=regionsum[0].size()-2;
if(row1<0)
row1=0;
if(col1<0)
col1=0;
return regionsum[row2+1][col2+1]+regionsum[row1][col1]-regionsum[row2+1][col1]-regionsum[row1][col2+1];
}
};
int _tmain(int argc, _TCHAR* argv[])
{
vector<vector<int>>matrix;
vector<int>aa;
//aa.push_back(5);
//matrix.push_back(aa);
NumMatrix numMatrix(matrix);
cout<<numMatrix.sumRegion(0, 0, 2, 3);
system("pause");
return 0;
}
accepted