有一个整型数组,用O(n)的算法来去掉里面重复的项目。有人知道吗? 我知道用hashtable或者位运算应该可以,但是不知道位运算代码怎么写下面是我写的用hashtable结果String数组的方案,整型一样的,不知道是否可以改进 public String[] compact(String input[]){
String output[] = new String[input.length];
int m = 0;
Hashtable hash = new Hashtable();
for (int i=0; i<output.length; i++){
if (!hash.containsKey(input[i])){
hash.put(input[i], i);
output[m]=input[i];
m++;
}
}
return output;
}
String output[] = new String[input.length];
int m = 0;
Hashtable hash = new Hashtable();
for (int i=0; i<output.length; i++){
if (!hash.containsKey(input[i])){
hash.put(input[i], i);
output[m]=input[i];
m++;
}
}
return output;
}
解决方案 »
- 请教jvm类加载一个问题
- 我想找个JAVA的工作(北京),各位兄弟帮帮我啊,如果你们的公司缺人的话介绍我进去,我给你5000分!!
- 请问我想看看println的源代码在哪儿能找到,歇歇了!!!!
- 请问如何用jTable更新数据库(Swing和hibernate)
- 难道就没有人知道吗?????
- 求助List的add()方法
- 怎样学好JAVA
- help about windows printer
- java获取CPU利用率时报错,大神们,帮帮忙
- 新手,问下简单计算机面板的问题。。
- 为什么明明没有超出heap的界限,却报OutOfMemoryException : java heap space
- 开发平台的选择及比较
template<class T>
void UniqueArray(T *array,int &len){
int i,j,k;
for(i=0;i<len;i++)
for(j=i+1;j<len;j++)
if(array[i]==array[j])
{
for(k=j;k<len;k++)
array[k]=array[k+1];
len--;
j--;
}
}另一种是:#include <stdio.h >
#include <stdlib.h > int main(int argc, char *argv[])
{
int array[] = {1, 2, 0, 2, -1, 999, -1, 3, 999, 88};
int len = sizeof(array)/sizeof(array[0]);
int i,j;
for (i=0; i <len; i++)
{
for (j=i+1; j <len; j++)
{
if (array==array[j])
{
len--;
array[j] = array[len];
}
}
}
for (i=0; i <len; i++)
{
printf ("%d ",array);
}
system("PAUSE");
return 0;
}
不需要这个判断的
if (!hash.containsKey(input[i])){改成 if (hash.get(input[i])==null){ 简单多了!!
public static String removeRepeat(String str){
String temp = "";
for(int i = 0 ; i<str.length(); i++){
char tempChar = str.charAt(i);
if(temp.indexOf(tempChar)==-1){
temp = temp+tempChar;
}
}
return temp;
}
#define INVALID 999999
#include <memery.h>
#define INVALID 999999
int src[100];int unique(int n, int* src, int* ans)
{
int i,j;
int* tmp;
tmp = (int*)malloc(n*sizeof(int*));
memset(tmp,INVALID,n*sizeof(int));
for(i = 0; i < n; i++)
{
if(*(tmp+*(src+i)) == INVALID)
*(tmp+*(src+i) = *(src+i);
}
j = 0;
for(i = 0; i < n; i++)
{
if(*(tmp + i) != INVALID)
*(ans+j++) = *(tmp + i);
}
return j;
}