一道机试题

来源:互联网 发布:讲解spring源码的书籍 编辑:程序博客网 时间:2024/05/21 11:32
Given a sorted array, remove the duplicates in place such that each element appear only once
and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example, Given input array A = [1,1,2] ,

Your function should return length = 2, and A is now [1,2] .


My Method:

/*Given a sorted array, remove the duplicates in place such that each element appear only onceand return the new length.Do not allocate extra space for another array, you must do this in place with constant memory.For example, Given input array A = [1,1,2] ,Your function should return length = 2, and A is now [1,2] .*/#include<stdio.h>#include<stdlib.h>void main(){int a[4] = { 1, 1, 2, 2, };//数组样式int len = sizeof(a)/sizeof(a[0]);<span style="white-space:pre"></span>//len为数组长度int stc_len = len;int temp;for (int i = 0; i < len - 1; i++){if (a[i] == a[i + 1])for (int j = i; j < stc_len - 1; j++){a[j] = a[j + 1];stc_len--;}}printf("数组的长度为%d\n", stc_len);for (int i = 0; i < stc_len; i++)printf("%d  ", a[i]);printf("\n");system("pause");}


The Reference:
/*Given a sorted array, remove the duplicates in place such that each element appear only onceand return the new length.Do not allocate extra space for another array, you must do this in place with constant memory.For example, Given input array A = [1,1,2] ,Your function should return length = 2, and A is now [1,2] .*/#include<stdio.h>#include<stdlib.h>void main(){int a[4] = { 1, 1, 2, 2, };//数组样式int len = sizeof(a)/sizeof(a[0]);//len为数组长度int index = 0;for (int i = 1; i < len; i++){if (a[index] != a[i])a[++index] = a[i];}index++;for (int i = 0; i < index; i++)printf("%d ", a[i]);system("pause");}

运行结果:

数组的长度为21  2请按任意键继续. . .



思考???

对于无序的数组应该这么做呢???


0 0