// 判断是否为质数
bool isPrime(int num){
if (num < 2) return false;
int i;
for(i = 2; i * i <= num; i++) {
if (num % i == 0) return false;
}
return true;
}
int getOneCount(int num){
int count = 0;
while (num != 0) {
num &= (num - 1);
count++;
}
return count;
}
// 算出含有1的个数m,m是否为素数
int countPrimeSetBits(int L, int R){
int i,num,count = 0;
for (i = L; i <= R; i++) {
num = getOneCount(i);
if (isPrime(num)) count++;
}
return count;
}
运行效率如下所示:
第2题:消失的数字 试题要求如下:
回答(C语言):
int missingNumber(int* nums, int numsSize){
int i=0;
int* data_buf=(int*)malloc(sizeof(int)*(numsSize+1));
memset(data_buf,0,sizeof(int)*(numsSize+1));
for(i=0;i<numsSize;i++){
data_buf[nums[i]]++;
}
for(i=0;i<numsSize;i++){
if(data_buf[i]==0){
break;
}
}
data_buf[numsSize]='\0';
return i;
}
运行效率如下所示:
第3题:最小绝对差 试题要求如下:
回答(C语言):
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
int cmp(const void* num, const void* num2){
return *(int*)num - *(int*)num2;
}
int** minimumAbsDifference(int* arr, int arrSize, int* returnSize, int** returnColumnSizes){
qsort(arr,arrSize,sizeof(int),cmp);
int **returnarra = malloc(sizeof(int*)*arrSize), count = 0;
int *ColumnSizes = (int*)malloc(sizeof(int)* arrSize);
assert(returnarra!=NULL && ColumnSizes!=NULL);
int different, min = abs(arr[0]-arr[arrSize-1]);
for(int i = 1; i < arrSize;i++){
if((different = abs(arr[i] - arr[i-1])) < min){
min = different;
}
}
for(int i = 1; i < arrSize; i++){
different = abs(arr[i] - arr[i-1]);
if(different == min){
int *pair = malloc(sizeof(int) * 2);
pair[0] = arr[i-1];
pair[1] = arr[i];
returnarra[count] =pair;
ColumnSizes[count++] = 2;
}
}
*returnSize = count;
*returnColumnSizes = ColumnSizes;
return returnarra;
}
运行效率如下所示:
第4题:按奇偶排序数组II 试题要求如下:
回答(C语言):
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* sortArrayByParityII(int* A, int ASize, int* returnSize){
//int* arr = (int*)malloc(sizeof(int) * ASize);
*returnSize = ASize;
int odd = 1;
for (int i = 0; i < ASize; i += 2) {
if (A[i] % 2 != 0) {
while (A[odd] % 2 == 1) {
odd += 2;
}
int tmp = A[odd];
A[odd] = A[i];
A[i] = tmp;
}
}
return A;
}
运行效率如下所示:
第5题:主要元素 试题要求如下:
回答(C语言):
int majorityElement(int* nums, int numsSize){
int cur;
int counter = 0;
for (int i = 0; i < numsSize; i++) {
if (counter == 0) {
counter = 1;
cur = nums[i];
} else if (cur != nums[i]) {
counter--;
} else {
counter++;
}
}
if(counter > 0)
return cur;
else
return -1;
}
运行效率如下所示:
第6题:逐步求和得到正数的最小值 试题要求如下:
回答(C语言):
int minStartValue(int* nums, int numsSize)
{
int min = nums[0], count = 0;
for (int i = 0; i < numsSize; i ++)
{
count += nums[i];
min = min < count ? min : count;
}
min = 1 - min;
return min > 0 ? min : 1;
}