消除重复数

 

问题描述: 这是一道外企算法的面试题,前提是不允许使用util包中任何类,即任何集合类都不允许使用。 写出的算法效率越高,此题得分越高,大家可以试一下。题目是输入一串已经排序好的数组,输出消除重复数之后的数组。如:
输入{ 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5 };输出{ 1, 2, 3, 4, 5 };

 

算法实现1:

/**
 * Copyright (c) 2011 Trusted Software and Mobile Computing(TSMC)
 * All rights reserved.
 * Author: Jarg Yee <yeshaoting@gmail.com>
 * http://jarg.iteye.com/
 */

/*
 * 
 */
public class Distinct2
{
	public static void main(String[] args)
	{
		int[] arr = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5};
		int[] arr2 = new int[arr.length];

		System.out.print("结果集:");
		int count = 0;		//记录结果集中元素数
		for(int i=0; i<arr.length; i++)
		{
			//第一次或者当前值不存在队列的情况
			if(i==0 || arr2[count-1]!=arr[i])
			{
				System.out.print(arr[i] + "\t");
				arr2[count++] = arr[i];
			}
		}
	}

}

 

 

 

算法实现2:

/**
 * Copyright (c) 2011 Trusted Software and Mobile Computing(TSMC)
 * All rights reserved.
 * Author: Jarg Yee <yeshaoting@gmail.com>
 * http://jarg.iteye.com/
 */

/*
 * 消除重复数(已经排序好的数组)
 * 采用队列的思想,将非重复的元素放入到队列中
 * 记录所存元素开始和结束的索引,据此输出结果
 */
public class Distinct
{
	private static int[] arr = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5};
	private Queue q = new Queue();
	
	//内部类 - 队列类
	class Queue
	{
		int front = 0, rear = 0;	//分别表示队首,队尾
		int[] queue = new int[arr.length];

		//判断队列是否为空
		public boolean isEmpty()
		{
			if(rear-front == 0)
				return true;
			return false;
		}

		//出队(不判断队列是否为空)
		public int deQueue()
		{
			return queue[front++];
		}

		//入队
		public void enQueue(int element)
		{
			queue[rear++] = element;
		}

		//获取队尾元素
		public int getQueueRear()
		{
			return queue[rear-1];
		}

		//输出队列元素
		public void display()
		{
			System.out.print("结果集:");
			for(int i=front; i<rear; i++)
			{
				System.out.print(deQueue() + "\t");
			}
		}
	}
	
	/** for debugging. */
	public static void main(String[] args)
	{
		Distinct obj = new Distinct();
		int current;
		for(int i=0; i<arr.length; i++)
		{
			current = arr[i];
			//第一次或者当前值不存在队列的情况
			if(i==0 || obj.q.getQueueRear()!=current)
			{
				obj.q.enQueue(current);
			}
		}
		obj.q.display();
	}
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值