您的位置:首页 > 其它

去掉重复的数字

2011-08-26 01:02 141 查看
题目:

请把一个整形数组中重复的数字去掉。例如:

1,   2,   0,   2,   -1,   999,   3,   999,   88

答案应该是:

1,   2,   0,   -1,   999,   3,   88

 

解法一:O(N2)

#include <stdio.h>
#include <stdlib.h>

int main() {
int a[] = {1, 2, 0, 2, -1, 999, 3, 999, 88};
int* b = (int*)malloc(sizeof(int*) * sizeof(a)/sizeof(a[0]));
int i = 0, k = 0, j = 0;
int flag = 0, size = 0;
for (; i < sizeof(a)/sizeof(a[0]); ++i) {
for (j = 0; j < k; ++j) {
if (0 == (a[i] ^ b[j])) {
flag = 1;
break;
}
}
if (0 == flag) {
b[k++] = a[i];
}
else {
flag = 0;
}
size = k;
}
for (k = 0; k < size; ++k) {
printf("%d, ", b[k]);
}
printf("\n");
return 0;
}


 解法二: O(N)

#include <iostream>
#include <math.h>

using namespace std;

typedef struct Info {
bool positive_flag_;
bool negative_flag_;
}HashTable;

int main() {
int a[] = {1, 2, 0, 2, -1, 999, -352, 3, 999, 998, 88};
int abs_max = 0;
for (int i = 0; i < sizeof(a)/sizeof(a[0]); ++i) { //求得数组中绝对值最大的数
if (abs(a[i]) > abs_max) {
abs_max = abs(a[i]);
}
}
HashTable* result = (HashTable*)malloc(sizeof(HashTable*) * (abs_max + 1));
memset(result, 0, sizeof(HashTable*) * (abs_max + 1));
HashTable item;
for (int i = 0; i < sizeof(a)/sizeof(a[0]); ++i) {
if (a[i] >= 0) {
result[a[i]].positive_flag_ = true;      //a[i]是正数置位
}
else {
result[a[i] + abs_max].negative_flag_ = true;//a[i]是负数置位
}
}

for (int i = 0; i <= abs_max; ++i) { //输出结果
if (result[i].positive_flag_) {
cout << i << " ";
}
if (result[i].negative_flag_) {
cout << i - abs_max << " ";
}
}
cout << endl;
return 0;
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  struct n2
相关文章推荐