1.距离相等的条形码
在一个仓库里,有一排条形码,其中第 i
个条形码为 barcodes[i]
。
请你重新排列这些条形码,使其中任意两个相邻的条形码不能相等。 你可以返回任何满足该要求的答案,此题保证存在答案。
题目要求任意两个相邻的条形码不能相等,所以可以采用贪心算法优先选择出现次数最多的条形码进行排列,首先用一个哈希表记录元素出现的次数,然后依次将这些元素(剩余数量,元素值)放入最大堆中,每次从堆顶中选出剩余数量最多的元素放入数组中,如果这个元素和数组最后一个元素相同,就选择剩余数量第二多的元素放入数组中,之后再把这两个元素剩余数量减一后放入堆中(为0则不再放入)。重复操作直到堆中不再有元素。
vector<int> rearrangeBarcodes(vector<int>& barcodes) {
unordered_map<int ,int>count;
for(int i=0;i<barcodes.size();i++){
count[barcodes[i]]++;
}
priority_queue<pair<int, int>> q;
auto it=count.begin();
for(;it!=count.end();it++){
q.push({it->second,it->first})
}
vector<int>res;
while(q.size()){
auto [cx, x] = q.top();
q.pop();
if (res.empty() || res.back() != x) {
res.push_back(x);
if (cx > 1) {
q.push({cx - 1, x});
}
} else {
if (q.size() < 1) return res;
auto [cy, y] = q.top();
q.pop();
res.push_back(y);
if (cy > 1) {
q.push({cy - 1, y});
}
q.push({cx, x});
}
}
return res;
}
2.搜索插入位置
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
请必须使用时间复杂度为 O(log n)
的算法。
使用二分查找法即可
int searchInsert(vector<int>& nums, int target){
int n=nums.size();
int start=0;
int end=n-1;
int ans=n;//返回位置
while(start<=end){
int mid=(start+end)/2;
if(nums[mid]<target){
start=mid+1;
}else{
ans=mid;
end=mid-1;
}
}
return ans;
}
3.跳跃游戏
给定一个长度为 n
的 0 索引整数数组 nums
。初始位置为 nums[0]
。
每个元素 nums[i]
表示从索引 i
向前跳转的最大长度。换句话说,如果你在 nums[i]
处,你可以跳转到任意 nums[i + j]
处:
0 <= j <= nums[i]
i + j < n
返回到达 nums[n - 1]
的最小跳跃次数。生成的测试用例可以到达 nums[n - 1]
。
int jump(vector<int>& nums) {
int maxn=0;
int n=nums.size();
int times=0;
int end=0;
for(int i=0;i<n-1;i++){
if(maxn>=i)
{
maxn=max(maxn,i+nums[i]);
}
if(i==end){
end=maxn;
times++;
}
}
return times;
}
利用贪心算法,首先算出当前位置所能到达的最大边界,正向遍历,当到达最大边界时,更新途中经过的点所能到达的最大位置为最大边界,并使跳跃次数+1;
4.Pow(x,n)
实现 pow(x, n) ,即计算 x
的整数 n
次幂函数(即,xn
)。
使用快速幂+递归的算法
double quickMul(double x, long long N) {
if (N == 0) {
return 1.0;
}
double y = quickMul(x, N / 2);
return N % 2 == 0 ? y * y : y * y * x;
}
double myPow(double x, int n) {
long long N = n;
return N >= 0 ? quickMul(x, N) : 1.0 / quickMul(x, -N);
}