`

去除数组中的重复数据

阅读更多
    今看到一个小题目,,要求前提是不允许使用util包以及之外的类,即任何集合类都不允许使用。 写出的算法效率越高,此题得分越高,大家可以试一下。题目是输入一串已经排序好的数组,输出消除重复数之后的数组。例如:
输入{ 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5 };输出{ 1, 2, 3, 4, 5 };

看了下,,写个算法转化为字符串的操作。
public static void main(String[] args) {
		// TODO Auto-generated method stub
	  
		int[] a = {-1,0, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5 };
		StringBuffer source=new StringBuffer();
		for(int i:a){
			source.append(i);
			source.append(",");
		}
		String temp;
		String sList=source.toString();
		System.out.println(sList);
		StringBuffer sb=new StringBuffer();
//		System.out.println(sList.substring(0,sList.indexOf(",")));
		while(sList.length()>0){
			temp=sList.substring(0,sList.indexOf(","));
			sb.append(temp);
			sb.append(",");
			sList=sList.replace(temp+",", "").trim();
		}
		
		System.out.println(sb.toString());
		
	}


   大家有什么好的策略,请赐教。。
分享到:
评论
2 楼 gbfd2012 2011-08-09  
x19881216 写道
	public static void main(String[] args) {
		int[] a = { -1,0, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5 };
		int b = a[0];
		int i = 1;

		for (int d : a) {
			if (d > b) {
				b = d;
				a[i] = b;
				i++;
			}
		}

		int[] e = new int[i];

		for (int j = 0; j < i; j++) {
			e[j] = a[j];
		}

		System.out.println(Arrays.toString(e));
	}

不借助任何工具类

好啊。
1 楼 x19881216 2011-08-09  
	public static void main(String[] args) {
		int[] a = { -1,0, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5 };
		int b = a[0];
		int i = 1;

		for (int d : a) {
			if (d > b) {
				b = d;
				a[i] = b;
				i++;
			}
		}

		int[] e = new int[i];

		for (int j = 0; j < i; j++) {
			e[j] = a[j];
		}

		System.out.println(Arrays.toString(e));
	}

不借助任何工具类

相关推荐

Global site tag (gtag.js) - Google Analytics