Leetcode 1365. How Many Numbers Are Smaller Than the Current Number (cpp)
題目
解法1:暴力
class Solution {
public:
vector<int> smallerNumbersThanCurrent(vector<int>& nums) {
vector<int> ans;
int count;
for(int i=0;i<nums.size();i++){
count = 0;
for(int j=0;j<nums.size();j++){
if(nums[j] < nums[i]) count++;
}
ans.push_back(count);
}
return ans;
}
};
解法2:hashtable
這道easy題最開始居然沒有想到這個解法
利用一個hashtable,key是數字,value是他在排序後在陣列中位置,不包括他自己在內,所以比他小的剛好等於他的index。因為有重複的數字,所以只記下她第一次出現的時候即可。當然也可以把重複數字刪掉
class Solution {
public:
vector<int> smallerNumbersThanCurrent(vector<int>& nums) {
vector<int> tmp = nums;
sort(nums.begin(),nums.end());
unordered_map<int,int> seen;
for(int i=0;i<nums.size();i++){
// only count it for the first time this number appeared
if(seen.find(nums[i]) == seen.end()){
seen[nums[i]] = i;
}
}
vector<int> ans;
for(auto num:tmp){
ans.push_back(seen[num]);
}
return ans;
}
};
相關文章
- Archived redolog is (significant) smaller than the redologfileHiveNifi
- Why AlloyFinger is so much smaller than hammerjs?JS
- 【REDO】Archived redolog is (significant) smaller than the redologfileHiveNifi
- Archived redolog is (significant) smaller than the redologfile_1356604.1HiveNifi
- LeetCode-3Sum SmallerLeetCode
- google2016面試題-count of smaller numbers after selfGo面試題
- How To Efficiently Drop A Table With Many Extents
- coca How many 搭配 大寫
- 【SQLSERVER】How to check current pool sizeSQLServer
- How to find Current open Cursors in OracleOracle
- LeetCode 259. Three Sum SmallerLeetCode
- [doc]How To Efficiently Drop A Table With Many Extents
- How to Convert Decimal Numbers to Words with PythonDecimalPython
- Oracle ASM How many allocation units per fileOracleASM
- Leetcode - Bitwise AND of Numbers RangeLeetCode
- LeetCode-Lexicographical NumbersLeetCode
- How Oracle Store Number internal(zt)Oracle
- HDU 1213 How Many Tables(並查集)並查集
- LeetCode-Bitwise AND of Numbers RangeLeetCode
- Leetcode Sum Root to Leaf NumbersLeetCode
- Leetcode Add Two NumbersLeetCode
- How to check whether the current database in using Oracle optionsDatabaseOracle
- How Oracle Store Number internal?(轉載)Oracle
- 【Leetcode】1689. Partitioning Into Minimum Number Of Deci-Binary Numbers(配數學證明)LeetCode
- HDU 2157 How many ways?? (矩陣快速冪)矩陣
- 動態規劃 hdu 1978 How many ways動態規劃
- How to make an IntelliJ IDEA plugin in less than 30 minutesIntelliJIdeaPlugin
- LeetCode 2 Add Two NumbersLeetCode
- Leetcode-Add Two NumbersLeetCode
- Sum Root to Leaf Numbers leetcode javaLeetCodeJava
- Add Two Numbers leetcode javaLeetCodeJava
- Leetcode Number of islandsLeetCode
- LeetCode:Largest NumberLeetCode
- Leetcode 165 Compare Version NumbersLeetCode
- Leetcode 967 Numbers With Same Consecutive DifferencesLeetCode
- LeetCode-2 Add Two NumbersLeetCode
- LeetCode 2. Add Two NumbersLeetCode
- Leetcode[421] Maximum XOR of Two Numbers in an ArrayLeetCode