solution.cpp 902 字节
Newer Older
每日一练社区's avatar
每日一练社区 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
static bool search(int *nums, int numsSize, int target)
{
	int lo = 0;
	int hi = numsSize - 1;
	while (lo <= hi)
	{
		int mid = lo + (hi - lo) / 2;
		if (nums[mid] == target)
		{
			return true;
		}
		if (nums[lo] == nums[mid] && nums[mid] == nums[hi])
		{
			lo++;
			hi--;
		}
		else if (nums[lo] <= nums[mid])
		{
			if (nums[lo] <= target && target < nums[mid])
			{
				hi = mid - 1;
			}
			else
			{
				lo = mid + 1;
			}
		}
		else
		{
			if (nums[mid] < target && target <= nums[hi])
			{
				lo = mid + 1;
			}
			else
			{
				hi = mid - 1;
			}
		}
	}
	return false;
}
int main(int argc, char **argv)
{
	int i;
	int target = atoi(argv[1]);
	int size = argc - 2;
	int *nums = malloc(size * sizeof(int));
	for (i = 0; i < argc - 2; i++)
	{
		nums[i] = atoi(argv[i + 2]);
	}
	printf("%d\n", search(nums, size, target));
	return 0;
}