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;
}
};
相關文章
- [LeetCode] 1343. Number of Sub-arrays of Size K and Average Greater than or Equal to ThresholdLeetCode
- HDU1213-How Many Tables
- coca How many 搭配 大寫
- LeetCode 259. Three Sum SmallerLeetCode
- 【Leetcode】1689. Partitioning Into Minimum Number Of Deci-Binary Numbers(配數學證明)LeetCode
- How Oracle Store Number internal(zt)Oracle
- HDU 2157 How many ways?? (矩陣快速冪)矩陣
- Leetcode 165 Compare Version NumbersLeetCode
- LeetCode 2 Add Two NumbersLeetCode
- Leetcode Number of islandsLeetCode
- LeetCode-2 Add Two NumbersLeetCode
- Leetcode 967 Numbers With Same Consecutive DifferencesLeetCode
- LeetCode 2. Add Two NumbersLeetCode
- Leetcode 447 Number of BoomerangsLeetCodeOOM
- [LeetCode] Third Maximum NumberLeetCode
- [LeetCode] Find the Duplicate NumberLeetCode
- Leetcode 9 Palindrome NumberLeetCode
- LeetCode 129. Sum Root to Leaf NumbersLeetCode
- Leetcode 933 Number of Recent CallsLeetCode
- [LeetCode] 9. Palindrome NumberLeetCode
- LeetCode之Fibonacci Number(Kotlin)LeetCodeKotlin
- LeetCode之Sum of Even Numbers After Queries(Kotlin)LeetCodeKotlin
- LeetCode 448. Find All Numbers Disappeared in an ArrayLeetCodeAPP
- [LeetCode] 2275. Largest Combination With Bitwise AND Greater Than ZeroLeetCode
- 【Leetcode】1395. Count Number of TeamsLeetCode
- Leetcode 137. Single Number IILeetCode
- Leetcode 611 javascript Valid Triangle NumberLeetCodeJavaScript
- LeetCode之Number of Recent Calls(Kotlin)LeetCodeKotlin
- [LeetCode] 248. Strobogrammatic Number IIILeetCode
- [LeetCode] 191. Number of 1 BitsLeetCode
- [LeetCode] 305. Number of Islands IILeetCode
- Leetcode 17 Letter Combinations of a Phone NumberLeetCode
- LeetCode2: Add two numbers(兩數相加)LeetCode
- Leetcode 1375. Bulb Switcher III (python+cpp)LeetCodePython
- Leetcode 1366. Rank Teams by Votes (python+cpp)LeetCodePython
- [LeetCode] 2684. Maximum Number of Moves in a GridLeetCode
- [LeetCode] 3238. Find the Number of Winning PlayersLeetCode
- LeetCode Palindrome Number(009)解法總結LeetCode