1. 16.15. 珠玑妙算
16.15. 珠玑妙算
分析:先找猜中,有即将solution和guess都置为0,再找伪猜中,同样找到即置为0.
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* masterMind(char* solution, char* guess, int* returnSize){
int count_ture=0;
int count_fake=0;
for(int i=0;i<4;i++)
{
if(solution[i]==guess[i])
{
count_ture++;
solution[i]='0';
guess[i]='0';
}
}
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
if(guess[i]==solution[j] && guess[i]!='0')
{
count_fake++;
solution[j]='0';
guess[i]='0';
}
}
}
int* ret=malloc(sizeof(int)*2);
*returnSize=2;
ret[0]=count_ture;
ret[1]=count_fake;
return ret;
}
2. 485. 最大连续 1 的个数
485. 最大连续 1 的个数
分析:计算连续出现1的次数,遇见0将计数器置为0,并保留次数的最大值。
int findMaxConsecutiveOnes(int* nums, int numsSize){
int count=0;
int max=0;
for(int i=0;i<numsSize;i++)
{
if(nums[i]==1)
{
count++;
}
else
{
max=fmax(max,count);
count=0;
}
}
max=fmax(max,count);
return max;
}
3. HJ31 单词倒排
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
void swap(char* left, char* right)
{
while (left < right)
{
char tmp = *left;
*left = *right;
*right = tmp;
left++;
right--;
}
}
int main() {
char arr[10000] = { 0 };
gets(arr);
swap(arr, arr + strlen(arr) - 1);
char* cur = arr;
while (*cur != '\0')
{
char* right = cur;
while ((*right <= 'z' && *right >= 'a') || (*right <= 'Z' && *right >= 'A'))
{
right++;
}
swap(cur, right - 1);
if (*right != '\0')
{
*right = ' ';
cur = right + 1;
}
else
{
cur = right;
}
}
printf("%s\n", arr);
return 0;
}