Given the array
Return the answer in an array.
Solution in C++:
vector<int> smallerNumbersThanCurrent(vector<int>& nums) {
int count[101] = {0};
int vect_size = nums.size();
for(int iter = 0; iter < vect_size; ++iter){
++count[nums.at(iter)];
}
int temp_count = 0;
bool first_one = true;
for(int iter = 0; iter < 101; ++iter){
//Case: Count is not equal to -1
if(count[iter] != 0){
if(first_one){
first_one = false;
temp_count = count[iter];
count[iter] = 0;
continue;
}
int temp = 0 ;
temp = count[iter];
count[iter] = temp_count;
temp_count += temp;
}
}
vector <int> ret;
for(auto iter = 0; iter < vect_size; ++iter){
ret.push_back(count[nums.at(iter)]);
}
return ret;
}
nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i].Return the answer in an array.
Input: nums = [8,1,2,2,3] Output: [4,0,1,1,3]
Solution in C++:
vector<int> smallerNumbersThanCurrent(vector<int>& nums) {
int count[101] = {0};
int vect_size = nums.size();
for(int iter = 0; iter < vect_size; ++iter){
++count[nums.at(iter)];
}
int temp_count = 0;
bool first_one = true;
for(int iter = 0; iter < 101; ++iter){
//Case: Count is not equal to -1
if(count[iter] != 0){
if(first_one){
first_one = false;
temp_count = count[iter];
count[iter] = 0;
continue;
}
int temp = 0 ;
temp = count[iter];
count[iter] = temp_count;
temp_count += temp;
}
}
vector <int> ret;
for(auto iter = 0; iter < vect_size; ++iter){
ret.push_back(count[nums.at(iter)]);
}
return ret;
}
Comments
Post a Comment