线性枚举例题
Posted 影中人lx
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线性枚举例题相关的知识,希望对你有一定的参考价值。
题目1:
int isevenbit(int num)
{
int cnt=0;
while(num)
{
num=num/10;
cnt++;
}
return (cnt%2==0);
}
int findNumbers(int* nums, int numsSize)
{
int ret=0;
for(int i=0;i<numsSize;i++)
{
if(isevenbit(nums[i]))
{
ret++;
}
}
return ret;
}
题目2:
int singleNonDuplicate(int* nums, int numsSize)
{
for(int i=1;i<numsSize;i++)
{
nums[0]=nums[0]^nums[i];
}
return nums[0];
}
题目3:
//模拟快速排序的思想,利用左右指针
int* exchange(int* nums, int numsSize, int* returnSize)
{
int left=0;
int right=numsSize-1;
while(left<right)
{
while(left<right)
{
if(nums[left]%2!=0)
left++;
else
break;
}
while(left<right)
{
if(nums[right]%2!=1)
right--;
else
break;
}
int tmp=0;
tmp=nums[left];
nums[left]=nums[right];
nums[right]=tmp;
left++; //进行下一次
right--; //进行下一次
}
*returnSize=numsSize;
return nums;
}
题目4:
//数列和=左边和*2+中间位置值
int findMiddleIndex(int* nums, int numsSize)
{
int total = 0;
for (int i = 0; i < numsSize; ++i)
{
total += nums[i];
}
int sum = 0;
for (int i = 0; i < numsSize; ++i)
{
if (2 * sum + nums[i] == total)
{
return i;
}
sum += nums[i];
}
return -1;
}
题目5:
int pivotIndex(int* nums, int numsSize)
{
int total=0;
for(int i=0;i<numsSize;i++)
{
total+=nums[i];
}
int sum=0;
for(int j=0;j<numsSize;j++)
{
if(sum*2+nums[j]==total)
{
return j;
}
sum+=nums[j];
}
return -1;
}
题目6:
//双指针
/快慢指针;块指针遍历数组,慢指针改变数组
int removeDuplicates(int* nums, int numsSize)
{
if (numsSize == 0)
{
return 0;
}
int fast = 1, slow = 1;
while (fast < numsSize)
{
if (nums[fast] != nums[fast-1])
{
nums[slow] = nums[fast];
slow++;
}
fast++;
}
return slow;
}
题目7:
bool* prefixesDivBy5(int* nums, int numsSize, int* returnSize) {
*returnSize = numsSize;
bool* answer = malloc(sizeof(bool) * numsSize);
int sum = 0;
for (int i = 0; i < numsSize; i++)
{
sum = ((sum<< 1) + nums[i]) % 5;
if(sum==0)
answer[i]=1;
else
answer[i]=0;
}
return answer;
}
题目8:
int smallestRepunitDivByK(int k)
{
if(k%2==0||k%5==0)
{
return -1;
}
int cnt=1;
int x=1;
while(x%k!=0)
{
x=(x*10+1)%k;
cnt++;
}
return cnt;
}
题目9:
bool checkZeroOnes(char * s)
{
int len=strlen(s);
int cnt1=0;
int cnt2=0;
int sum1=0;
int sum2=0;
for(int i=0;i<len;i++)
{
if(s[i]=='1')
{
cnt2++;
sum2=0;
if(cnt2>cnt1)
{
cnt1=cnt2;
}
}
if(s[i]=='0')
{
sum2++;
cnt2=0;
if(sum2>sum1)
{
sum1=sum2;
}
}
}
return cnt1>sum1?true:false;
}
以上是关于线性枚举例题的主要内容,如果未能解决你的问题,请参考以下文章