去掉重复的数字
2011-08-26 01:02
141 查看
题目:
请把一个整形数组中重复的数字去掉。例如:
1, 2, 0, 2, -1, 999, 3, 999, 88
答案应该是:
1, 2, 0, -1, 999, 3, 88
解法一:O(N2)
解法二: O(N)
请把一个整形数组中重复的数字去掉。例如:
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; }
相关文章推荐
- 随机数字去掉重复和排序的方法
- 给定一组数字, 排列后得到的集合, 去掉重复的数, 求其和
- 请把一个整形数组中重复的数字去掉
- java 去掉重复的数字
- 明明想在学校中请一些同学一起做一项问卷调查,为了实验的客观性,他先用计算机生成了N个1到1000之间的随机整数(N≤1000),对于其中重复的数字,只保留一个,把其余相同的数去掉,不同的数对应着不同的学生的学号。然后再把这些数从
- 如何把一个整型数组中重复的数字去掉
- 华为OJ训练之0025-170108-去掉重复数字
- 创建一个包含15个随机整数(0~9)的列表,然后去掉其中的所有重复数字。
- 在一个整形数组中去掉重复的数字
- 把一个整形数组中重复的数字去掉 - 微软面试题
- java__排序后的数组删除重复数字。给定升序排序的数组,如果数组有 22 个或 22 个以上相同的数字,去掉他们,直到剩下 22 个为止。
- 遇到的比较有意思的问题(1)去掉重复数字(2)提取数组的子数组,求和最大的子数组、最大的子数组和
- (笔试题)把一个整数数组中重复的数字去掉
- 把一个整形数组中重复的数字去掉 - 微软面试题
- 去掉有序数组中重复数字 原地 leetcode java (最简单的方法)
- 去掉数组中重复的数字
- [百度]数组中去掉连续重复的数字,只保留1个
- 去掉排序数组中重复的数字
- 使用泛型去掉数组中的重复数字
- 166 请把一个整形数组中重复的数字去掉