LeetCode 338
给你一个整数 n
,对于 0 <= i <= n
中的每个 i
,计算其二进制表示中 1
的个数 ,返回一个长度为 n + 1
的数组 ans
作为答案。
示例 1:
输入:n = 2 输出:[0,1,1] 解释: 0 --> 0 1 --> 1 2 --> 10
示例 2:
输入:n = 5 输出:[0,1,1,2,1,2] 解释: 0 --> 0 1 --> 1 2 --> 10 3 --> 11 4 --> 100 5 --> 101
提示:
0 <= n <= 105
思路:
短除法。
代码:
class Solution {
public:
int count(int x)
{
int ans=0;
while(x)
{
if(x%2==1)ans++;
x=x/2;
}
return ans;
}
vector<int> countBits(int n) {
vector<int> v;
for(int i=0;i<=n;i++)
{
v.push_back(count(i));
}
return v;
}
};
LeetCode347
给你一个整数数组 nums
和一个整数 k
,请你返回其中出现频率前 k
高的元素。你可以按 任意顺序 返回答案。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2 输出: [1,2]
示例 2:
输入: nums = [1], k = 1 输出: [1]
提示:
1 <= nums.length <= 105
k
的取值范围是[1, 数组中不相同的元素的个数]
- 题目数据保证答案唯一,换句话说,数组中前
k
个高频元素的集合是唯一的
进阶:你所设计算法的时间复杂度 必须 优于 O(n log n)
,其中 n
是数组大小。
思路:
STL大法好!
代码:
class Solution {
public:
unordered_map<int,int> m;
vector<int> topKFrequent(vector<int>& nums, int k) {
vector<int> v;
for(int i=0;i<nums.size();i++)
{
m[nums[i]]++;
}
priority_queue<pair<int,int>> pq;
for (auto it : m) pq.emplace(it.second,it.first);
while(k--)
{
v.push_back(pq.top().second);
pq.pop();
}
return v;
}
};
LeetCode394
给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string]
,表示其中方括号内部的 encoded_string
正好重复 k
次。注意 k
保证为正整数。
你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k
,例如不会出现像 3a
或 2[4]
的输入。
示例 1:
输入:s = "3[a]2[bc]" 输出:"aaabcbc"
示例 2:
输入:s = "3[a2[c]]" 输出:"accaccacc"
示例 3:
输入:s = "2[abc]3[cd]ef" 输出:"abcabccdcdcdef"
示例 4:
输入:s = "abc3[cd]xyz" 输出:"abccdcdcdxyz"
提示:
1 <= s.length <= 30
s
由小写英文字母、数字和方括号'[]'
组成s
保证是一个 有效 的输入。s
中所有整数的取值范围为[1, 300]
思路:
感觉自己的写法有点暴力的。。
不断从栈中读取,然后乘起来再压入栈。
代码:
class Solution {
public:
string decodeString(string s) {
stack<int> s1;
stack<char> s2;
int num;
for(int i=0;i<s.length();)
{
if(s[i]==']'){
string t="";
while(s2.top()!='['){
t=s2.top()+t;
s2.pop();
}
s2.pop();
int k=s1.top();
s1.pop();
string g="";
while(k>0)
{
g=g+t;
k--;
}
for(int j=0;j<g.length();j++){
s2.push(g[j]);
}
i++;
}
else if(s[i]>='0'&&s[i]<='9'){
num=0;
while(s[i]>='0'&&s[i]<='9'){
num=num*10+(s[i]-'0');
i++;
}
s1.push(num);
}
else if(s[i]=='['){
s2.push(s[i]);
i++;
}
else {
s2.push(s[i]);
i++;
}
}
string t="";
while(s2.size())
{
t=s2.top()+t;
s2.pop();
}
return t;
}
};