2019.11.21 做OJ题的反思

1.利用二分法查找数组元素(适用于有序数组)

  

 1 #include<stdio.h>
 2 int BinarySearch(int a[],int n,int key);
 3 int arr[2000050];
 4 
 5 int main(void)
 6 {
 7     int n,m,i;
 8     int num;
 9     
10     scanf("%d%d",&n,&m);
11     for(i=0;i<n;i++)
12     {
13         scanf("%d",&arr[i]);
14     }
15     for(i=1;i<=m;i++)
16     {
17         scanf("%d",&num);
18         printf("%d",BinarySearch(arr,n,num));
19          if(i==m) printf("\n");
20          else printf(" ");
21     }
22     return 0;
23 }
24 int BinarySearch(int a[],int n,int key)
25 {
26     int left=0,right=n-1;
27     int middle,i=0;
28     while(left<=right)
29     {
30         middle=(left+right)/2;
31         if(a[middle]>key)
32             right=middle-1;
33         if(a[middle]<key)
34             left=middle+1;
35         if(a[middle]==key)
36             return middle;
37     }
38     return -1;
39 }

 PS:对于二分法查找问题,主要是寻找key值所在的区域,逐步缩小查找的范围,以提高查找效率。对于一些比较大的有序数组的时候,如果使用数组遍历的方式,那么效率肯定很低下了。如何缩小范围,即利用left与right的重新赋值来达到目的。这种题目最好先自己演算一遍,找到查找的规律,从特殊到一般。

2.利用计数方法来解决简单的括号匹配问题

 1 #include<stdio.h>
 2 int main(void)
 3 {
 4     char ch[105];
 5     int i=0;
 6     int count=0;
 7     int flag=1;
 8     
 9     scanf("%s",ch);
10     while(ch[i]!='\0')
11     {
12         if(ch[i]=='(') count++;
13         if(ch[i]==')'&&count==0)
14         {
15             printf("parentheses do not match!\n");
16             return 0;    
17         }
18         if(ch[i]==')'&&count!=0) count--;
19         i++;
20     }
21     if(count==0) 
22         printf("parentheses match!\n");
23     else
24         printf("parentheses do not match!\n");    
25         
26     return 0; 
27 }

 PS: 对于括号匹配问题,注意建立模型。什么时候是匹配成功,什么时候是匹配失败。显然最终左右括号数必定相等,且在字符串中,当左右括号数等的时候,必定是先出现左括号。所以依据此可以建立两个条件。

3.字符数组的使用

 1 #include<stdio.h>
 2 int main(void)
 3 {
 4     char ch[105];
 5     int arr[52];
 6     char ch1[52]={[0]='A',[26]='a'};
 7     int i=0,j=0;
 8 
 9     scanf("%s",ch);
10     for(j=0;j<52;j++)
11         arr[j]=0;
12     for(j=1;j<52;j++)
13     {    if(j<=25)
14             ch1[j]=ch1[j-1]+1;
15         if(j>=27) 
16             ch1[j]=ch1[j-1]+1;
17     }    
18     while(ch[i]!='\0')
19     {
20         if(ch[i]<='Z'&&ch[i]>='A')
21             arr[ch[i]-'A']++;
22         if(ch[i]<='z'&&ch[i]>='a')
23             arr[ch[i]-'A'-6]++;        
24         i++;
25     }
26     for(j=0;j<52;j++)
27     {
28         if(arr[j]!=0)
29             printf("The character %c has presented %d times.\n",ch1[j],arr[j]);
30     } 
31     
32     return 0; 
33 }

PS:在我的思路中,我忽略了大写字母与小写字母的ASCLL码(美国信息交换标准代码)之间还有一些表示符号。

  

     'Z'的ASCLL码为90,而'a'的ASCLL码为97,其中还有6个ASCLL码表示一些特殊符号。

   这一特点使我的代码在一开始时WA(wrong anwser)了,好坑~~~

猜你喜欢

转载自www.cnblogs.com/ziyang1060/p/11904149.html