当前位置:网站首页>7.2刷题两个
7.2刷题两个
2022-07-03 07:11:00 【就一个挺垃圾的跑路人】
三个数的最大乘积
排序
排序后分情况处理
- 当全为负数或正数时,我们只要选择最大的后三位数相乘即可.
- 只有一个负数时-直接用后三位相乘即可.
- 当负数个数有但还是有三个正数时.分为两种情况两者中取最大值.
- 用两个负数的最小值于一个整数的最大值相乘
- 用三个整数相乘
- 当负数个数多到无法拥有三个整正数时
- 用两个负数的最小值于一个整数的最大值相乘
在上面情况中可以看出3情况是判断最多的.但是情况3是的取最大值是可以兼容到124的所以其实我们只需要判断出
- 负数中的最小值和次小值(也是整体最小值)和最大值相乘
- 最大值,次大值,次次大值相乘
上面两种情况那个情况的值最大即可.
class Solution {
public:
int maximumProduct(vector<int>& nums)
{
sort(nums.begin(),nums.end());
int s = nums.size()-1;
return max(nums[0]*nums[1]*nums[s],nums[s]*nums[s-1]*nums[s-2]);//一共只有两种情况是我们想要的答案直接返回最大即可.
}
};
线性扫描
思路和上题类似但是我们不通过排序来得到值了,我们通过线性扫描来得到.
class Solution {
public:
int maximumProduct(vector<int>& nums)
{
int min1 = INT_MAX,min2 = INT_MAX;//min1为最小值min2为最大值
int max1 = INT_MIN,max2 = INT_MIN,max3 = INT_MIN;//max1是最大值.....
for(int i =0;i<nums.size();i++)
{
if(nums[i]<min1)
{
min2 = min1;//让min2是次小值
min1 = nums[i];//min1是最小值
}
else if(nums[i]<min2)
{
min2 = nums[i];
}
if(nums[i]>max1)
{
max3 = max2;
max2 = max1;
max1 = nums[i];
}
else if(nums[i]>max2)
{
max3 = max2;
max2 = nums[i];
}
else if(nums[i]>max3)
{
max3 = nums[i];
}
}
return max(min1*min2*max1,max1*max2*max3);//和上面的思路类似只是这些值不来自排序了
}
};
有多少小于当前数字的数字
哈希思想
标注一下:本人并没有学过哈希,这个标题的哈希思想其实也就是本人在经过几次刷题都说这种是哈希思想所以有此标题
思路:
把数组(数组1及给定的数组)的数字放在另一个数组(我成为数组2)中,将他的值转化为数组2的下标位置,并用数组2记录他的出现次数.
然后我们只需要把对应数组1的值转换到数组2中,把数组二对应下标的前面的下标的内容加上即可.
比如数组1中有元素8,我们就只需要将数组2中的前八个下标值相加(0,1,2,3,4,5,6,7).
class Solution {
public:
vector<int> smallerNumbersThanCurrent(vector<int>& nums)
{
vector<int> ret(nums.size());
int arr[101] = {
0};//利用哈希思想
for(int i = 0;i<nums.size();i++)
{
arr[nums[i]]++;
}
for(int i =0;i<nums.size();i++)
{
int tmp =0;
for(int j =0;j<nums[i];j++)
{
tmp += arr[j];
}
ret[i] = tmp;
}
return ret;
}
};
边栏推荐
猜你喜欢
How to migrate or replicate VMware virtual machine systems
Sorting out the core ideas of the pyramid principle
Summary of abnormal mechanism of interview
Jenkins
Software testing learning - day one
2022-06-23 VGMP-OSPF-域間安全策略-NAT策略(更新中)
[HCAI] learning summary OSI model
MySQL installation
3311. Longest arithmetic
Inno setup production and installation package
随机推荐
[set theory] equivalence classes (concept of equivalence classes | examples of equivalence classes | properties of equivalence classes | quotient sets | examples of quotient sets)*
Common APIs
Software testing assignment - day 3
Discussion on some problems of array
Thoughts in Starbucks
Advanced API (byte stream & buffer stream)
JMeter JSON extractor extracts two parameters at the same time
TypeScript let与var的区别
“百度杯”CTF比赛 2017 二月场,Web:爆破-1
深度学习参数初始化(一)Xavier初始化 含代码
Advanced API (local simulation download file)
10000小时定律不会让你成为编程大师,但至少是个好的起点
php artisan
Hands on redis master-slave replication, sentinel master-slave switching, cluster sharding
Advanced API (serialization & deserialization)
Shim and Polyfill in [concept collection]
JS date comparison
JMeter test result output
高并发内存池
Redis command