啦啦啦,我是刘天昊,那么今天来分享一道简单的题目,主要想和大家谈谈如何去加速自己的代码
先看题目
Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the sister could gain.
Example 1:
Input: candies = [1,1,2,2,3,3] Output: 3 Explanation: There are three different kinds of candies (1, 2 and 3), and two candies for each kind. Optimal distribution: The sister has candies [1,2,3] and the brother has candies [1,2,3], too. The sister has three different kinds of candies.
Example 2:
Input: candies = [1,1,2,3] Output: 2 Explanation: For example, the sister has candies [2,3] and the brother has candies [1,1]. The sister has two different kinds of candies, the brother has only one kind of candies.
Note:
- The length of the given array is in range [2, 10,000], and will be even.
- The number in given array is in range [-100,000, 100,000].
好,我们开始思考如何解决这个问题,假设这个数组排好序,那么我们只要处理不重复的数字就能保证女性朋友可以得到更多种类的糖果
so我们先对数组排好序,处理没有重复的数字,判断是否超过数字的一半(均分嘛,不能太贪心)
so 核心,快排序,res记录结果po上代码
void QuickSort(int *nums,int left,int right)
{
int point=nums[left];
int i=left;
int j=right;
if(i>j)
{
return ;
}
while(i!=j)
{
while(nums[j]>=point&&i<j)
{
j--;
}
while(nums[i]<=point&&i<j)
{
i++;
}
if(i<j)
{
nums[i]=nums[i]^nums[j];
nums[j]=nums[i]^nums[j];
nums[i]=nums[i]^nums[j];
}
}
nums[left]=nums[i];
nums[i]=point;
QuickSort(nums,left,i-1);
QuickSort(nums,i+1,right);
}
int distributeCandies(int* candies, int candiesSize)
{
int num=candiesSize/2;
int res=0;
QuickSort(candies,0,candiesSize-1);
res++;
for(int i=1;i<candiesSize;i++)
{
if(candies[i-1]!=candies[i])
{
res++;
}
}
if(res>=num)
{
return num;
}
else
{
return res;
}
return 0;
}
运行325ms,果然很慢,毕竟我们的时间复杂度是nlogn。
开始考虑我们如何去优化这个算法呢,好我们如何去处理乱序的重复问题,fine,hash表查找啊。
greet我们把问题缩减到了O(n)po上代码
int distributeCandies(int* candies, int candiesSize)
{
int hash[200000];
memset(hash,0,sizeof(hash));
int num=candiesSize/2;
int res=0;
for(int i=0;i<candiesSize;i++)
{
if(candies[i]<0)
{
hash[candies[i]+200000]++;
if(hash[candies[i]+200000]==1)
{
res++;
}
}
else
{
hash[candies[i]]++;
if(hash[candies[i]]==1)
{
res++;
}
}
}
if(res>=num)
{
return num;
}
else
{
return res;
}
return 0;
}
96ms,好极了我们现在从打败5%到打败80%了,但是我们很贪心,再来思考如何去加速这个算法
ok,当res大于一半的时候我们是不用继续走程序了所以把判断加到循环里面去早点终结这个循环是个不错的主意
int distributeCandies(int* candies, int candiesSize)
{
int hash[200000];
memset(hash,0,sizeof(hash));
int num=candiesSize/2;
int res=0;
for(int i=0;i<candiesSize;i++)
{
if(candies[i]<0)
{
hash[candies[i]+200000]++;
if(hash[candies[i]+200000]==1)
{
res++;
}
}
else
{
hash[candies[i]]++;
if(hash[candies[i]]==1)
{
res++;
}
}
if(res>=num)
{
return num;
}
}
return res;
}
fine 我们来到了72ms现在如何进步呢?这个问题交给读者了(作者我懒的思考了)-。-!