第一个只出现一次的字符,josephus环,最大子数组和

时间:2021-04-30 14:54:46
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXINT 0x7fffffff
#define MININT 0X80000000
//字符串中第一个只出现一次的字符
char firstSingle(char *str)
{
int a[255];
memset(a, 0, 255 * sizeof(int));
char *p = str;
while (*p != '\0'){
++a[*p];
++p;
}
p = str;
while (*p != '\0'){
if (a[*p] == 1) return *p;
++p;
}
return '\0';
}
//josephus问题 f(n,m)=(f(n-1,m)+m)%n,迭代求解最后一个数的原始数
int joseph(int n, int m)
{
int fn = 0;
for (int i = 2; i <= n; ++i)
fn = (fn + m) % i;
return fn;
} //最大子数组和
int maxSubArraySum(int *a, int n, int &b, int &e)
{
int p, sum, maxSum;
p = sum = 0;
maxSum = MININT;
for (int i = 0; i < n; ++i){
if (sum < 0){
sum = a[i];
p = i;
}
else sum += a[i];
if (sum > maxSum){
maxSum = sum;
b = p;
e = i;
}
}
return maxSum;
}
int main()
{
char str[] = "abaccdeff";
printf("%c\n", firstSingle(str));
printf("%d\n", joseph(5, 3));
int a[] = { 13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7 };
int len, b, e;
len = maxSubArraySum(a, 16, b, e);
printf("the maxSubArray is :\n");
for (int i = b; i <= e; ++i)
printf("%d\t", a[i]);
printf("\nthe maxSubArraySum is : %d\n", len);
}