|
发表于 2018-8-13 14:17:55
|
显示全部楼层
本楼为最佳答案
- #include<stdio.h>
- #include<stdlib.h>
- int str2set(int *lite, int length)
- {
- int i, j, temp_length = 0;
- int in_flag = 0;//1 is true, 0 is false
- int temp[length];
- for(i = 0;i < length; i++)
- {
- for(j = 0; j < temp_length; j++)
- {
- if(lite[i] == temp[j])
- {
- in_flag = 1;
- break;
- }
- }
- if(in_flag == 0)
- {
- temp[j] = lite[i];
- temp_length++;
- }
- in_flag = 0;
- }
- return temp_length;
- }
- int str2set_forsorted(int *lite, int length)
- {
- int i, max, j = 0;
- int in_flag = 0;
- int temp[length];
- max = lite[0];
- for(i = 0; i < length; i++)
- {
- if(lite[i] > max)
- {
- temp[j] = max;
- j++;
- max = lite[i];
- }
- }
- j++;
- return j;
- }
- int main()
- {
- int A[8] = {1, 2, 2, 3, 3, 4, 4, 4};
- int res;
- res = str2set_forsorted(A, 8);
- printf("The length of str2set is: %d",res);
- return 0;
- }
复制代码
str2set是没有排序的数组变成集合的函数,需要两层嵌套循环,所以时间复杂度是O(N^2)。
而至于str2set_forsorted是排序之后的数组变成集合的函数,我默认是从小到大排序了。其实这是一个打擂台找最大值/最小值的问题,一旦有新的最大/最小值就需要将其写入数组当中,并更新长度计数器。
此函数用codeblocks测试过,但是我测试的样本较少,可能对某些数组有bug,请您指出。 |
|