标签:style color java os io strong for ar
每个测试案例包括两行:
第一行有1个整数n,表示数组的大小。1<=n <= 10^6。
第二行有n个整数,表示数组元素,每个元素均为int。
第三行有1个整数m,表示接下来有m次查询。1<=m<=10^3。
下面有m行,每行有一个整数k,表示要查询的数。
81 2 3 3 3 3 4 513
4
代码:
/* 数字在排序数组中出现的次数 by Rowandjj 2014/8/17 */ #include<stdio.h> #include<stdlib.h> int GetTimes(int arr[],int len,int target) { if(arr == NULL || len <= 0) { return 0; } int low = 0,high = len-1; while(low <= high) { int mid = low + ((high-low)>>1); if(arr[mid] == target) { int count = 1; int i; for(i = mid-1;i >= 0; i--) { if(arr[i] != target) { break; } count++; } for(i = mid+1; i <= len; i++) { if(arr[i] != target) { break; } count++; } return count; }else if(arr[mid] > target) { high = mid-1; }else { low = mid+1; } } return 0; } int main() { int n; while(scanf("%d",&n) != EOF) { int *arr = (int *)malloc(n*sizeof(int)); if(arr == NULL) exit(EXIT_FAILURE); int i; for(i=0;i<n;i++) scanf("%d",arr+i); int m; scanf("%d",&m); for(i=0;i<m;i++) { int k; scanf("%d",&k); printf("%d\n",GetTimes(arr,n,k)); } free(arr); arr = NULL; } return 0; }
#include<stdio.h> #include<stdlib.h> int GetFirstN(int arr[],int len,int target) { if(arr == NULL || len<=0) { return -1; } int low = 0,high = len-1; while(low <= high) { int mid = low + ((high-low)>>1); if(arr[mid] == target) { if(mid == 0 || arr[mid-1] != target) { return mid; }else { high = mid-1; } }else if(arr[mid] > target) { high = mid-1; }else { low = mid+1; } } return -1; } int GetLastN(int arr[],int len,int target) { if(arr == NULL || len <= 0) { return -1; } int low = 0,high = len-1; while(low <= high) { int mid = low + ((high-low)>>1); if(arr[mid] == target) { if(mid == len-1 || arr[mid+1] != target) { return mid; }else { low = mid+1; } }else if(arr[mid] > target) { high = mid-1; }else { low = mid+1; } } return -1; } int GetTimes(int arr[],int len,int target) { if(arr == NULL || len <= 0) { return 0; } int t1 = GetFirstN(arr,len,target); int t2 = GetLastN(arr,len,target); if(t1 !=-1 && t2 != -1) { return t2-t1+1; }else { return 0; } } int main() { int n; while(scanf("%d",&n) != EOF) { int *arr = (int *)malloc(n*sizeof(int)); if(arr == NULL) exit(-1); int i; for(i=0;i<n;i++) scanf("%d",arr+i); int m; scanf("%d",&m); for(i=0;i<m;i++) { int k; scanf("%d",&k); printf("%d\n",GetTimes(arr,n,k)); } free(arr); arr = NULL; } return 0; }
标签:style color java os io strong for ar
原文地址:http://blog.csdn.net/chdjj/article/details/38640697